Securing and Optimizing Linux RedHat Edition -A Hands on Guide Wolf openNA logo Gerhard Mourani Open Network Architecture www.openna.com              gmourani@openna.com              gmourani@netscape.net               Madhu "Maddy" Copyright © 2000 by Gerhard Mourani and OpenDocs, LLC. Copyright © 2000 by Madhusudan (Madhu "Maddy") XML Source This version and its subsequent outputs whether be it HTML, PDF or any other derivatives can be distributed under the same licensing terms and conditions as the orginal Securing and Optimizing Linux i.e. as set forth in the Open Publication License; V1.0 or later, the latest version is presently available at www.opencontent.org/openpub/. Please note even if i madhusudan (Madhu "Maddy"), hold the copyright for the XML source(Markup), you still need to get permission from Gerhard Mourani the orginal author of Securing and Optmising Linux, to make any changes to the content of this book. Please do read the licensing terms and conditions detailed below for additional information This material may be distributed only subject to the terms and conditions set forth in the Open Publication License; V1.0 or later, the latest version is presently available at www.opencontent.org/openpub/. Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder. Distribution of the work or derivative of the work in any standard (paper) book form for commercial purposes is prohibited unless prior permission is obtained from the copyright holder. Please note even if I, Gerhard Mourani have the copyright, I don't control commercial printing of the book. Please contact OpenDocs @www.opendocspublishing.com/ if you have questions concerning such matters. The logos, trademarks, symbols used in this book are properties of their respective compan(y)ies. ----------------------------------------------------------------------------- Table of Contents Preface 1. Why did i write this book? 2. Why fiddle? 3. DocBook ! 4. DocBook/XML 1. Getting Started 1. Introduction 2. Installation 2. Overview of OS Linux 3. Installation of your Linux Server 4. Post-Install 3. Security, Optimization and Upgrade 5. General System Security 6. Linux General Optimization 7. Configuring and Building a Secure, Optimized Kernel 4. Networking -Management, Firewall, Masquerading and Forwarding 8. TCP/IP -Network Management 9. Files -Networking Functionality 10. Networking -Firewall 11. The firewall scripts files 12. Networking Firewall -Masquerading and Forwarding 5. Software -Security 13. Linux -The Compiler functionality 14. Software -Security/Monitoring 6. Software -Networking 15. Software -Securities 16. Software -Securties(commercial) 17. Software -Securities/System Integrity 18. Linux Tripwire ASR 1.3.1 19. Software -Securities/Management & Limitation 20. Set Limits using Qouta 21. Software -Networking 22. Software -Server/Mail Network 23. Linux IMAP & POP Server 24. Software -Networking/Encryption 25. Linux FreeS/WAN VPN 26. Linux OpenLDAP Server 27. Linux PostgreSQL Database Server 28. Software -Server/Proxy Network 29. Software -Network Server, web/Apache 30. Optional component to install with Apache 31. Software -Server/File Sharing-Network 32. Linux FTP Server 7. Backup and Restore 33. Why's and When's of Backup and Restore I. Appendixes A. Resources B. Tweaks, Tips and Administration tasks C. Obtaining Requests for Comments (RFCs) List of Tables 3-1. Sample representaion of partitions 33-1. Dump scheme List of Examples 3-1. Starting and Stopping various Daemon's 5-1. Export file systems using NFS 5-2. Disable console-equivalent access 5-3. Print log reports 5-4. Use man pages 5-5. Use find to find 6-1. For 128 MB of RAM 7-1. SMP support 8-1. Two ISA ethernet cards 12-1. rc.firewall.blocked 13-1. Using tar 15-1. Remote login using ssh 15-2. scp Secure Copy utility 15-3. local to remote 16-1. login to a remote using ssh2 16-2. sftp2, Secure File Transfer 18-1. Usage of Tripwire 19-1. Importing using gpg 19-2. Signing key 19-3. Encrypting 19-4. Decrypting 20-1. usrquota 20-2. grpquota 21-1. dnsquery 21-2. Look up host names 21-3. Using host 21-4. List a complete domain 22-1. Overriding RBL 22-2. Alternative names 22-3. sendmail.cf 26-1. my-data-file 26-2. LDMB backend 26-3. modifyentry 26-4. Address Book 30-1. Using Netscape browser 33-1. Backup directory of a week 33-2. scp SSH command 33-3. scp SSH command ----------------------------------------------------------------------------- Preface 1. Why did i write this book? When I began writing this book, the first question I asked myself was how to install Linux on a server, and be sure that no one from the outside, or inside, could access it without authorization. Then I wondered if any method similar to the one on Windows® exists to improve the computers performance. Subsequently, I began a search on the Internet and read several books to get the most information on security and performance for my server. After many years of research and studies I had finally found the answer to my questions. These answers were found, all scattered throughout different documents, books, articles, and Internet sites. I created documentation based on my research that could help me through my daily activities. Through the years, my documentation grew and started to look more like a book and less like simple, scattered notes. I decide to publish it on the Internet so that anyone could take advantage of it. By sharing this information, I felt that I was doing my part for the community who answered so many of my computing needs with one magical, reliable, strong, powerful, fast and free operating system named Linux. I had received a lot of feedback and comments about my documentation, which helped to improve it over time. ----------------------------------------------------------------------------- 2. Why fiddle? Madhu "Maddy" Is there a need to fiddle with what apparently is perfectly working and is serving the need. Well for one the i have choosen a format, XML, unlike the original manuscript which was written in word, in this case has the advantage of source being one and output can be in various format. That is if the source is in XML, it is easier now to convert into HTML, PDF, RTF etc. Also to prove to the sceptics that DocBook is very much suitable for large production quality projects, not that this is the first effort, in this case an entire book has been marked up in XML. Infact why XML indeed? XML -eXtensible Markup Language has been able to do justice to a large extent to the hype. Maybe having a watch body like w3.org to monitor has been advantageous; unlike HTML which lacked a formal monitoring, ability to extend, a weak structure and no support for validation, XML has all these and more. It is a system-independant, vendor-independant and has behind it the proven experience of SGML implementation, XML being a subset of SGML. I concur with Tim Bray's reported comment that it is ridiculous to use an application like MS Word, Quark Express etc.for writing text which will be stored as a binary and proprietory format therby bloating it considerably. And unlike HTML which has about aprox. 50-60 pre-cooked tags, with XML one can make up one's own. Infact this facility of having one's own tag will make it very, very useful in the long run. And the inherent factor that XML is all about content and nothing to do with presentation will be its greatest strength for years to come. The presentation part is taken care of by Stylesheet or FO or some such thing. ----------------------------------------------------------------------------- 3. DocBook ! DocBook is a DTD - Document Type Definition. now what is this? well say for example having said XML is in itself a rule set , suppose i use an markup element tag in my document and another author uses element tag in his document, isn't it true we are trying to convey the same meaning .Imagine thousands of pages are being written for the web, for the publishing industry and what a waste of enormous time if people would like to convey similar meaning but use different elements with the core language being same, this is where an DTD comes into picture.   Docbook DTD is a very popular set of tags for describing books,   articles and other prose documents, particularly technical documentation. Docbook is defined using the native DTD syntax of SGML and XML. Like HTML, DocBook is an example of a markup language defined in SGML/XML. ---From the book DocBook - The Definitive Guide by Norman Walsh and Leonard Muellner.   ----------------------------------------------------------------------------- 4. DocBook/XML With the sole intent of making this book future proof, I have ported ( i am not sure this is the right term) this entire book into DocBook/XML.That the source being Markedup in XML, this ensures:   *  It will become platform independant and the source is not in any proprietory format like word.   *  It will be easy to have different outputs like HTML, PDF, RTF etc. With the never version of browsers supporting Raw XML as input with stylesheet being a seperate component, that this remains ready for that day when it becomes possible to have it converted on the fly.   *  That in the eventuality of me not being involved in the project at a later date, with the advent of professionals, there will be enough warm bodies to do this job. My fond hope is that this should not turn out be just a futile excersize and it proves usefull to everybody; atleast to some people even they are a small minority, the least of all to Gerhard Mourani, who is the author of this splendid book. ----------------------------------------------------------------------------- 4.1. Bouquets Brickbats Etc. The idea behind this exercize primarily has been :   *  To give back something to the Linux community which has been instrumental in spearheading the spirit of sharing.   *  To create awareness about possibilities existing with the available tools set. But in the process some mistakes might have creeped in but there can be no excuse. Since this book has been looked at twice over; but still, i think the mistakes are entirely mine, if at all and not Gerhard's. So if you spot some glaring mistakes whether be it in the form of wrong or mis-information, typos or grammatical mistakes please do inform me at or you can even inform gerhard at . I am sure he will give a wallop on my backside( it is quite fragile!) so that such mistakes don't happen next time. Also welcome are the suggestions on how we could improve on this, so that next time round it will much be better. Here is hoping that this proves useful despite those already mentioned, creeped in mistakes, errors etc. and it kindles in you the same spirit which has embodied the growth of Linux as a powerful environement to work in. And if that happens i would consider myself highly obliged and this will prove to be a satisfying endevour for me personally. I have a feeling that the orginal author of this book Gerhard Mourani shares this thought of mine and probably agrees with me. 1. Getting Started Owl Table of Contents 1. Introduction 1.1. Audience 1.2. Organization of This Book 1.3. Pre-requisites 1.4. Obtaining the book and example configuration files 1.5. Acknowledgements from Gerhard ----------------------------------------------------------------------------- Chapter 1. Introduction I realized that a lot of people wanted to see it published for its contents, to get advantages out of it and see the power of this beautiful Linux system in action. A lot of time and effort went into the making of this book, and to ensure that the results were as accurate as possible. If you find any abnormalities, inconsistent results, errors, omissions or anything else that doesn't look right, please let me know so I that can investigate the problem or correct the error. Suggestions for future versions are also welcome and appreciated. ----------------------------------------------------------------------------- 1.1. Audience This book is intended for a target audience of technical and system administrators who manage Linux servers, but it also includes enough material for home users and others. It discusses how to install and setup a Red Hat Linux Server with all the necessary security and optimization for a high performance Linux specific machine. Since we speak of optimization and security configuration, we have used only source distribution (tar.gz) programs; the most available type for critical server software, like Apache, BIND/DNS, Samba, Squid, OpenSSL etc. Source packages give us fast upgrades, security updates when necessary, and a better compilation, customization, and optimization option for our specific machines that often we can't have with RPM packages. ----------------------------------------------------------------------------- 1.2. Organization of This Book Depending of your level of knowledge in Linux, you can read this book from the start to finish or each chapter which may be of interest to you. Each chapter and section of this book appears in a manner that let you read only the relevant parts of your interest without the need to schedule a couple of day's reading. Too many books available as of now take two pages to explain something that can be explained in two lines, I'm sure that many of you agree with my opinion. This book attempts a different path, in the sense, only the essential and important information that the readers are interested in knowing are explained in detail thereby eliminating all the nonsense. Though the fact that you can read this book in any order you want, there is a particular order that you could follow if something seem to be confusing for you. The steps shown below is what I recommend to facilitate a smooth reading. Chapter 2 through Chapter 4 will guide you to do these steps: i. Setup Linux in your computer ii. Remove all the unnecessary RPM package(s) during setup iii. Install the necessary RPM package(s) for compilation Chapter 5 through Chapter 7 will guide you with these additional steps: iv. Secure the system in general v. Optimize the system in general vi. Install, recompile and customize the Kernel   *  Chapter 24 will guide you through this: vii. Install OpenSSL to be able to use encryption with the Linux server   *  Chapter 15 will guide you through this: viii. Install OpenSSH to be able to make remote administration tasks   *  Chapter 21 will guide you through this: ix. Install BIND/DNS as client or server depending of your needs   *  Chapter 22 will guide you through this: x. Install Sendmail as client or server depending of your needs   *  Chapter 10 through Chapter 12 will guide you through these steps: xi. Install & Configure the firewall script according to which services are installed in your system   *  Chapter 17 and Chapter 18 should guide you through this step: xii. Install Tripwire Now for this step you will need to go through the book section wise to choose what you want. xiii. Install any software you need later. ----------------------------------------------------------------------------- 1.3. Pre-requisites These installation instructions assume that: You have a CD-ROM drive on your computer and the Official Red Hat Linux CD-ROM. Installations were tested on the Official Red Hat Linux version 6.1 and 6.2. You should understand the hardware system on which the operating system will be installed. After examining the hardware, the rest of this document guides you, step-by-step, though the installation process. +---------------------------------------------------------------------------+ | About products mentioned in this book: | | | | Many products, mentioned in this book; some commercial, but most are not | | commercial, cost nothing and can be freely used or distributed. It is | | also important to say that I'm not affiliated with any of them and if I | | mention a tool, because it is useful. You will find that a lot of big | | companies in their daily use, use most of them. | +---------------------------------------------------------------------------+ ----------------------------------------------------------------------------- 1.4. Obtaining the book and example configuration files Securing and Optimizing Linux: RedHat Edition is now also available to download around the most popular Linux web sites. Free formatted versions of this book can be found on the Internet via the following addresses listed below. From the original web site Open Network Architecturewww.openna.com The Linux Documentation Project homepage: www.linuxdoc.org O'Reilly Network: oreilly.linu.com/pub/d/25 Linux Security portal linuxsecurity.com/docs On the other hand you like the nice feel of paper and would like to browse through the pages at your convenience, you will have to purchase it. By clicking here! You can Buy here! It also comes with an accompanying CD filled with some nice goodies and all the example configuration files. Other related web sites may exist without my knowledge. If you host this book Securing and Optimizing Linux: RedHat Edition and want to be included in the list of the next release, please send me a message with your intentions. If you receive this as part of a printed distribution or on a CD-ROM, please check out the Linux Documentation home page www.linuxdoc.org/ or the original website at www.openna.com to see if there is a more recent version. This could potentially save you a lot of trouble. If you want to translate this book, please notify me so I can keep track of what languages I have been published in. ----------------------------------------------------------------------------- 1.4.1. Example Configuration files The example configuration files in this book are available electronically via http from this website www.openna.com/books/floppy.tgz. In either case, be it from CDROM or if you have downloaded from the website extract the files from the archive by typing: [root@deep ]/tmp#tar xzpf floppy.tgz this is assuming you have stored the floppy.tgz in a directory called tmp/ . Errata: Important As i was giving the final look over on this book, Gerhard Mourani has released an errata for all firewall scripts and it is available here http://www.openna.com/books/errata.htm If you cannot get the examples directly over the Internet, please contact the author at these email addresses: ----------------------------------------------------------------------------- 1.5. Acknowledgements from Gerhard I would like to thank Michel Méral who has drawn all the beautiful animal drawing in my book, Robert L. Ziegler for allowing me to include his Firewall software and all Linux users around the world for their comments and suggestions. ----------------------------------------------------------------------------- 1.5.1. Acknowledgements from "Maddy" The book has been orginally written by Gerhard Mourani www.openna.com but i would like to thank him for collaborating with me in porting ( for the want of a better word).To say he was co-operative will be an under statement he was always there with a helping hand to answer my innumerable queries etc. Also i would like to thank the following people,but not in any particular order; Norman Walsh, http://nwalsh.com/~ndw/ for his phenominal and brilliant contribution to DocBook. To me at times looks like only one man contributing to its growth, popularity and in the process as well making it a mature product. Add to that he is a wonderful human being. My many many thanks to him. Peter Graves, http://armedbear.org for his Brilliant editor j, i do all my work using it and there are no words to describe it. i am indebted to him. I doubt very much if i could have worked for long stretches without it. Bryan Henderson, http://netpbm.sourceforge.net/ for his netpbm package and more than any thing for having the patience in dealing with my often persistent and idiotic queries. His software was mainly responsible for converting and manupilating all the orginal images which were in some esoteric format. Additionally i would also like to thank the following for releasing the right software at the right time: James clark, http://www.jclark.com/ for his xt and xp Michael Kay, http://users.iclway.co.uk/mhkay/saxon/ for Saxon To each and everyone at OASIS, http://www.oasis-open.org/docbook/ To each and everyone at Docbook.org, http://docbook.org/ To Sebestain Rahtz, http://users.ox.ac.uk/~rahtz/passivetex/ for his contribution to DocBook Mark Galassi for his brilliant Docbook Tutorial http://nis-www.lanl.gov/ ~rosalia/mydocs/ , My starting point!. The list would probably go on endlessly, and may be require a book for acknowledgements i guess. 2. Installation Turtle! Table of Contents 2. Overview of OS Linux 2.1. What is Linux? 2.2. A Few good reasons to use Linux 2.3. Fears, Uncertainity and Doubts 3. Installation of your Linux Server 3.1. Know your Hardware! 3.2. Creating the Boot Disk and Booting 3.3. Installation Class and Method (Install Type) 3.4. Disk Setup- Disk Druid 3.5. Disk Druid 3.6. An example 3.7. Post-Partitioning 3.8. Components to Install- Package Group Selection 3.9. Select Individual Package - Part 'A' 3.10. Select Individual Package -Part 'B' 3.11. How to use RPM Commands 3.12. Starting and stopping daemon services 4. Post-Install 4.1. Software that must be uninstalled 4.2. Use RPM command to uninstall. 4.3. Software that must be installed 4.4. Check,Re-confirm 4.5. Verify,Cross-check 4.6. some colors for a change 4.7. Update of the latest software ----------------------------------------------------------------------------- Chapter 2. Overview of OS Linux This part of the book deals with all the basic knowledge required to properly install a Linux OS, in our case a Redhat Linux on your system. Introduction to Linux Steps to be taken prior to install Steps to be taken post install ----------------------------------------------------------------------------- 2.1. What is Linux? Linux is an Operating System that was first created at the University of Helsinki in Finland by a young student named Linus Torvalds. At this time the student was working on a UNIX system that was running on an expensive platform. Because of his low budget, and his need to work at home, he decided to create a copy of the UNIX system in order to run it on a less expensive platform, such as an IBM PC. He began his work in 1991 when he released version 0.02 and worked steadily until 1994 when version 1.0 of the Linux Kernel was released. The current full-featured version at this time is 2.2.X; released January 25, 1999, and development continues. +---------------------------------------------------------------------------+ | GNU GPL and Linux | | | | The Linux operating system is developed under the GNU General Public | | License (also known as GNU GPL) and its source code is freely available | | to everyone who downloads it via the Internet. The CD-ROM version of | | Linux is also available in many stores, and companies that provide it | | will charge you for the cost of the media and support. Linux may be used | | for a wide variety of purposes including networking, software | | development, and as an end-user platform. Linux is often considered an | | excellent, low-cost alternative to other more expensive operating systems | | because you can install it on multiple computers without paying more. | +---------------------------------------------------------------------------+ ----------------------------------------------------------------------------- 2.2. A Few good reasons to use Linux There are no royalty or licensing fees for using Linux, and the source code can be modified to fit your needs. The results can be sold for profit, but original authors retain copyright and you must provide the source to your modifications. Because it comes with source code to the kernel, it is quite portable. Linux runs on more CPUs and platforms than any other computer operating system. The recent direction of the software and hardware industry is to push consumers to purchase faster computers with more system memory and hard drive storage. Linux systems are not affected by those industries orientation because of it capacity to run on any kind of computers, even aging x486-based computers with limited amounts of RAM. Linux is a true multi-tasking operating system similar to its brother UNIX. It uses sophisticated, state-of-the-art memory management to control all system processes. That means that if a program crashes you can kill it and continue working with confidence. Another benefit is that Linux is practically immunized against all kinds of viruses that we find in other operating systems. To date we have found only two viruses that were effective on Linux systems. ----------------------------------------------------------------------------- 2.3. Fears, Uncertainity and Doubts Let's dispel some of the fear, uncertainty, and doubt about Linux: It's a toy operating system. Fortune 500 companies, governments, and consumers; more and more use, Linux as a cost-effective computing solution. It has been used and is still used by big companies like IBM, Amtrak, NASA, and others. There's no support. Every Linux distribution comes with more than 12,000 pages of documentation. Commercial Linux distributions such as Red Hat Linux, Caldera, SuSE, and OpenLinux offer initial support for registered users, and small business and corporate accounts can get 24/7 supports through a number of commercial support companies. As an Open Source operating system, there's no six-months to wait for a service release, and the online Linux community fixes many serious bugs within hours. ----------------------------------------------------------------------------- Chapter 3. Installation of your Linux Server The next two chapters is structured in a manner that follows the original installation of the Red Hat Linux CD-ROM. Each section below refers to, and will guide you through, different screens that will appear during the setup of your system after the insertion of the Red Hat boot diskette in your computer. We promise that it will be interesting to have the machine you want to install Linux on, ready and near to you when you follow the steps described below. From time to time Red Hat Linux updates its operating system to a new version and adds, changes or removes some packages as well as changes some locations, content or features of files in its distribution. Red Hat Recently has updated their version of operating system to 6.2 called Zoot, which is a minor upgrade of 6.1, so to be as accurate as possible about all information contained in these early chapters, we'll comment upon installation of version 6.1 as well as version 6.2 for those who will upgrade or install to it. Any sections in this chapter that refer to version 6.1 will be for the Red Hat Linux 6.1 (Cartman) distribution, and any section where we talk about version 6.2 will be for the Red Hat Linux 6.2 (Zoot) distribution, respectively. The following conventions will simplify the interpretations in these chapter: All versions This icon applies to Red Hat Linux version 6.1 and 6.2 respectively. Version 6.1 only This icon applies to Red Hat Linux version 6.1 only. Version 6.2 only This icon applies to Red Hat Linux version 6.2 only. We know that many organizations and companies handle different versions of this operating system, and run a number of services on them. Sometimes it may be difficult to upgrade to the latest version since clients use services on the server 24 hours a day. With this simple convention, people who maintain and use version 6.1 of Red Hat Linux will always find exact information related to their needs. ----------------------------------------------------------------------------- 3.1. Know your Hardware! Understanding the hardware of your computer is essential for a successful installation of Red Hat Linux. Therefore, you should take a moment now and familiarize yourself with your computer hardware. Be prepared to answer the following questions:   *  How many hard drives do you have?   *  What size is each hard drive? e.g. 3.2GB.   *  If you have more than one hard drive, which is the primary one?   *  What kind of hard drive do you have? e.g. IDE, SCSI.   *  How much RAM do you have e.g. 256MB RAM.   *  Do you have a SCSI adapter? If so, who is the manufacturer and what model is it?   *  Do you have a RAID system? If so, who is the manufacturer and what model is it?   *  What type of mouse do you have e.g. PS/2, Microsoft, Logitech.   *  How many buttons does your mouse have? 2/3 buttons.   *  If you have a serial mouse, what COM port is it connected to? e.g. COM1.   *  What is the make and model of your video card? How much video RAM do you have? e.g. 4MB.   *  What kind of monitor do you have? Make and Model.   *  Will you be connected to a network? If so, what will be the following:   *  a. Your IP address? b. Your netmask? c. Your gateway address? d. Your domain name server's IP address? e. Your domain name? f. Your hostname? g. Your types of network(s) card(s)? Make and Model. h. Your number of card(s)? Make and Model. ----------------------------------------------------------------------------- 3.2. Creating the Boot Disk and Booting [VersionAll] The first thing to do is to create an installation diskette also known as a boot disk. If you have purchased the official Red Hat Linux CD-ROM, you will find this floppy disk named Boot Diskette in the Red Hat Linux box and you don't need to create it. From time to time, you may find that the installation will fail with the standard diskette image that comes with the official Red Hat Linux CD-ROM. If this happens, a revised diskette is required in order for the installation to work properly. In these cases, special images are available via the Red Hat Linux Errata web page to solve the problem www.redhat.com/errata. Since this, is a relatively rare occurrence, you will save time if you try to use the standard diskette images first, and then review the Errata only if you experience any problem completing the installation. Step 1. Before you make the boot disk, insert the Official Red Hat Linux CD-ROM Part 1 in your computer that runs the Windows operating system. When the program asks for the filename, enter boot.img for the boot disk. To make the floppies under MS-DOS, you need to use these commands assuming your CD-ROM is drive D: and contain the Official Red Hat Linux CD-ROM. Open the Command Prompt under Windows: Start | Programs | Command Prompt C:\> d: D:\> cd \dosutils D:\dosutils> rawrite Enter disk image source file name: ..\images\boot.img Enter target diskette drive: a: Please insert a formatted diskette into drive A: and press --ENTER-- : D:\dosutils> The rawrite.exe program asks for the filename of the disk image: Enter boot.img and insert a floppy into drive A. It will then ask for a disk to write to: Enter a:, and when complete, label the disk; for example, Red Hat boot disk. Step 2. Since we'd start the installation directly off the CD-ROM, boot with the boot disk. Insert the boot diskette you create into the drive A: on the computer where you want to install Linux and reboot the computer. At the boot:, press Enter to continue booting and follow the three simple steps below: Choose your language You can choose your prefferd language for the Linux OS from a list. For example, English, Danish etc Choose your keyboard type You can choose your Keyboard type. For example US pc104, norwegian etc Select your mouse type You can choose your mouse type. For example Logitech two button, Microsoft three button mouse etc ----------------------------------------------------------------------------- 3.3. Installation Class and Method (Install Type) Red Hat Linux 6.1 and 6.2 include four different classes, or type of installation. They are: GNOME Workstation KDE Workstation Server Custom The first three classes GNOME Workstation, KDE Workstation, and Server give you the option of simplifying the installation process with a significant loss of configuration flexibility that we don't want to lose. For this reason we highly recommend Custom installation, as this allows you to choose what services are added and how the system is partitioned.The idea is to load the minimum number of packages, while maintaining maximum efficiency. The less software that resides on the box, the fewer potential security exploits or holes may appear.Select Custom and click Next ----------------------------------------------------------------------------- 3.4. Disk Setup- Disk Druid Versian All We assume that you are installing your new Linux server to a new hard drive, with no other existing file system or operating system previously installed. A good partition strategy is to create a separate partition for each major file system. This enhances security and prevents accidental denial of service or exploit of SUID programs. Creating multiple partitions offers you the following advantages: Protection against denial of service attack. Protection against SUID programs. Faster booting. Easy backup and upgrade management. Ability for better control of mounted file system. Limit each file system's ability to grow. +---------------------------------------------------------------------------+ | Warning | +---------------------------------------------------------------------------+ |If previous file system or operating system exist on the hard drive and | |computer where you want to install your Linux system, we highly recommend, | |that you make a backup of your current system before proceeding with the | |disk partitioning. | +---------------------------------------------------------------------------+ Step 1. For performance, stability and security reasons you must create something like the following partitions listed below on your computer. We suppose for this partition configuration the fact that you have a SCSI hard drive of 3.2 GB. Of course you will need to adjust partition sizes according to your own needs and disk size. Partitions that must be created on your system: /boot 5MB (1) /usr 512MB (2) /home 1146MB (3) /chroot 256MB (4) /cache 256MB (5) /var 256MB (6) 128MB (7) /tmp 256MB (8) / 256MB (9) (1) All Kernel images are kept here. (2) Must be large, since all Linux binaries programs are installed here. (3) Proportional to the number of users you intend to host i.e. 10MB per users multiplied by the number of users 114 = 1140MB. (4) If you want to install programs in chroot jail environment i.e. DNS. (5) This is the cache partition of a proxy server i.e. Squid. (6) Contains files that change when the system run normally i.e. Log files. (6) Our swap partition. The virtual memory of the Linux operating system. (8) Our temporary files partition. (9) Our root partition. We have made two more special partitions: /chroot The /chroot partition can be used for DNS server chrooted, Apache server chrooted and other chrooted future programs. /cache The /cache partition can be used for a Squid Proxy server. If you are not intending to install Squid Proxy server you don't need to create the /cache partition. Keeping /tmp and /home on separate partitions is pretty much mandatory if users have shell access to the server- protection against SUID programs; splitting these off into separate partitions also prevent users from filling up any critical file system -denial of service attack. The same applies to / var, and /usr on separate partitions is also a very good idea. By isolating the /var partition, you protect your root partition from overfilling -denial of service attack. In our partition configuration we'll reserve 256 MB of disk space for chrooted programs like Apache, DNS and other software. This is necessary because Apache DocumentRoot files and other binaries, programs related to Apache will be installed in this partition if you decide to run Apache web server in a chrooted jail. Take note that the size of the Apache chrooted directory on the chrooted partition is proportional to the size of your DocumentRoot files. If you're not intending to install and use Apache on your server, you can reduce the size of this partition to something like 10 MB for DNS server that you always need in a chrooted jail environment for security reasons. Note Minimum size of partitions: For information purposes only, this is the minimum size in megabytes, which a Linux installation must have to function properly. The sizes of partitions listed below are really small. This configuration can fit into a very old hard disk of 512MB in size that you might find in old x486 computers. We show you this partition just to get an idea of the minimum requirements. / 35MB /boot 5MB /chroot 10MB /home 100MB /tmp 30MB /usr 232MB /var 25MB ----------------------------------------------------------------------------- 3.5. Disk Druid Disk Druid Partitions is a program that partitions your hard drive for you. Choose Add to add a new partition, Edit to edit a partition, Delete to delete a partition and Reset to reset the partitions to the original state. When you add a new partition, a new window appears on your screen and gives you parameters to choose. Different parameters are: Mount Point: for where you want to mount your new partition in the filesystem. Size (Megs): for the size of your new partition in megabytes. Partition Type: Linux native for Linux filesystem and Swap for Linux Swap Partition. Note : If you have a SCSI disk the device name will be /dev/sda and if you have an IDE disk it will be /dev/hda. If you're looking for high performance and stability, a SCSI disk is highly recommended. Linux refers to disk partitions using a combination of letters and numbers. It uses a naming scheme that is more flexible and conveys more information than the approach used by other operating systems. Here is a summary: Disk naming convention First Two Letters The first two letters of the partition name indicate the type of device on which the partition resides. You'll normally see either hd (for IDE disks), or sd (for SCSI disks). The Next Letter This letter indicates which device the partition is on. For example: /dev/hda (the first IDE hard disk) and /dev/hdb (the second IDE disk). Keep this information in mind, it will make things easier to understand when you're setting up the partitions Linux requires. Swap partitions are used to support virtual memory. If your computer has 16 MB of RAM or less, you must create a swap partition. Even if you have more memory, a swap partition is still recommended. The minimum size of your swap partition should be equal to your computer's RAM or 16 MB (whichever is larger). The largest useable swap partition is roughly 1 GB, since 2.2 kernel, 1 GB swap file are supported so making a swap partition larger than that will result in wasted space. Note, however, that you can create and use more than one swap partition although this is usually only necessary for very large server installations. Try to put your swap partitions near the beginning of your drive. The beginning of the drive is physically located on the outer portion of the cylinder, so the read/write head can cover much more ground per revolution. Linux Partitions representation of linux partition ----------------------------------------------------------------------------- 3.6. An example To make the partitions listed below on your system; this is the partition we'll need for our server installation example; the command will be under Disk Druid: Add Mount Point: /boot our /boot directory. Size (Megs): 5 Partition Type: Linux Native Ok Add Mount Point: /usr our /usr directory. Size (Megs): 512 Partition Type: Linux Native Ok Add Mount Point: /home our /home directory. Size (Megs): 1146 Partition Type: Linux Native Ok Add Mount Point: /chroot our /chroot directory. Size (Megs): 256 Partition Type: Linux Native Ok Add Mount Point: /cache our /cache directory. Size (Megs): 256 Partition Type: Linux Native Ok Add Mount Point: /var our /var directory. Size (Megs): 256 Partition Type: Linux Native Ok Add Mount Point: our /Swap partition leave the Mount Point Blank. Size (Megs): 128 Partition Type: Linux Swap Ok Add Mount Point: /tmp our /tmp directory. Size (Megs): 256 Partition Type: Linux Native Ok Add Mount Point: / our / directory. Size (Megs): 256 Partition Type: Linux Native Ok After the partitions of your hard disk has been completed, you must see something like the following information on your screen. Our mount points will look like this: Table 3-1. Sample representaion of partitions Mount Point Device Requested Actual Type /boot sda1 5M 5M Linux Native /usr sda5 512M 1146M Linux Native /home sda6 256M 256M Linux Native /chroot sda7 256M 256M Linux Native /cache sda8 256M 256M Linux Native /var sda9 256M 256M Linux Native sda10 128M 128M Linux Swap /tmp sda11 256M 256M Linux Native / sda12 256M 256M Linux Native +-----+------------+---------+--------+--------+--------+ |Drive|Geom [C/H/S]|Total (M)|Free (M)|Used (M)|Used (%)| +-----+------------+---------+--------+--------+--------+ |sda |[3079/64/32]|3079M |1M |3078M |99% | +-----+------------+---------+--------+--------+--------+ Note : We are using a SCSI hard disk hence the first two letters of the device are sd. ----------------------------------------------------------------------------- 3.7. Post-Partitioning Now that you are partitioning and choosing the mount point of your directories, select Next to continue. After your partitions are created, the installation program will ask you to choose partitions to format. Choose the partitions you want to initialize, check the (Check for bad blocks during format) box, and press Next. This formats the partitions and makes them active so Linux can use them. On the next screen you will see the LILO Configuration where you have the choice to install LILO boot record on: Master Boot Record (MBR) Or First Sector of Boot Partition Usually if Linux is the only OS on your machine you should choose the Master Boot Record (MBR) option. After that, you need to configure your Network and Clock. After you finish configuring the clock, you need to give your system a root password and authentication configuration. For Authentication Configuration don't forget to select: Enable MD5 passwords Enable Shadow passwords Enable NIS doesn't need to be selected since we are not configuring NIS services on this server. ----------------------------------------------------------------------------- 3.8. Components to Install- Package Group Selection After your partitions have been configured and selected for formatting, you are ready to select packages for installation. By default, Linux is a powerful operating system that executes many useful services. However, many of these services are unneeded and pose potential security risks. Ideally, each network service should be on a dedicated, single-purpose host. Many Linux operating systems are configured by default to provide a wider set of services and applications than are required to provide a particular network service, so you may need to configure the server to eliminate unneeded services. Offering only essential services on a particular host can enhance your network security in several ways:   *  Other services cannot be used to attack the host and impair or remove desired network services.   *  Different individuals may administer different services. By isolating services so each host and service has a single administrator you will minimize the possibility of conflicts between administrators.   *  The host can be configured to better suit the requirements of the particular service. Different services might require different hardware and software configurations, which could lead to needless vulnerabilities or service restrictions. By reducing services, the number of logs and log entries is reduced so detecting unexpected behavior becomes easier. A proper installation of your Linux server is the first step to a stable, secure system. You first have to choose which system components you want to install. Choose the components, and then you can go through and select or deselect each individual package of each component by selecting Select individual packages option on your Red Hat setup screen. Since we are configuring a Linux Server, we don't need to install a graphical interface XFree86 on our system, a graphical interface on a server means less processes, less CPU availability, less memory, security risks, and so on. Graphical interfaces are usually used on workstations only. Select the following packages for installation: Networked Workstation Network Management Workstation Utilities After selecting the components you wish to install, you may select or deselect packages. Important : Select the Select individual packages options before continuing to have the option to select and deselect packages. ----------------------------------------------------------------------------- 3.9. Select Individual Package - Part 'A' The installation program presents a list of the package groups available. Select a group to examine. The components listed below must be deselected from the Menu Group for security; optimization and other reasons described below: All versions Applications/File:. git The GIT package provides an extensible file system browser, an ASCII/ hexadecimal file viewer, a process viewer/killer and other related utilities and shell scripts. Unnecessary. All versions Applications/Internet:. finger The finger package is a client utility, which allows users to see information about system users. Security risks. ftp The ftp package provides the standard UNIX command-line FTP client. Security risks. fwhois The fwhois client program allows for querying whois databases. Security risks. ncftp The Ncftp package is an improved FTP client. [Security risks, Unnecessary. rsh The rsh package provides client programs, which allows users to run commands on remote machines, login to other machines and copy files between machines (rsh, rlogin and rcp). Security risks. rsync rsync is very powerfull mirroring program, which brings very quickly remote and host files into sync. Unnecessary talk The ntalk package provides client and daemon programs for the Internet talk protocol, which allows you to chat with other users on different UNIX systems. Security risks. telnet Telnet is a popular protocol for logging into remote systems over the network but it is insecure (transfer password in plain text). Security risks. All versions Applications/Publishing:. ghostscript The GhostScript package is a set of software that provides a PostScript interpreter, and an interpreter for Portable Document Format PDF files. Unnecessary ghostscript-fonts The GhostScript interpreter can use the Ghostscript-fonts package during text rendering. Unnecessary. Version 6.2 only groff-perl The groff-perl package is a set of commands and print filter used in printer environment. Unnecessary, no printer installed on the server. Version 6.2 only mpage The mpage package utility takes plain text files or PostScript documents as input, reduces the size of the text, and prints the files on a PostScript printer with several pages on each sheet of paper. Unnecessary, no printer installed on the server Version 6.2 only pnm2ppa The pnm2ppa package is a color driver for printing to HP PPA printers. Unnecessary, no printer installed on the server. rhs-printfilters The rhs-printfilters package contains a set of print filters, which is primarily meant to be use with the Red Hat printtool. Unnecessary, no printer installed on the server Version all Applications/System:. arpwatch The arpwatch package contains utilities to monitor Ethernet or FDDI network traffic and build databases of Ethernet/IP address pairs. Unnecessary bind-utils The bind-utils package contains a collection of utilities to find out information about Internet hosts. We will compile it later on this book. Version 6.1 only knfsd-clients The knfsd-clients package contains the showmount program that queries the mount daemon on a remote host for information about the NFS server on the remote host. Security risks, and NFS services are not installed on this server. Version 6.1 only procinfo The procinfo package acquires information about your system from the kernel as it is running. Unnecessary, other methods exist. rdate The rdate package utility can retrieve the date and time from another machine on your network. Security risks. rdist The rdist package is a program that maintains identical copies of files on multiple hosts. Security risks. screen This screen package is a useful utility for users who telnet into a machine or are connected via a dumb terminal, but want to use more than just one login. Unnecessary ucd-snmp-utils The ucd-snmp-utils package contains various utilities for use with the ucd-snmp network management project. Unnecessary, Security risks Version All Documentation:. indexhtml The indexhtml package contains the HTML page and graphics for a welcome page shown by your Web browser into X Window Systems. Unnecessary,we don't use graphical interface. ----------------------------------------------------------------------------- 3.10. Select Individual Package -Part 'B' Version All System Environment/Base:. chkfontpath The chkfontpath package is a simple program for adding, removing and listing the directories contained in the X font server's path. Unnecessary, we don't use graphical interface yp-tools The Network Information Service NIS is a system, which provides and centralizes network information; login names, passwords, home directories, and group information, to all of the machines on a network. Security risks, we don't use it on our server Version All System Environment/Daemons: . XFree86-xfs The XFree86-xfs package is a font server for XFree86 that can also serve fonts to other X servers remotely. Unnecessary, we don't use graphical interface Version 6.2 only finger-server The finger-server package contain the finger daemon that runs from the /etc/inetd.conf, file and allows users to see information about system users on the server. Security risks. lpr The lpr package provides the basic system utility for managing printing services. Unnecessary and no printer installed on the server Version 6.2 only nfs-utils The nfs-utils package provides the tools and daemon for the kernel NFS server. This package must be installed if you want to provide NFS services on your server. Security risks, and NFS services are not installed on this server. pidentd The pidentd package contains the identd, which looks up specific TCP/IP connections and returns either the user name or other information about the process that owns the connection. Unnecessary, very few things on the net require the sender to be running identd, because many machines don't have it and because many people turn it off. portmap The portmapper package manages RPC connections, which are used by protocols like NFS and NIS. Unnecessary, Security risks, and NIS/NFS services are not installed on this server. Version 6.2 only rsh-server The rsh-server package provides the servers needed for (rsh, rlogin, rcp) which allow users to run remote access commands on remote machines. Security risks rusers The routed package routing daemon maintains current routing tables by handling incoming RIP traffic and broadcasts outgoing RIP traffic about network traffic routes. Unnecessary, Security risks, and limited. Version 6.2 only rusers-server The rusers package program allows users to find out who is logged into various machines on the local network. Security risks. Version 6.2 only rwall-server The rwall-server package contains the daemon which allows receiving remote messages from users in remote hosts. Security risks rwho The rwho package shows who is logged in for all machines on the local network running the rwho daemon. Security risks. Version 6.2 only talk-server The talk-server package provides the daemon program, which allows you to chat via terminal with other users on remote UNIX systems. Security risks. Version 6.2 only telnet-server The telnet-server package provides the daemon, which allows telnet remote logins protocol to your server. Security risks, replace by SSH Version 6.1 only tftp The tftp package or Trivial File Transfer Protocol TFTP allows users to transfer files to and from a remote machine. It is normally used only for booting diskless workstations. Security risks, Unnecessary. Version 6.2.only tftp-server The tftp-server package provides the server for (TFTP), which allows users to transfer files to and from a remote machine. Security risks, Unnecessary. ucd-snmp The ucd-snmp package or SNMP -Simple Network Management Protocol is a protocol used for network management. Unnecessary, Security risks Version All ypbind The ypbind package is a daemon which binds NIS -Network Information Service server client to NIS server. Security risks, we don't use it on our server. Version 6.2 only ypserv The ypserv package is the NIS -Network Information Service server, which provides network information (NIS) to all of the machines on a network. Security risks, we don't use it on our server Version All System Environment/Libraries:. XFree86-libs The XFree86-libs package contains the shared libraries that most X programs need to run properly. Unnecessary, we dont use graphical interface. libpng The libpng package contains a library of functions for creating and manipulating GIF image format files. GIF is a bit-mapped graphics format similar to the GIF format. Unnecessary. User Interface/X:. Version 6.1 only XFree86-75dpi-fonts The XFree86-75dpi-fonts package contains the 75 dpi fonts (the standard fonts) used on most X Window Systems. Unnecessary, we don't use graphical interface. Version 6.2 only urw-fonts The urw-fonts package contain free versions of the 35 standard Type 1 PostScript fonts. Unnecessary, we don't use graphical interface. ----------------------------------------------------------------------------- 3.11. How to use RPM Commands This section contains an overview of principal modes using with RPM for installing, uninstalling, upgrading, querying, listing, and checking RPM packages on your Linux system. You must be familiar with these RPM commands now because we'll use them often in the continuation of this book. To install a RPM package, use the command: [root@deep] /#rpm -ivh foo-1.0-2.i386.rpm Take a note that RPM packages have a file of names like foo-1.0-2.i386.rpm, which include the package name (foo), version (1.0), release (2), and architecture (i386). To uninstall a RPM package, use the command: [root@deep] /#rpm -e foo Notice that we used the package name foo, not the name of the original package file foo-1.0-2.i386.rpm. To upgrade a RPM package, use the command: [root@deep] /#rpm -Uvh foo-1.0-2.i386.rpm With this command, RPM automatically uninstall the old version of foo package and install the new one. Always use rpm -Uvh to install packages, since it works fine even when there are no previous versions of the package installed. To query a RPM package, use the command: [root@deep] /#rpm -q foo This command will print the package name, version, and release number of installed package foo. Use this command to verify that a package is or is not installed on your system. To display package information, use the command: [root@deep] /#rpm -qi foo This command display package information; includes name, version, and description of the installed program. Use this command to get information about the installed package. To list files in package, use the command: [root@deep] /#rpm -qlfoo This command will list all files in a installed RPM package. It works only when the package is already installed on your system. To check a RPM signature package, use the command: [root@deep] /#rpm --checksig foo This command checks the PGP signature of specified package to ensure its integrity and origin. Always use this command first before installing new RPM package on your system. Also, GnuPG or Pgp software must be already installed on your system before you can use this command. ----------------------------------------------------------------------------- 3.12. Starting and stopping daemon services The init program of Linux -also known as process control initialization, is in charge of starting all the normal and authorized processes that need to run at boot time on your system. These may include the APACHE daemons, NETWORK daemons, and anything else that must be running when your machine boots. Each of these processes has a script under /etc/rc.d/init.d/ directory written to accept an argument, which can be start, stop and restart. You can execute those scripts by hand in fact with a command: Example 3-1. Starting and Stopping various Daemon's To start the httpd Web Server manually under Linux. [root@deep] /# /etc/rc.d/init.d/httpd start Starting httpd: [OK] To stop the httpd Web Server manually under Linux. [root@deep] /# /etc/rc.d/init.d/httpd stop Shutting down http: [OK] To restart the httpd Web Server manually under Linux. [root@deep] /# /etc/rc.d/init.d/httpd restart Shutting down http: [OK] Starting httpd: [OK] Check inside your /etc/rc.d/init.d/ directory for services available and use command start | stop | restart to work around. ----------------------------------------------------------------------------- Chapter 4. Post-Install This entire chapter deals with the steps to be taken after the installation of your server, for example, uninstallation of certain programs which are going to compiled on your server using source tarballs, installation of certain programs required to compile these source tarballs etc ----------------------------------------------------------------------------- 4.1. Software that must be uninstalled Red Hat Linux installs other pre-compiled binaries of programs on your system by default and doesn't give you the choice to uninstall them during the install setup. For this reason, you must uninstall the following software on your system after the installation of your server.We must uninstall them for better security and to make space in our server. For more information and explanation of their capabilities and uses, please see your Red Hat manual or install the package and make an rpm -qi foo command to query and get a detailed description of the program, and then uninstall it again. Below is the list of programs and a short description of their utilizations. Version All pump The Pump DHCP package allows individual diskless clients on a network to get their own IP network configuration information from network servers. Unnecessary. Version All mt-st The mt -for magnetic tape drives and st -for SCSI tape devices tape drive management programs can control rewinding, ejecting, skipping files, blocks and more. Necessary only if you have a tape backup on this server. Version All eject The eject package contains an eject program that allows the user to eject removable media typically CD-ROMs, floppy disks, Iomega Jaz or Zip disks using software control. Necessary only if you have a tape backup on this server. Version All Metamail Metamail is a program that uses the mailcap file to determine how it should display non-text or multimedia material. Unnecessary. Version All apmd The apmd package, or advanced Power Management daemon utilities, can watch your notebook's battery and warn all users when the battery is low. Unnecessary for a server. Version All kernel-pcmcia-cs The kernel-pcmcia-cs package is for laptop machines and some non-laptops that support PCMCIA cards for expansion. Unnecessary for a server. Version All linuxconf The linuxconf package is a system configuration tool. Unnecessary, buggy program. Version All getty_ps The getty_ps package contains programs that are used to accept logins on the console or a terminal on your system. Unnecessary. Version 6.1 only setconsole The setconsole package is a basic system utility for setting up the / etc/inittab, /dev/systty and /dev/console files to handle a new console. Unnecessary. Version All isapnptools The isapnptools package contains utilities for configuring ISA Plug-and-Play (PnP) cards/boards. Unnecessary. Version All setserial The setserial package is a basic system utility for displaying or setting serial port information. Unnecessary. Version All kudzu The kudzu package is a hardware-probing tool run at system boot time to determine what hardware has been added or removed from the system. Unnecessary. version All raidtools The raidtools package includes the tools you need to set up and maintain a software RAID device on a Linux system. Depending if you use Raid or not. Version All gnuPG The GnuPG package is a tool for secure communication and data storage. It is a replacement for the PGP software. It can also be used to encrypt data and to create digital signatures. We will compile it later on our book. Version All redhat-logos The redhat-logos package contains files of the Red Hat "Shadow Man" logo and the RPM logo. Unnecessary on a server. Version All redhat-release The redhat-release package contains the Red Hat Linux release file. Unnecessary. Version All gd The gd package allows your code to quickly draw images and write out the result as a .gif file. Unnecessary. Version All pciutils The pciutils package contains various utilities for inspecting and setting devices connected to the PCI bus. We use other methods. Version All rmt The rmt utility provides remote network access to make backup. Security risks since rmt depends on rsh to work. ----------------------------------------------------------------------------- 4.2. Use RPM command to uninstall. The command to uninstall software is: [root@deep] /#rpm -e Where is the name of the software you want to uninstall e.g. (foo). Since Programs like apmd, kudzu, and sendmail are daemons that run as process. It is better to stop those processes before uninstalling them from the system.To stop those processes, use the following commands: [root@deep] /# /etc/rc.d/init.d/apmd stop [root@deep] /# /etc/rc.d/init.d/sendmail stop [root@deep] /# /etc/rc.d/init.d/kudzu stop 1. Version 6.1 only Now you can uninstall them safely, and all other packages, as shown below: Remove the specified packages for Red Hat Linux version 6.1 (Cartman). [root@deep] /# rpm -e --nodeps pump mt-st eject mailcap apmd kernel-pcmcia-cs linuxconf getty_ps setconsole isapnptools setserial kudzu raidtools gnupg redhat-logos redhat-release gd pciutils rmt Version 6.2. only Remove the specified packages for Red Hat Linux version 6.2 (Zoot). [root@deep] /# rpm -e --nodeps pump mt-st eject mailcap apmd kernel-pcmcia-cs linuxconf getty_ps isapnptools setserial kudzu raidtools gnupg redhat-logos redhat-release gd pciutils rmt 2. Version All Remove the linux.conf-installed file manually. [root@deep] /# rm -f /etc/conf.linuxconf-installed Note : This is a configuration file related to linuxconf software that must be removed manually. The program hdparm is needed by IDE hard disk but not SCSI hard disks. If you have an IDE disk on your system you must keep this program (hdparm), but if you don't have an IDE hard disk you can remove it safely from your system. To remove hdparm from your system, use the following command: [root@deep] /# rpm -e hdparm Use the programs kbdconfig, mouseconfig, timeconfig, authconfig, ntsysv, and setuptool in order to set your keyboard language and type, your mouse type, your default time zone, your NIS and shadow passwords, your numerous symbolic links in /etc/rc.d directory, and text mode menu utility which allow you to access all of these features. After those configurations have been set during the installation stage of your Linux server it's rare that you would need to change them again. So, you can uninstall them, and if in future you need to change your keyboard, mouse, default time, etc again via test mode menu, all you have to do is to install the program with the RPM from your original CD-ROM. To remove all the above programs from your system, use the following command: [root@deep] /# rpm -e kbdconfig mouseconfig timeconfig authconfig ntsysv setuptool Even if you are not intending to install a mail server on your Linux system, the program Sendmail is always needed on your servers for potential messages sent to the root user by different software services installed on your machine. Sendmail is a Mail Transport Agent -MTA program that sends mail from one machine to another. It can be configured in different manners; it can serve as an internal delivery mail system to a Mail Hub Server, or can be configured to be a Central Mail Hub Server for all Sendmail machines on your network. So depending on what you want to do with Sendmail, you must configure it to respond to your specific needs. For this reason you must uninstall Sendmail and see the relevant sections in this book that is related to Sendmail configuration and installation. To remove Sendmail from your system, use the following command: [root@deep] /# rpm -e sendmail ----------------------------------------------------------------------------- 4.3. Software that must be installed There are certain programs required to be able to compile programs on your server, hence you must install the following RPM packages. This part of the installation is very important and requires that you install all related packages described below. These are on your Red Hat Part 1 CD-ROM under RedHat/RPMS directory and represent the base necessary software needed on Linux to compile and install programs. 1. First, we mount the CD-ROM drive and move to the RPMS subdirectory of the CD-ROM. To mount the CD-ROM drive and move to RPM directory, use the following commands: [root@deep] /# mount /dev/cdrom /mnt/cdrom/ [root@deep] /# cd /mnt/cdrom/RedHat/RPMS/ In the process of customizing our linux server, we will be using, most of the time source tarballs rather than pre-compiled RPMs hence these are the packages that we need to be able to compile and install programs. Remember, this is the minimum package that will allow you to compile most of the tarballs available for Linux. Other compiled binary packages exist on the Red Hat CD-ROM, so verify with the README file that came with the tarballs program you want to install if you receive an error messages during compilation of the specific software. Version 6.1 only m4-1.4-12.i386.rpm egcs-1.1.2-24.i386.rpm dev86-0.14.9-1.i386.rpm ElectricFence-2.1-1.i386.rpm bison-1.28-1.i386.rpm flex-2.5.4a-7.i386.rpm byacc-1.9-11.i386.rpm gdb-4.18-4.i386.rpm cdecl-2.5-9.i386.rpm kernel-headers-2.2.12-20.i386.rpm cpp-1.1.2-24.i386.rpm glibc-devel-2.1.2-11.i386.rpm cproto-4.6-2.i386.rpm make-3.77-6.i386.rpm ctags-3.2-1.i386.rpm patch-2.5-9.i386.rpm Version 6.2 only m4-1.4-12.i386.rpm egcs-1.1.2-30.i386.rpm dev86-0.15.0-2.i386.rpm ElectricFence-2.1-3.i386.rpm bison-1.28-2.i386.rpm flex-2.5.4a-9.i386.rpm byacc-1.9-12.i386.rpm gdb-4.18-11.i386.rpm cdecl-2.5-10.i386.rpm kernel-headers-2.2.14-5.0.i386.rpm cpp-1.1.2-30.i386.rpm glibc-devel-2.1.3-15.i386.rpm cproto-4.6-3.i386.rpm make-3.78.1-4.i386.rpm ctags-3.4-1.i386.rpm patch-2.5-10.i386.rpm Note : It is better to install software mentioned above in one shot, if you don't want to receive error message regarding dependencies during RPM install. 2. Version 6.1 only Install all the needed software above with one RPM command. The RPM command to install all software together is: [root@deep ] /RPMS#rpm -Uvh m4-1.4-12.i386.rpm dev86-0.14.9-1.i386.rpm bison-1.28-1.i386.rpm byacc-1.9-11.i386.rpm cdecl-2.5-9.i386.rpm cpp-1.1.2-24.i386.rpm cproto-4.6-2.i386.rpm ctags-3.2-1.i386.rpm egcs-1.1.2-24.i386.rpm ElectricFence-2.1-1.i386.rpm flex-2.5.4a-7.i386.rpm gdb-4.18-4.i386.rpm kernel-headers-2.2.12-20.i386.rpm glibc-devel-2.1.2-11.i386.rpm make-3.77-6.i386.rpm patch-2.5-9.i386.rpm Version 6.2 only Install all the needed software above with one RPM command. The RPM command to install all software together is: [root@deep ] /RPMS#rpm -Uvh m4-1.4-12.i386.rpm dev86-0.15.0-2.i386.rpm bison-1.28-2.i386.rpm byacc-1.9-12.i386.rpm cdecl-2.5-10.i386.rpm cpp-1.1.2-30.i386.rpm cproto-4.6-3.i386.rpm ctags-3.4-1.i386.rpm egcs-1.1.2-30.i386.rpm ElectricFence-2.1-3.i386.rpm flex-2.5.4a-9.i386.rpm gdb-4.18-11.i386.rpm kernel-headers-2.2.14-5.0.i386.rpm glibc-devel-2.1.3-15.i386.rpm make-3.78.1-4.i386.rpm patch-2.5-10.i386.rpm The RPM package has many options, for example we have used the following sytax: rpm [-Uvh] [file] you might be curious to know what these arguments -Uvh means, why should it be given at all etc.Here is a brief description: -U -stands for Upgrade which will uninstall an older version of the package you are installing and install the new one, which will eliminate the error likely to occur if in case the package being uninstalled has dependencies. It is generally recomded to use this argument even while you are obsolutely sure that there is no earlier version of the package you are trying to install is existing on your machine. v -stands for verbose, which is quite self explanatory. This argument ensures all messages are written to the stdout/console so you get to know what is happening. h -this generates the hash mark # in a series, this will give a sense of visual progress with the install process . So, when you use rpm -Uvh, whether it is Redhat ver 6.1 or ver 6.2, what you see on your console is shown below,Notice in the display that the name of the package is seen but not the version number. Infact we have mentioned this earlier in this book that when you install or upgrade you have to enter the package name with version name, for example rpm -ivh mnt-1.0.4.rpm but while querying the same package using rpm command the syntax is as follows: rpm -qi mnt, Please do keep this mind. Given below is a graphical representation of your screen when you install the above mentioned rpm's : version all m4 ################################################## dev86 ################################################## bison ################################################## byacc ################################################## cdecl ################################################## cpp ################################################## cproto ################################################## ctags ################################################## egcs ################################################## ElectricFence ################################################## flex ################################################## gdb ################################################## kernel-headers ################################################## glibc-devel ################################################## make ################################################## patch ################################################## You must exit and re-login for all the change to take effect. To exit from your console, use the command: [root@deep] /# exit ----------------------------------------------------------------------------- 4.4. Check,Re-confirm After installation and compilation of all programs you need on your server, it's a good idea to remove all unnecessary programs (compilers, etc) described above unless needed it is obsolutely needed by the system. Few reasons are:   *  If a cracker gains access to your server he or she cannot compile or modify binary programs. Also, this will free a lot of space and will help to improve regular scanning of files on your server for integrity checking.   *  When you run a server you will give it a special task to accomplish. You will never put all services you want to offer in one machine or you will lose speed - resources available divided by the number of process running on the server.   *  Decrease your security with a lot of services running on the same machine, if a cracker accesses this server, he or she can attack directly all the others available.   *  Having different servers doing different tasks will simplify the administration, management you know what task each server is supposed to do, what services should be available, which ports are open to clients access and which one are closed, you know what you are supposed to see in the log files, etc, and give you more control and flexibility on each server dedicated for mail, web pages, database, development, backup, etc.   *  For example, having one server specialized just for development and testing will permit you to not be compelled to install compiler programs on a server each time you want to compile and install new software on it, and be obliged afterwards to uninstall the compilers, or other sharp objects. If you have followed each step exactly as described till now, Since we have chosen to customize the installation of our Linux system, this is the list of all installed programs that you must have on your server after the complete installation of the Linux Server. This list must match exactly the install.log file located in your /tmp directory or you could run into a problem. Don't forget to install all programs listed above in Software that must be installed after installation of the Server to be able to compile programd properly on your Server. Version 6.1 only Installing setup. Installing gawk. Installing netkit-base. Installing filesystem. Installing gd. Installing newt. Installing basesystem. Installing gdbm. Installing ntsysv. Installing ldconfig. Installing getty_ps. Installing passwd. Installing glibc. Installing glib. Installing pciutils. Installing shadow-utils. Installing gmp. Installing perl. Installing mktemp. Installing gnupg. Installing procmail. Installing termcap. Installing gpm. Installing procps. Installing libtermcap. Installing groff. Installing psmisc. Installing bash. Installing gzip. Installing pump. Installing MAKEDEV. Installing hdparm. Installing python. Installing SysVinit. Installing initscripts. Installing quota. Installing Installing ipchains. Installing raidtools. XFree86-Mach64. Installing chkconfig. Installing isapnptools. Installing readline. Installing apmd. Installing kbdconfig. Installing redhat-logos. Installing ncurses. Installing kernel. Installing rootfiles. Installing info. Installing Installing rpm. kernel-pcmcia-cs. Installing fileutils. Installing kudzu. Installing sash. Installing grep. Installing ld.so. Installing sendmail. Installing ash. Installing less. Installing setconsole. Installing at. Installing libc. Installing setserial. Installing authconfig. Installing libstdc++. Installing setuptool. Installing bc. Installing lilo. Installing shapecfg. Installing bdflush. Installing pwdb. Installing slang. Installing binutils. Installing pam. Installing slocate. Installing bzip2. Installing sh-utils. Installing stat. Installing sed. Installing redhat-release. Installing sysklogd. Installing console-tools. Installing linuxconf. Installing tar. Installing e2fsprogs. Installing logrotate. Installing tcp_wrappers. Installing rmt. Installing losetup. Installing tcpdump. Installing cpio. Installing lsof. Installing tcsh. Installing cracklib. Installing mailcap. Installing time. Installing Installing mailx. Installing timeconfig. cracklib-dicts. Installing crontabs. Installing man. Installing timed. Installing textutils. Installing mingetty. Installing tmpwatch. Installing dev. Installing mkbootdisk. Installing traceroute. Installing diffutils. Installing mkinitrd. Installing utempter. Installing dump. Installing modutils. Installing util-linux. Installing ed. Installing mount. Installing vim-common. Installing eject. Installing mouseconfig. Installing vim-minimal. Installing etcskel. Installing mt-st. Installing vixie-cron. Installing file. Installing ncompress. Installing which. Installing findutils. Installing net-tools. Installing zlib. Version 6.2 only Installing setup. Installing gawk. Installing ncompress. Installing filesystem. Installing gd. Installing net-tools. Installing basesystem. Installing gdbm. Installing newt. Installing ldconfig. Installing getty_ps. Installing ntsysv. Installing glibc. Installing glib. Installing passwd. Installing shadow-utils. Installing gmp. Installing pciutils. Installing mktemp. Installing gnupg. Installing perl. Installing termcap. Installing gpm. Installing popt. Installing libtermcap. Installing groff. Installing procmail. Installing bash. Installing gzip. Installing procps. Installing MAKEDEV. Installing hdparm. Installing psmisc. Installing SysVinit. Installing inetd. Installing pump. Installing Installing initscripts. Installing quota. XFree86-Mach64. Installing anacron. Installing ipchains. Installing raidtools. Installing chkconfig. Installing iputils. Installing readline. Installing apmd. Installing isapnptools. Installing redhat-logos. Installing ncurses. Installing kbdconfig. Installing rootfiles. Installing info. Installing kernel. Installing rpm. Installing fileutils. Installing Installing sash. kernel-pcmcia-cs. Installing grep. Installing kernel-utils. Installing sendmail. Installing ash. Installing kudzu. Installing setserial. Installing at. Installing ld.so. Installing setuptool. Installing authconfig. Installing less. Installing shapecfg. Installing bc. Installing libc. Installing slang. Installing bdflush. Installing libstdc++. Installing slocate. Installing binutils. Installing lilo. Installing stat. Installing bzip2. Installing pwdb. Installing sysklogd. Installing sed. Installing pam. Installing tar. Installing console-tools. Installing sh-utils. Installing tcp_wrappers. Installing e2fsprogs. Installing redhat-release. Installing tcpdump. Installing rmt. Installing linuxconf. Installing tcsh. Installing cpio. Installing logrotate. Installing time. Installing cracklib. Installing losetup. Installing timeconfig. Installing Installing lsof. Installing tmpwatch. cracklib-dicts. Installing crontabs. Installing mailcap. Installing traceroute. Installing textutils. Installing mailx. Installing utempter. Installing dev. Installing man. Installing util-linux. Installing diffutils. Installing mingetty. Installing vim-common. Installing dump. Installing mkbootdisk. Installing vim-minimal. Installing ed. Installing mkinitrd. Installing vixie-cron. Installing eject. Installing modutils. Installing which. Installing etcskel. Installing mount. Installing zlib. Installing file. Installing mouseconfig.   Installing findutils. Installing mt-st.   ----------------------------------------------------------------------------- 4.5. Verify,Cross-check After we have uninstalled all the software that must be uninstalled after the installation of our Linux server see Software that must be uninstalled after installation of the Server and after the addition of the necessary RPM packages, so that we will able to compile programs on our server, we must verify the list of all installed RPM programs again but this time with the following command: To verify the list of all installed RPM package on your system, use the command: [root@deep] /#rpm -qa > installed_rpm The -qa option will query all installed RPM packages on your system and the symbol > will redirect the output to the file named installed_rpm. Version 6.1 only The content of the installed_rpm file must match exactly this: setup-2.0.5-1 findutils-4.1-32 passwd-0.63-1 filesystem-1.3.5-1 gawk-3.0.4-1 perl-5.00503-6 basesystem-6.0-4 cdecl-2.5-9 flex-2.5.4a-7 ldconfig-1.9.5-15 gdbm-1.8.0-2 procps-2.0.4-2 glibc-2.1.2-11 glib-1.2.5-1 psmisc-18-3 shadow-utils-19990827-2 gmp-2.0.2-10 python-1.5.2-7 mktemp-1.5-1 cpp-1.1.2-24 quota-1.66-8 termcap-9.12.6-15 gpm-1.17.9-3 gdb-4.18-4 libtermcap-2.0.8-18 groff-1.11a-9 readline-2.2.1-5 bash-1.14.7-16 gzip-1.2.4-14 glibc-devel-2.1.2-11 MAKEDEV-2.5-2 initscripts-4.48-1 rootfiles-5.2-5 SysVinit-2.77-2 ipchains-1.3.9-3 rpm-3.0.3-2 chkconfig-1.0.7-2 cproto-4.6-2 sash-3.3-1 ncurses-4.2-25 ElectricFence-2.1-1 make-3.77-6 info-3.12h-2 kernel-2.2.12-20 shapecfg-2.2.12-2 fileutils-4.0-8 patch-2.5-9 slang-1.2.2-4 grep-2.3-2 ld.so-1.9.5-11 slocate-2.0-3 ash-0.2-18 less-340-1 stat-1.5-11 at-3.1.7-11 libc-5.3.12-31 sysklogd-1.3.31-12 m4-1.4-12 libstdc++-2.9.0-24 tar-1.13.11-1 bdflush-1.5-10 lilo-0.21-10 tcp_wrappers-7.6-9 binutils-2.9.1.0.23-6 pwdb-0.60-1 tcpdump-3.4-16 bzip2-0.9.5c-1 pam-0.68-7 tcsh-6.08.00-6 sed-3.02-4 sh-utils-2.0-1 time-1.7-9 console-tools-19990302-17 logrotate-3.3-1 timed-0.10-23 e2fsprogs-1.15-3 losetup-2.9u-4 tmpwatch-2.0-1 byacc-1.9-11 lsof-4.45-1 traceroute-1.4a5-16 cpio-2.4.2-13 mailx-8.1.1-9 utempter-0.5.1-2 cracklib-2.7-5 man-1.5g-6 util-linux-2.9w-24 cracklib-dicts-2.7-5 mingetty-0.9.4-10 vim-common-5.4-2 crontabs-1.7-7 mkbootdisk-1.2.2-1 vim-minimal-5.4-2 textutils-2.0-2 mkinitrd-2.3-1 vixie-cron-3.0.1-39 dev-2.7.10-2 modutils-2.1.121-14 which-2.8-1 diffutils-2.7-16 mount-2.9u-4 zlib-1.1.3-5 dump-0.4b4-11 ctags-3.2-1 dev86-0.14.9-1 ed-0.2-12 ncompress-4.2.4-14 egcs-1.1.2-24 bison-1.28-1 net-tools-1.53-1 kernel-headers-2.2.12-20 etcskel-2.0-1 netkit-base-0.10-37   file-3.27-3 newt-0.50-13   Version 6.2 only The content of the installed_rpm file must look exactly like this: setup-2.1.8-1 file-3.28-2 ncompress-4.2.4-15 filesystem-1.3.5-1 findutils-4.1-34 net-tools-1.54-4 basesystem-6.0-4 gawk-3.0.4-2 newt-0.50.8-2 ldconfig-1.9.5-16 patch-2.5-10 passwd-0.64.1-1 glibc-2.1.3-15 gdbm-1.8.0-3 perl-5.00503-10 shadow-utils-19990827-10 bison-1.28-2 popt-1.5-0.48 mktemp-1.5-2 glib-1.2.6-3 procmail-3.14-2 termcap-10.2.7-9 gmp-2.0.2-13 procps-2.0.6-5 libtermcap-2.0.8-20 gpm-1.18.1-7 psmisc-19-2 bash-1.14.7-22 groff-1.15-8 quota-2.00pre3-2 MAKEDEV-2.5.2-1 gzip-1.2.4a-2 gdb-4.18-11 SysVinit-2.78-5 inetd-0.16-4 readline-2.2.1-6 anacron-2.1-6 initscripts-5.00-1 make-3.78.1-4 chkconfig-1.1.2-1 ipchains-1.3.9-5 rootfiles-5.2-5 m4-1.4-12 iputils-20000121-2 rpm-3.0.4-0.48 ncurses-5.0-11 cpp-1.1.2-30 sash-3.4-2 info-4.0-5 cproto-4.6-3 shapecfg-2.2.12-2 fileutils-4.0-21 kernel-2.2.14-5.0 slang-1.2.2-5 grep-2.4-3 ctags-3.4-1 slocate-2.1-2 ash-0.2-20 kernel-utils-2.2.14-5.0 stat-1.5-12 at-3.1.7-14 ElectricFence-2.1-3 sysklogd-1.3.31-16 byacc-1.9-12 ld.so-1.9.5-13 tar-1.13.17-3 bc-1.05a-5 less-346-2 tcp_wrappers-7.6-10 bdflush-1.5-11 libc-5.3.12-31 tcpdump-3.4-19 binutils-2.9.5.0.22-6 libstdc++-2.9.0-30 tcsh-6.09-4 bzip2-0.9.5d-2 lilo-0.21-15 time-1.7-9 sed-3.02-6 pwdb-0.61-0 tmpwatch-2.2-1 console-tools-19990829-10 pam-0.72-6 traceroute-1.4a5-18 e2fsprogs-1.18-5 sh-utils-2.0-5 utempter-0.5.2-2 cpio-2.4.2-16 logrotate-3.3.2-1 util-linux-2.10f-7 cracklib-2.7-5 losetup-2.10f-1 vim-common-5.6-11 cracklib-dicts-2.7-5 lsof-4.47-2 vim-minimal-5.6-11 crontabs-1.7-7 mailx-8.1.1-10 vixie-cron-3.0.1-40 textutils-2.0a-2 man-1.5h1-1 which-2.9-2 dev-2.7.18-3 mingetty-0.9.4-11 zlib-1.1.3-6 diffutils-2.7-17 mkbootdisk-1.2.5-3 dev86-0.15.0-2 dump-0.4b15-1 mkinitrd-2.4.1-2 egcs-1.1.2-30 ed-0.2-13 modutils-2.3.9-6 kernel-headers-2.2.14-5.0 cdecl-2.5-10 mount-2.10f-1 glibc-devel-2.1.3-15 etcskel-2.3-1 flex-2.5.4a-9   This step is required to make sure we have not forgotten to remove some unnecessary RPM or to add some important packages that permit us to compile programs on the system. If the result looks as our installed_rpm file above, we are ready to play with our new Linux server. ----------------------------------------------------------------------------- 4.6. some colors for a change Putting some colors on your terminal can help you to distinguish folders, files, archives, devices, symbolic links and executable file from others. My opinion is that colors help to make less errors and fast navigation on your system. It's important to note that this hack is necessary only for Red Hat Linux version 6.1 (Cartman) and older, since the new Red Hat Linux version 6.2 (Zoot) now enables and includes this feature by default. Edit the profile file vi /etc/profile and add the following lines: # Enable Colour ls eval `dircolors /etc/DIR_COLORS -b` export LS_OPTIONS='-s -F -T 0 --color=yes' Edit the bashrc file vi /etc/bashrc and add the line: alias ls='ls --color=auto' Then log in and out. The new COLORS-environment variable should now be set, and your system will recognize that. Note : Remember that this feature is only required for Red Hat Linux version 6.1 and older. ----------------------------------------------------------------------------- 4.7. Update of the latest software Keep and update all software especially network software up to date with the latest versions. Check the errata pages for the Red Hat Linux distribution, available at www.redhat.com/corp/support/errata/index.html. The errata pages are perhaps the best resource for fixing 90% of the common problems with Red Hat Linux. In addition, security holes for which a solution exists are generally on the errata page 24 hours after Red Hat has been notified. You should always check there first. Software that must be updated at this time for your Red Hat Linux server are: groff-1_15-1_i386.rpm pam-0_68-10_i386.rpm sysklogd-1_3_31-14_i386.rpm gpm-1.19.1-1.i386.rpm initscripts-4_70-1_i386.rpm Linux kernel 2.2.14 -linux-2_2_14_tar.gz e2fsprogs-1.17-1.i386.rpm gpm-1.19.1-1.i386.rpm Note : The Linux kernel is the most important, and always must be updated. See below for more information on building a custom kernel for your specific system. You can verify that the RPM software above is installed on your system before make an update with the following command: [root@deep] /#rpm -q Where is the name of the software you want to verify like groff, sysklogd, etc. 3. Security, Optimization and Upgrade Bat Now that we have installed a base system, the next three chapters will concentrate on   +  How to tighten the security of our configured system.   +  Optimise our sytem to perform at its peak.   +  Upgrade our machine for the latest kernel. Please note when we talk of tightening the security we are referring to the features available within the base installed system and not to any new additional software. We will talk about that later in this book. Table of Contents 5. General System Security 5.1. BIOS 5.2. Security as a Policy 5.3. Choose a right Password 5.4. The root account 5.5. The /etc/exports file 5.6. Disable console program access 5.7. Disable all console access 5.8. The inetd - /etc/inetd.conf file 5.9. TCP_WRAPPERS 5.10. The /etc/host.conf file 5.11. The /etc/services file 5.12. The /etc/securetty file 5.13. Special accounts 5.14. Blocking; su to root, by one and sundry 5.15. Put limits on resource 5.16. Control mounting a file system 5.17. Conceal binary RPM 5.18. Shell logging 5.19. The LILO and lilo.conf file 5.20. Disable Ctrl-Alt-Delete keyboard shutdown command 5.21. Physical hard copies of all-important logs 5.22. Tighten scripts under /etc/rc.d/ 5.23. Bits from root-owned programs 5.24. The kernel tunable parameters 5.25. Refuse responding to broadcasts request 5.26. Routing Protocols 5.27. Enable TCP SYN Cookie Protection 5.28. Disable ICMP Redirect Acceptance 5.29. Enable always-defragging Protection 5.30. Enable bad error message Protection 5.31. Enable IP spoofing protection 5.32. Log Spoofed, Source Routed and Redirect Packets 5.33. Unusual or hidden files 5.34. System is compromised ! 6. Linux General Optimization 6.1. The /etc/profile file 6.2. Benchmark Results 6.3. Benchmark results-i586 6.4. Benchmark results -i486 6.5. The bdflush parameters 6.6. The buffermem parameters 6.7. The ip_local_port_range parameters 6.8. The /etc/nsswitch.conf file 6.9. The file-max parameter 6.10. The ulimit parameter 6.11. The atime and noatime attribute 6.12. Tuning IDE Hard Disk Performance 6.13. Better manage your TCP/IP resources 7. Configuring and Building a Secure, Optimized Kernel 7.1. Pre-Install 7.2. Uninstallation and Optimization 7.3. Securing the kernel 7.4. Compilation 7.5. Kernel configuration -Part "A" 7.6. Kernel configuration -Part "B" 7.7. Kernel configuration -Part "C" 7.8. Kernel configuration -Part "D" 7.9. Kernel configuration -Part "E" 7.10. Installing the new kernel 7.11. Delete programs, Edit files pertaining to modules 7.12. Create a emergency Rescue and Boot floppy disk ----------------------------------------------------------------------------- Chapter 5. General System Security A secure Linux server depends on how the administrator configures it to be. Once we have eliminated the potential securities risk by removing RPM services not needed, we can start to secure our existing services and software on our server. In this chapter we will discuss some of the more general, basic techniques used to secure your system. The following is a list of features that can be used to help prevent attacks from external and internal sources. ----------------------------------------------------------------------------- 5.1. BIOS It is recommended that you set a Boot password to disallow booting from floppy drives and set passwords on BIOS features. You can check your BIOS manual or look it over thoroughly the next time you boot up your system to know how to do this. Disallowing the possibility to boot from floppy drives and being able to set a password to access the BIOS features will improve the security of your system. This will block undesired people from trying to boot your Linux system with a special boot disk and will protect you from people trying to change BIOS feature like allowing boot from floppy drive or booting the server without prompt password. ----------------------------------------------------------------------------- 5.2. Security as a Policy It is important to point out that you cannot implement security if you have not decided what needs to be protected, and from whom. You need a security policy; a kind of list of what you consider allowable and not allowable, upon which to base any decisions regarding security. The policy should also determine your response to security violations. What you should consider while compiling a security policy will depend entirely on your definition of security. The answers to the following questions should provide some general guidelines:   *  How do you classify confidential or sensitive information?   *  Does the system contain confidential or sensitive information?   *  Exactly whom do you want to guard against?   *  Do remote users really need access to your system?   *  Do passwords or encryption provide enough protection?   *  Do you need access to the Internet?   *  How much access do you want to allow to your system from the Internet?   *  What action will you take if you discover a breach in your security? This list is not very comprehensive, and your policy will probably encompass a lot more before it is completed. Any security policy must be based on some degree of paranoia; deciding how much you trust people, both inside and outside your organization. The policy must, however, provide a balance between allowing your users reasonable access to the information they require to do their work and totally disallowing access to your information. The point where this line is drawn will determine your policy. ----------------------------------------------------------------------------- 5.3. Choose a right Password The starting point of our Linux General Security tour is the password. Many people keep their valuable information and files on a computer, and the only thing preventing others from seeing it is the eight-character string called a password. An unbreakable password, contrary to popular belief, does not exist. Given time and resources all passwords can be guessed either by social engineering or by brute force. Social engineering of server passwords and other access methods are still the easiest and most popular way to gain access to accounts and servers. Often, something as simple as acting as a superior or executive in a company and yelling at the right person at the right time of the day yields terrific results. Running a password cracker on a weekly basis on your system is a good idea. This helps to find and replace passwords that are easily guessed or weak. Also, a password checking mechanism should be present to reject a weak password when first choosing a password or changing an old one. Character strings that are plain dictionary words, or are all in the same case, or do not contain numbers or special characters should not be accepted as a new password. We recommend the following rules to make passwords effective:   * They should be at least six characters in length, preferably eight characters including at least one numeral or special character.   *  They must not be trivial; a trivial password is one that is easy to guess and is usually based on the user's name, family, occupation or some other personal characteristic.   * They should have an aging period, requiring a new password to be chosen within a specific time frame.   *  They should be revoked and reset after a limited number of concurrent incorrect retries. The minimum acceptable password length by default when you install your Linux system is 5. This mean that when a new user is allowed to have a access on the server, his/her password length will be at minimum 5 mixes of character strings, letter, number, special character etc. This is not enough and must be 8. To prevent non-security-minded people or administrators from being able to enter just 5 characters for the valuable password, edit the rather important /etc/login.defs file and change the value of 5 to 8. Edit the login.defs file vi /etc/login.defs and change the line that read: PASS_MIN_LEN 5 To read: PASS_MIN_LEN 8 The login.defs is the configuration file for the login program. You should review or make changes to this file for your particular system. This is where you set other security policy settings like password expiration defaults or minimum acceptable password length. ----------------------------------------------------------------------------- 5.4. The root account The root account is the most privileged account on a Unix system. The root account has no security restrictions imposed upon it. This means the system assumes you know what you are doing, and will do exactly what you request -- no questions asked. Therefore it is easy, with a mistyped command, to wipe out crucial system files. When using this account it is important to be as careful as possible. For security reasons, never log in on your server as root unless it is absolutely an instance that necessitates root access. Also, if you are not on your server, never sign in and leave yourself on as root --this is Very, Very, Very BAD practice. Set login time out for the root account. Despite the notice to never, if they are not on the server sign in as root and leave it unattended, administrators still stay on as root or forget to logout after finishing their work and leave their terminals unattended. The answer to solve this problem is to make the bash shell automatically logout after not being used for a period of time. To do that, you must set the special variable of Linux named TMOUT to the time in seconds of no input before logout. Edit your profile file /etc/profile and add the following line somewhere after the line that read HISTFILESIZE= on this file: TMOUT=7200 The value we enter for the variable TMOUT= is in second and represent 2 hours (60 * 60 = 3600 * 2 = 7200 seconds). It is important to note that if you decide to put the above line in your /etc/profile file, then the automatic logout after two hours of inactivity will apply for all users on the system. So, instead, if your prefer to control which users will be automatically logged out and which ones not, you can set this variable in their individual .bashrc file. After this parameter has been set on your system, you must logout and login again as root for the change to take effect. ----------------------------------------------------------------------------- 5.5. The /etc/exports file If you are exporting file systems using NFS service, be sure to configure the /etc/exports file with the most restrictive access possible. This means not using wildcards, not allowing root write access, and mounting read-only wherever possible. Example 5-1. Export file systems using NFS Edit the exports file vi /etc/exports and add: /dir/to/export host1.mydomain.com(ro,root_squash) /dir/to/export host2.mydomain.com(ro,root_squash) Where:   *  /dir/to/export is the directory you want to export.   *  host#.mydomain.com is the machine allowed to log in this directory.   *  The ro option mean mounting read-only.   *  The root_squash option for not allowing root write access in this directory. For this change to take effect you will need to run the following command on your terminal: [root@deep]# /usr/sbin/exportfs -a Note : Please be aware that having an NFS service available on your system can be a security risk. Personally, I don't recommend using it. ----------------------------------------------------------------------------- 5.6. Disable console program access In a safe environment where we are sure that console is secured because passwords for BIOS and LILO are set and all physical power and reset switches on the system are disabled it may be advantageous to entirely disable all console-equivalent access to programs like shutdown, reboot, and halt for regular users on your server. To do this, run the following command: [root@deep] /#rm -f /etc/security/console.apps/ Where is the name of the program to which you wish to disable console-equivalent access. Unless you use xdm, however, be careful not to remove the xserver file or no one but root will be able to start the X server. If you always use xdm to start the X server, root is the only user that needs to start X, in which case you might actually want to remove the xserver file. Example 5-2. Disable console-equivalent access [root@deep] /# rm -f /etc/security/console.apps/halt [root@deep] /# rm -f /etc/security/console.apps/poweroff [root@deep] /# rm -f /etc/security/console.apps/reboot [root@deep] /# rm -f /etc/security/console.apps/shutdown [root@deep] /# rm -f /etc/security/console.apps/xserver (1) (1) if removed, root will be the only user able to start X. This will disable console-equivalent access to programs halt, poweroff, reboot, and shutdown. Once again, the program xserver apply only is you are installed the Xwindow interface on your system. Note : If you are following our setup installation, the Xwindow interface is not installed on your server and all the files described above will not appear in the /etc/security directory, so can safely ignore the above steps. ----------------------------------------------------------------------------- 5.7. Disable all console access The Linux-PAM library installed by default on your system allows the system administrator to choose how applications authenticate users, such as for console access, program and file access. In order to disable all these accesses for the users, you must comment out all lines that refer to pam_console.so in the /etc/pam.d/ directory. This step is a continuation of the above hack Disable console program access. The following script will do the trick automatically for you. As root creates the disabling.sh script file, touch disabling.sh and add the following lines inside: # !/bin/sh cd /etc/pam.d for i in * ; do sed '/[^#].*pam_console.so/s/^/#/' < $i > foo && mv foo $i done Make this script executable with the following command and execute it: [root@deep] /# chmod 700 disabling.sh [root@deep] /# ./disabling.sh This will comment out all lines that refer to pam_console.so for all files located under /etc/pam.d directory. Once the script has been executed, you can remove it from your system. ----------------------------------------------------------------------------- 5.8. The inetd - /etc/inetd.conf file inetd, called also the super server, will load a network program based upon a request from the network. The inetd.conf file tells inetd which ports to listen to and what server to start for each port. The first thing to look at as soon as you put your Linux system on ANY network is what services you need to offer. Services that you do not need to offer should be disabled and uninstalled so that you have one less thing to worry about, and attackers have one less place to look for a hole. Look at your /etc/inetd.conf file to see what services are being offered by your inetd program. Disable what you do not need by commenting them out by adding a # at the beginning of the line, and then sending your inetd process a SIGHUP command to update it to the current inetd.conf file. 1. Change the permissions on this file to 600. [root@deep] /#chmod 600 /etc/inetd.conf 2. Ensure that the owner is root. [root@deep] /# stat /etc/inetd.conf File: "/etc/inetd.conf" Size: 2869 Filetype: Regular File Mode: (0600/-rw-------) Uid: ( 0/ root) Gid: ( 0/ root) Device: 8,6 Inode: 18219 Links: 1 Access: Wed Sep 22 16:24:16 1999(00000.00:10:44) Modify: Mon Sep 20 10:22:44 1999(00002.06:12:16) Change: Mon Sep 20 10:22:44 1999(00002.06:12:16) 3. Edit the inetd.conf file vi /etc/inetd.conf and disable services like: ftp, telnet, shell, login, exec, talk, ntalk, imap, pop-2, pop-3, finger, auth, etc. unless you plan to use it. If it's turned off, it's much less of a risk. # To re-read this file after changes, just do a 'killall -HUP inetd' # #echo stream tcp nowait root internal #echo dgram udp wait root internal #discard stream tcp nowait root internal #discard dgram udp wait root internal #daytime stream tcp nowait root internal #daytime dgram udp wait root internal #chargen stream tcp nowait root internal #chargen dgram udp wait root internal #time stream tcp nowait root internal #time dgram udp wait root internal # # These are standard services. # #ftp stream tcp nowait root /usr/sbin/tcpd in.ftpd -l -a #telnet stream tcp nowait root /usr/sbin/tcpd in.telnetd # # Shell, login, exec, comsat and talk are BSD protocols. # #shell stream tcp nowait root /usr/sbin/tcpd in.rshd #login stream tcp nowait root /usr/sbin/tcpd in.rlogind #exec stream tcp nowait root /usr/sbin/tcpd in.rexecd #comsat dgram udp wait root /usr/sbin/tcpd in.comsat #talk dgram udp wait root /usr/sbin/tcpd in.talkd #ntalk dgram udp wait root /usr/sbin/tcpd in.ntalkd #dtalk stream tcp wait nobody /usr/sbin/tcpd in.dtalkd # # Pop and imap mail services et al # #pop-2 stream tcp nowait root /usr/sbin/tcpd ipop2d #pop-3 stream tcp nowait root /usr/sbin/tcpd ipop3d #imap stream tcp nowait root /usr/sbin/tcpd imapd # # The Internet UUCP service. # #uucp stream tcp nowait uucp /usr/sbin/tcpd /usr/lib/uucp/uucico -l # # Tftp service is provided primarily for booting. Most sites # run this only on machines acting as "boot servers." Do not uncomment # this unless you *need* it. # #tftp dgram udp wait root /usr/sbin/tcpd in.tftpd #bootps dgram udp wait root /usr/sbin/tcpd bootpd # # Finger, systat and netstat give out user information which may be # valuable to potential "system crackers." Many sites choose to disable # some or all of these services to improve security. # #finger stream tcp nowait root /usr/sbin/tcpd in.fingerd #cfinger stream tcp nowait root /usr/sbin/tcpd in.cfingerd #systat stream tcp nowait guest /usr/sbin/tcpd /bin/ps -auwwx #netstat stream tcp nowait guest /usr/sbin/tcpd /bin/netstat -f inet # # Authentication # #auth stream tcp nowait nobody /usr/sbin/in.identd in.identd -l -e -o # # End of inetd.conf 4. [root@deep] /# killall -HUP inetd 5. One more security measure you can take to secure the inetd.conf file is to set it immutable, using the chattr command. To set the file immutable simply, execute the following command: [root@deep] /# chattr +i /etc/inetd.conf This will prevent any changes accidental or otherwise to the inetd.conf file. A file with the immutable attribute set i cannot be modified, deleted or renamed, no link can be created to this file and no data can be written to it. The only person that can set or clear this attribute is the super-user root. If you wish later to modify the inetd.conf file you will need to unset the immutable flag: To unset the immutable flag, simply execute the following command: [root@deep] /# chattr -i /etc/inetd.conf Note : Don't forget to send your inetd process a SIGHUP signal killall -HUP inetd after making change to your inetd.conf file. The services you enable on a selected host depend on the functions you want the host to provide. Functions could support the selected network service, other services hosted on this computer, or development and maintenance of the operating system and applications. ----------------------------------------------------------------------------- 5.9. TCP_WRAPPERS By default Red Hat Linux allows all service requests. Using TCP_WRAPPERS makes securing your servers against outside intrusion is a lot simpler and painless then you would expect. Deny all hosts by putting ALL: ALL@ALL, PARANOID in the /etc/hosts.deny file and explicitly list trusted hosts who are allowed to your machine in the /etc/hosts.allow file. This is the safest and the best configuration. TCP_WRAPPERS is controlled from two files and the search stops at the first match. /etc/hosts.allow /etc/hosts.deny Access will be granted when a daemon, client pair matches an entry in the / etc/hosts.allow file. Otherwise, access will be denied when a daemon, client pair matches an entry in the /etc/hosts.deny file. Otherwise, access will be granted. 1. Edit the hosts.deny file vi /etc/hosts.deny and add the following lines: Access is denied by default. # Deny access to everyone. ALL: ALL@ALL, PARANOID # Matches any host whose name does not match its address, see below. Which means all services, all locations, so any service not explicitly allowed is then blocked, unless they are permitted access by entries in the allow file. Note : With the parameter PARANOID; If you intend to run telnet or ftp services on your server, dont forget to add the client's machine name and IP address in your /etc/hosts file on the server or you can expect to wait several minutes for the DNS lookup to time out, before you get a login: prompt. 2. Edit the hosts.allow file vi /etc/hosts.allow and add for example, the following line: The explicitly authorized host are listed in the allow file. As an example:sshd: 208.164.186.1 gate.openna.com, For your client machine: 208.164.186.1 is the IP address and gate.openna.com the host name of one of your client allowed using sshd. 3. The tcpdchk program is the tcpd wrapper configuration checker. It examines your tcp wrapper configuration and reports all potential and real problems it can find. After your configuration is done, run the program tcpdchk. [root@deep] /# tcpdchk Note : Error messages may look like this: warning: /etc/hosts.allow, line 6: can't verify hostname: gethostbyname(win.openna.com) failed. If you receive this kind of error message, check in your DNS configuration file for the existence of this hostname. ----------------------------------------------------------------------------- 5.9.1. Don't display system issue file If you don't want your systems issue file to be displayed when people log in remotely, you can change the telnet option in your /etc/inetd.conf file to look like: telnet stream tcp nowait root /usr/sbin/tcpd in.telnetd -h Adding the -h flag on the end will cause the daemon to not display any system information and just hit the user with a login: prompt. This hack is only necessary if you are using a telnet daemon on your server instead I recommend you use SSH. ----------------------------------------------------------------------------- 5.10. The /etc/host.conf file Linux uses a resolver library to obtain the IP address corresponding to a host name. The /etc/host.conf file specifies how names are resolved. The entries in the etc/host.conf file tell the resolver library what services to use, and in what order, to resolve names. Edit the host.conf file vi /etc/ host.conf and add the following lines: # Lookup names via DNS first then fall back to /etc/hosts. order bind,hosts # We have machines with multiple IP addresses. multi on # Check for IP address spoofing. nospoof on The order option indicates the order of services. The sample entry specifies that the resolver library should first consult the name server to resolve a name and then check the /etc/hosts file. It is recommended to set the resolver library to first check the name server, bind and then the hosts file (hosts) for better performance and security on all your servers. Of course you must have the DNS/BIND software installed or this configuration will not work. The multi option determines whether a host in the /etc/hosts file can have multiple IP addresses i.e.multiple interface ethN. Hosts that have more than one IP address are said to be multiomed, because the presence of multiple IP addresses implies that host has several network interfaces. As an example, a Gateway Server will always have multiple IP address and must have this option set to ON. The nospoof option indicates to take care of not permitting spoofing on this machine. IP-Spoofing is a security exploit that works by tricking computers in a trust relationship that you are someone that you really aren't. In this type of attack, a machine is set up to look like a legitimate server and then issue connections and other types of network activities to legitimate end systems, other servers or large data repository systems. This option must be set ON for all types of servers. ----------------------------------------------------------------------------- 5.11. The /etc/services file The port numbers on which certain standard services are offered are defined in the RFC 1700 Assigned Numbers. The /etc/services file enables server and client programs to convert service names to these numbers -ports. The list is kept on each host and it is stored in the file /etc/services. Only the "root" user is allowed to make modification in this file and it is rare to edit the /etc/services file to make change since it already contains the more common service names to port numbers. To improve security, we can immunize this file to prevent unauthorized deletion or addition of services. To immunize the / etc/services file, use the command: [root@deep] /#chattr +i /etc/services ----------------------------------------------------------------------------- 5.12. The /etc/securetty file The /etc/securetty file allows you to specify which TTY devices the root user is allowed to login on. The /etc/securetty file is read by the login program usually /bin/login. Its format is a list of the tty devices names allowed, and for all others that are commented out or do not appear in this file, root login is disallowed. Disable any tty that you do not need by commenting them out # at the beginning of the line. Edit the securetty file vi, /etc/securetty and comment out the following lines: tty1 #tty2 #tty3 #tty4 #tty5 #tty6 #tty7 #tty8 Which means only root is allowed to login on tty1. This is my recommendation, allowing root to log in only on one tty device and use the su command to switch to root if you need more. devices to log in as root. ----------------------------------------------------------------------------- 5.13. Special accounts It is important to DISABLE ALL default vendor accounts that you don't use on your system, some accounts exist by default even if you have not installed the related services on your server. This should be checked after each upgrade or new software installation. Linux provides these accounts for various system activities, which you may not need if the services are not installed on your server. If you do not need the accounts, remove them. The more accounts you have, the easier it is to access your system. We assume you are using the Shadow password suite on your Linux system. If you are not, you should consider doing so, as it helps to tighten up security somewhat. This must already be set if you've followed our instructions till now and selected under the Authentication Configuration the option to Enable Shadow Passwords see Post Partitioning for more information. To delete user on your system, use the command: [root@deep] /# userdel username To delete group on your system, use the command: [root@deep] /# groupdel username 1. Type the following commands on your terminal to delete users listed below: [root@deep] /# userdel adm [root@deep] /# userdel lp [root@deep] /# userdel sync [root@deep] /# userdel shutdown [root@deep] /# userdel halt [root@deep] /# userdel news [root@deep] /# userdel uucp [root@deep] /# userdel operator [root@deep] /# userdel games (1) [root@deep] /# userdel gopher [root@deep] /# userdel ftp (2) (1) Delete this user if you don't use X Window Server. (2) Delete this user if you don't use ftp anonymous server. By default, the userdel command will not delete a user's home directory. If you want the home directories of accounts to be deleted too, then add the -r option to the userdel command. 2. Type the following commands on your terminal to delete the usersgroups listed below: [root@deep] /# groupdel adm [root@deep] /# groupdel lp [root@deep] /# groupdel news [root@deep] /# groupdel uucp [root@deep] /# groupdel games (1) [root@deep] /# groupdel dip [root@deep] /# groupdel pppusers [root@deep] /# groupdel popusers (2) [root@deep] /# groupdel slipusers (1) Delete this group if you don't use X Window Server. (2) Delete this group if you don't use pop server for email. 3. Add the necessary user to the system, to add a new user on your system, use the command: [root@deep] /# useradd username To add or change password for user on your system, use the command: [root@deep] /# passwd username For example: [root@deep] /# useradd admin [root@deep] /# passwd admin The output should look something like this. Changing password for user admin New UNIX password: somepasswd passwd: all authentication tokens updated successfully 4. The immutable bit can be used to prevent accidentally deleting or overwriting a file that must be protected. It also prevents someone from creating a symbolic link to this file, which has been the source of attacks involving the deletion of /etc/passwd, /etc/shadow, /etc/group or /etc/gshadow. To set the immutable bit on the passwords and groups files, use the command: [root@deep] /# chattr +i /etc/passwd [root@deep] /# chattr +i /etc/shadow [root@deep] /# chattr +i /etc/group [root@deep] /# chattr +i /etc/gshadow Note : In future, if you intend to add or delete users, passwords, usergroups, or group files, you must unset the immutable bit on all those files or you will not be able to make your changes. Also if you intend to install an RPM program that will automatically add a new user to the different immunized passwd and group files, then you will receive an error message during the install if you have not unset the immutable bit from those files. ----------------------------------------------------------------------------- 5.14. Blocking; su to root, by one and sundry The su Substitute User command allows you to become other existing users on the system. For example you can temporarily become root and execute commands as the super-user root. If you don't want anyone to su to root or restrict su command to certain users then add the following two lines to the top of your su configuration file in the /etc/pam.d/ directory. We highly recommend that you limit the person allowed to su to the root account. 1. Edit the su file vi /etc/pam.d/su and add the following two lines to the top of the file: auth sufficient /lib/security/pam_rootok.so debug auth required /lib/security/pam_wheel.so group=wheel After adding the two lines above, the /etc/pam.d/su file should look like this: #%PAM-1.0 auth sufficient /lib/security/pam_rootok.so debug auth required /lib/security/pam_wheel.so group=wheel auth required /lib/security/pam_pwdb.so shadow nullok account required /lib/security/pam_pwdb.so password required /lib/security/pam_cracklib.so password required /lib/security/pam_pwdb.so shadow use_authtok nullok session required /lib/security/pam_pwdb.so session optional /lib/security/pam_xauth.so Which mean only those who are a member of the wheel group can su to root; it also includes logging. Note that the wheel group is a special account on your system that can be used for this purpose. You cannot use any group name you want to make this hack. This hack combined with specifying which TTY devices root is allowed to login on will improve your security a lot on the system. 2. Now that we have defined the wheel group in our /etc/pam.d/su file configuration, it is time to add some users allowed to su to root account. If you want to make, for example, the user admin a member of the wheel group, and thus be able to su to root, use the following command: [root@deep] /# usermod -G10 admin   +  Which means G is a list of supplementary groups,   +  Where the user is also a member of, 10 is the numeric value of the user's ID wheel,   +  admin is the user we want to add to wheel group. Use the same command above for all users on your system you want to be able to su to root account. If you can't su in a GNOME terminal, it's because you've used the wrong terminal. So don't think that this advice simply doesn't work because of a terminal problem!. ----------------------------------------------------------------------------- 5.15. Put limits on resource The limits.conf file located under the /etc/security directory can be used to control and limit resources for the users on your system. It is important to set resource limits on all your users so they can't perform denial of service attacks number of processes, amount of memory, etc). These limits will have to be set up for the user when he or she logs in. For example, limits for all users on your system might look like this. 1. Edit the limits.conf file vi /etc/security/limits.conf and add or change the lines to read: * hard core 0 * hard rss 5000 * hard nproc 20 This says to prohibit the creation of core files - core 0, restrict the number of processes to 20 - nproc 20, and restrict memory usage to 5M - rss 5000 for everyone except the super user root. All of the above only concern users who have entered through the login prompt on your system. With this kind of quota, you have more control on the processes, core files, and memory usage that users may have on your system. The asterisk * mean: all users that logs in on the server. 2. You must also edit the /etc/pam.d/login file and add the following line to the bottom of the file: session required /lib/security/pam_limits.so After adding the line above, the /etc/pam.d/login file should look like this: #%PAM-1.0 auth required /lib/security/pam_securetty.so auth required /lib/security/pam_pwdb.so shadow nullok auth required /lib/security/pam_nologin.so account required /lib/security/pam_pwdb.so password required /lib/security/pam_cracklib.so password required /lib/security/pam_pwdb.so nullok use_authtok md5 shadow session required /lib/security/pam_pwdb.so session required /lib/security/pam_limits.so #session optional /lib/security/pam_console.so 3. Finally edit the /etc/profile file and change the following line: ulimit -c 1000000 to read: ulimit -S -c 1000000 > /dev/null 2<&1 This modification is required so as to avoid getting error messages like this Unable to reach limit during login:. ----------------------------------------------------------------------------- 5.16. Control mounting a file system You can have more control on mounting a file system like /home and /tmp partitions with some nifty options like noexec, nodev, and nosuid. This can be setup in the /etc/fstab text file. The fstab file contains descriptive information about the various file systems mount options; each line addresses one file system. Details regarding to security options in the fstab text file are: defaults: Allow everything quota, read-write, and suid on this partition. noquota: Do not set users quotas on this partition. nosuid: Do not set SUID/SGID access on this partition. nodev: Do not set character or special devices access on this partition. noexec: Do not set execution of any binaries on this partition. quota: Allow users quotas on this partition. ro: Allow read-only on this partition. rw: Allow read-write on this partition. suid: Allow SUID/SGID access on this partition. For more information on options that you can set in this file fstab, see the man pages about mount(8). Edit the fstab file vi /etc/fstab and change it depending on your needs. For example: /dev/sda11 /tmp ext2 defaults 1 2 /dev/sda6 /home ext2 defaults 1 2 To read: /dev/sda11 /tmp ext2 defaults,rw,nosuid,nodev,noexec 1 2 /dev/sda6 /home ext2 defaults,rw,nosuid,nodev 1 2 nosuid, Meaning do not allow set-user-identifier or set-group-identifier bits to take effect, nodev, do not interpret character or block special devices on this file system partition, noexec, do not allow execution of any binaries on the mounted file system. Take a note that we have added the rw option to the modified lines above. This is because the default options for these lines are defaults, which means to set quota, read-write, and suid, so we must add the rw option to continue having read-write access on these modified file systems. For our example above, the /dev/sda11 represent our /tmp directory partition on the system, and /dev/sda6 the /home directory partition. Of course this will be not the same for you, depending on how you have partitioned your hard disk and what kind of disks are installed on your system, IDE -hda, hdb, etc or SCSI -sda, sdb, etc. Once you have made the necessary adjustments to the /etc/fstab file, it is time to makethe Linux system aware about the modification. This can be accomplished with the following commands: [root@deep] /#mount -oremount /home/ [root@deep] /#mount -oremount /tmp/ Each file system that has been modified must be remounted with the command show above. In our example we have modified the /home/, and /tmp/ file system and it is for this reason that we remount these file system with the above commands. ----------------------------------------------------------------------------- 5.17. Conceal binary RPM Once you have installed all the software that you need on yo42ur Linux server with the RPM command, it's a good idea for better security to move it to a safe place like a floppy disk or other safe place of your choice. With this method if some one accesses your server and has the intention to install software like trojan horses, password thieves etc. with RPM command, he shouldn't be able to do so. Of course, if in the future you want to install or upgrade new software via RPM, all you have to do is to replace the RPM binary to its original directory again. To move the RPM binary on the floppy disk, use the command: [root@deep] /# mount /dev/fd0 /mnt/floppy/ [root@deep] /# mv /bin/rpm /mnt/floppy/ [root@deep] /# umount /mnt/floppy Never uninstall the RPM program completely from your system or you will be unable to reinstall it again later, since to install RPM or other software you need to have RPM commands available. Another thing you can do is change the default permission of the rpm command from 755 to 700. With this modification, non-root users can't use the rpm program to query, install etc; in case you forget to move it to a safe place after installation of new programs. To change the default permission of /bin/rpm, use the command: [root@deep] /# chmod 700 /bin/rpm ----------------------------------------------------------------------------- 5.18. Shell logging To make it easy for you to repeat long commands, the bash shell stores up to 500 old commands in the ~/.bash_history file where ~/ is your home directory. Each user that has an account on the system will have this file .bash_history in their home directory. Reducing the number of old commands the .bash_history files can hold may protect users on the server who enter by mistake their password on the screen in plain text and have their password stored for a long time in the .bash_history file. 1. The HISTFILESIZE and HISTSIZE lines in the /etc/profile file determine the size of old commands the .bash_history file for all users on your system can hold. For all accounts I would highly recommend setting the HISTFILESIZE and HISTSIZE in /etc/profile file to a low value such as 20. Edit the profile file vi /etc/profile and change the lines to: HISTFILESIZE=20 HISTSIZE=20 Which mean, the .bash_history file in each users home directory can store 20 old commands and no more. Now, if a cracker tries to see the ~ /.bash_history file of users on your server to find some password typed by mistake in plain text, he or she has less chance to find one. 2. The administrator should also add into the /etc/skel/.bash_logout file the rm -f $HOME/.bash_history line, so that each time a user logs out, its .bash_history file will be deleted so crackers will not be able to use .bash_history file of users who are not presently logged into the system. Edit the .bash_logout file vi /etc/skel/.bash_logout and add the following line: rm -f $HOME/.bash_history The above hack will only work for future users you'll add in the server. If you already have existing users in the /etc/passwd file, you must edit and add the above line into their .bash_logout files manually. ----------------------------------------------------------------------------- 5.19. The LILO and lilo.conf file LILO is the most commonly used boot loader for Linux. It manages the boot process and can boot Linux kernel images from floppy disks, hard disks or can even act as a boot manager for other operating systems. LILO is very important in the Linux system and for this reason, we must protect it the best we can. The most important configuration file of LILO is the lilo.conf file, which resides under the /etc directory. It is with this file that we can configure and improve the security of our LILO program and Linux system. Following are three important options that will improve the security of our valuable LILO program. Adding: timeout=00 This option controls how long in seconds LILO waits for user input before booting to the default selection. One of the requirements of C2 security is that this interval be set to 0 unless the system dual boots something else. Adding: restricted This option asks for a password only, if parameters are specified on the command line (e.g. linux single). The option restricted can only be used together with the password option. Make sure you use this one on each image. Adding: password= This option asks the user for a password when trying to load the Linux system in single mode. Passwords are always case-sensitive, also make sure the /etc/lilo.conf file is no longer world readable, or any user will be able to read the password. An example of protected lilo.conf file. 1. Edit the lilo.conf file vi /etc/lilo.conf and add or change the above three options as show: boot=/dev/sda map=/boot/map install=/boot/boot.b prompt timeout=00 ß change this line to 00. Default=linux restricted ß add this line. password= (1) image=/boot/vmlinuz-2.2.12-20 label=linux initrd=/boot/initrd-2.2.12-10.img root=/dev/sda6 read-only (1) add this line and put your password. 2. Because the configuration file /etc/lilo.conf now contains unencrypted passwords, it should only be readable for the super-user root. [root@deep] /# chmod 600 /etc/lilo.conf will be no longer world readable. 3. Now we must update our configuration file /etc/lilo.conf for the change to take effect. [root@deep] /# /sbin/lilo -v to update the lilo.conf file. 4. One more security measure you can take to secure the lilo.conf file is to set it immutable, using the chattr command. To set the file immutable simply, use the command: [root@deep] /# chattr +i /etc/lilo.conf And this will prevent any changes accidental or otherwise to the lilo.conf file. If you wish to modify the lilo.conf file you will need to unset the immutable flag: To unset the immutable flag, use the command: [root@deep] /# chattr -i /etc/lilo.conf ----------------------------------------------------------------------------- 5.20. Disable Ctrl-Alt-Delete keyboard shutdown command Commenting out the line with a # listed below in your /etc/inittab file will disable the possibility of using the Ctrl-Alt-Delete command to shutdown your computer. This is pretty important if you don't have the best physical security on the box. To do this, edit the inittab file vi /etc/inittab and change the line: ca::ctrlaltdel:/sbin/shutdown -t3 -r now To read: #ca::ctrlaltdel:/sbin/shutdown -t3 -r now Now, for the change to take effect type in the following at a prompt: [root@deep] /#/sbin/init q ----------------------------------------------------------------------------- 5.21. Physical hard copies of all-important logs One of the most important security considerations is the integrity of the different log files under the /var/log directory on your server. If despite each of the security functions put in place on our server a cracker can gain access to it, our last defense is the log file system, so it is very important to consider a method of being sure of the integrity of our log files. If you have a printer installed on your server, or on a machine on your network, a good idea would be to have actual physical hard copies of all-important logs. This can be easily accomplished by using a continuous feed printer and having the syslog program sending all logs you seem important out to /dev/lp0 the printer device. Cracker can change the files, programs, etc on your server, but can do nothing when you have a printer that prints a real paper copy of all of your important logs. Example 5-3. Print log reports For logging of all telnet, mail, boot messages and ssh connections from your server to the printer attached to this server, you would want to add the following line to the "/etc/syslog.conf" file: Edit the syslog.conf file vi / etc/syslog.conf and add at the end of this file the following line: authpriv.*;mail.*;local7.*;auth.*;daemon.info /dev/lp0 Now restart your syslog daemon for the change to take effect: [root@deep] /# /etc/rc.d/init.d/syslog restart For logging of all telnet, mail, boot messages and ssh connections from your server to the printer attached to a remote server in your local network, then you would want to add the following line to /etc/syslog.conf file on the remote server. If you don't have a printer in your network, you can also copy all the log files to another machine; simply omit the first step below of adding /dev/lp0 to your syslog.conf file on remote and go directly to the -r option step on remote. Using the feature of copying all the log files to another machine will give you the possibility to control all syslog messages on one host and will tear down administration needs. Edit the syslog.conf file vi /etc/syslog.conf on the remote server for example: mail.openna.com and add at the end of this file the following line: authpriv.*;mail.*;local7.*;auth.*;daemon.info /dev/lp0 Since the default configuration of the syslog daemon is to not receive any messages from the network, we must enable on the remote server the facility to receive messages from the network. To enable the facility to receive messages from the network on the remote server, add the following option -r to your syslog daemon script file only on the remote host: Edit the syslog daemon vi +24 /etc/rc.d/init.d/syslog and change: daemon syslogd -m 0 To read: daemon syslogd -r -m 0 Now restart your syslog daemon on the remote host for the change to take effect: [root@mail /]# /etc/rc.d/init.d/syslog restart Now, if we have a firewall on the remote server you are supposed to have one), we must add or verify the existence of the following lines: ipchains -A input -i $EXTERNAL_INTERFACE -p udp \ (1) -s $SYSLOG_CLIENT \ (2) -d $IPADDR 514 -j ACCEPT (3) (1) Where EXTERNAL_INTERFACE="eth0" in the firewall file. (2) Where IPADDR="208.164.186.2" in the firewall file. (3) Where SYSLOG_CLIENT="208.164.168.0/24" in the firewall file. Now restart your firewall on the remote host for the change to take effect: [root@mail /]# /etc/rc.d/init.d/firewall restart This firewall rule will allow incoming UDP packet on port 514 (syslog port) on the remote server that come from our internal client to be accepted. For more information on Firewall see Chapter 7 Networking firewall. Finally, edit the syslog.conf file vi /etc/syslog.conf on the local server, and add at the end of this file the following line: authpriv.*;mail.*;local7.*;auth.*;daemon.info @mail Where mail is the hostname of the remote server. Now if anyone ever hacks your box and menaces to erase vital system logs, you still have a hard copy of everything. It should then be fairly simple to trace where they came from and deal with it accordingly. Now restart your syslog daemon for the change to take effect: [root@deep] /# /etc/rc.d/init.d/syslog restart Same as on the remote host, we must add or verify the existence of the following lines in our firewall script file on the local host: ipchains -A output -i $EXTERNAL_INTERFACE -p udp \ (1) -s $IPADDR 514 \ (2) -d $SYSLOG_SERVER 514 -j ACCEPT (3) (1) Where EXTERNAL_INTERFACE="eth0" in the firewall file. (2) Where IPADDR="208.164.186.1" in the firewall file. (3) Where SYSLOG_SERVER="mail.openna.com" in the firewall file. Now restart your firewall for the change to take effect: [root@deep] /# /etc/rc.d/init.d/firewall restart This firewall rule will allow outgoing UDP packet on port 514 syslog port on the local server destined to the remote syslog server to be accepted. For more information on Firewall see chapter 7 Networking firewall. Important : Never use your Gateway Server as a host to control all syslog messages; this is a very bad idea. More options and strategies exist with the sysklogd program, see the man pages about sysklogd(8), syslog(2), and syslog.conf(5) for more information. ----------------------------------------------------------------------------- 5.22. Tighten scripts under /etc/rc.d/ Fix the permissions of the script files that are responsible for starting and stopping all your normal processes that need to run at boot time. [root@deep] /# chmod -R 700 /etc/rc.d/init.d/* Which means just root is allowed to Read, Write, and Execute scripts files on this directory. I don't think regular users need to know what is inside those script files. Important : If you install a new program or update a program that use the init system V script located under /etc/rc.d/init.d/ directory, don't forget to change or verify the permission of this script file again. ----------------------------------------------------------------------------- 5.22.1. The /etc/rc.d/rc.local file By default, when you login to a Linux box, it tells you the Linux distribution name, version, kernel version, and the name of the server. This is giving away too much info. We'd rather just prompt users with a Login: 1. To do this, Edit the /etc/rc.d/rc.local file and Place # in front of the following lines as shown: # This will overwrite /etc/issue at every boot. So, make any changes you # want to make to /etc/issue here or you will lose them when you reboot. #echo "" > /etc/issue #echo "$R" >> /etc/issue #echo "Kernel $(uname -r) on $a $(uname -m)" >> /etc/issue # #cp -f /etc/issue /etc/issue.net #echo >> /etc/issue 2. Then, remove the following files: issue.net and issue under /etc directory: [root@deep] /# rm -f /etc/issue [root@deep] /# rm -f /etc/issue.net The /etc/issue.net file is the login banner that users will see when they make a networked i.e. telnet, SSH connection to your machine. You will find it in the /etc directory, along with a similar file called issue, which is the login banner that gets displayed to local users. It is simply a text file and can be customized to your own taste, but be aware that as noted above, if you do change it or remove it like we do, you'll also need to modify the /etc /rc.d/rc.local shell script, which re-creates both the issue and issue.net files every time the system boots. ----------------------------------------------------------------------------- 5.23. Bits from root-owned programs A regular user will be able to run a program as root if it is set to SUID root. All programs and files on your computer with the s bits appearing on its mode, have the SUID -rwsr-xr-x or SGID -r-xr-sr-x bit enabled. Because these programs grant special privileges to the user who is executing them, it is important to remove the s bits from root-owned programs that won't absolutely require such privilege. This can be accomplished by executing the command chmod a-s with the name(s) of the SUID/SGID files as its arguments. Such programs include, but aren't limited to:   *  Programs you never use.   * Programs that you don't want any non-root users to run.   * Programs you use occasionally, and don't mind having to su to root to run. We've placed an asterisk * next to each program we personally might disable and consider to be not absolutely required for the working of our server. Remember that your system needs some suid root programs to work properly, so be careful. make your choices based on your requirements. To find all files with the s bits from root-owned programs, use the command: [root@deep]#find / -type f \( -perm -04000 -o -perm -02000 \) \-exec ls 'lg {} \; *-rwsr-xr-x 1 root root 35168 Sep 22 23:35 /usr/bin/chage *-rwsr-xr-x 1 root root 36756 Sep 22 23:35 /usr/bin/gpasswd *-r-xr-sr-x 1 root tty 6788 Sep 6 18:17 /usr/bin/wall -rwsr-xr-x 1 root root 33152 Aug 16 16:35 /usr/bin/at -rwxr-sr-x 1 root man 34656 Sep 13 20:26 /usr/bin/man -r-s--x--x 1 root root 22312 Sep 25 11:52 /usr/bin/passwd -rws--x--x 2 root root 518140 Aug 30 23:12 /usr/bin/suidperl -rws--x--x 2 root root 518140 Aug 30 23:12 /usr/bin/sperl5.00503 -rwxr-sr-x 1 root slocate 24744 Sep 20 10:29 /usr/bin/slocate *-rws--x--x 1 root root 14024 Sep 9 01:01 /usr/bin/chfn *-rws--x--x 1 root root 13768 Sep 9 01:01 /usr/bin/chsh *-rws--x--x 1 root root 5576 Sep 9 01:01 /usr/bin/newgrp *-rwxr-sr-x 1 root tty 8328 Sep 9 01:01 /usr/bin/write -rwsr-xr-x 1 root root 21816 Sep 10 16:03 /usr/bin/crontab *-rwsr-xr-x 1 root root 5896 Nov 23 21:59 /usr/sbin/usernetctl *-rwsr-xr-x 1 root bin 16488 Jul 2 10:21 /usr/sbin/traceroute -rwxr-sr-x 1 root utmp 6096 Sep 13 20:11 /usr/sbin/utempter -rwsr-xr-x 1 root root 14124 Aug 17 22:31 /bin/su *-rwsr-xr-x 1 root root 53620 Sep 13 20:26 /bin/mount *-rwsr-xr-x 1 root root 26700 Sep 13 20:26 /bin/umount *-rwsr-xr-x 1 root root 18228 Sep 10 16:04 /bin/ping *-rwxr-sr-x 1 root root 3860 Nov 23 21:59 /sbin/netreport -r-sr-xr-x 1 root root 26309 Oct 11 20:48 /sbin/pwdb_chkpwd To disable the suid bits on selected programs above, type the following commands: [root@deep] /# chmod a-s /usr/bin/chage [root@deep] /# chmod a-s /usr/bin/gpasswd [root@deep] /# chmod a-s /usr/bin/wall [root@deep] /# chmod a-s /usr/bin/chfn [root@deep] /# chmod a-s /usr/bin/chsh [root@deep] /# chmod a-s /usr/bin/newgrp [root@deep] /# chmod a-s /usr/bin/write [root@deep] /# chmod a-s /usr/sbin/usernetctl [root@deep] /# chmod a-s /usr/sbin/traceroute [root@deep] /# chmod a-s /bin/mount [root@deep] /# chmod a-s /bin/umount [root@deep] /# chmod a-s /bin/ping [root@deep] /# chmod a-s /sbin/netreport Example 5-4. Use man pages If you want to know what those programs do, type man program-name and read the man page. [root@deep] /# man netreport ----------------------------------------------------------------------------- 5.24. The kernel tunable parameters With the new version of Red Hat Linux 6.2 all kernel parameters available under the /proc/sys subdirectory of Linux can be configured at runtime. You can now use the new /etc/sysctl.conf file under Red Hat Linux 6.2 to modify and set kernel parameters at runtime. The sysctl.conf file is read and loaded each time the system reboots. All settings are now stored in the /etc/ sysctl.conf file. All modifications to /proc/sys should be made through /etc/ sysctl.conf, because they offer better for control, and are executed before rc.local or any other users scripts. We have shown you the networking security options that you must configure on your server for both Red Hat Linux version 6.1 and 6.2 below. ----------------------------------------------------------------------------- 5.24.1. Prevent your system responding to Ping Version 6.1 only Preventing your system for responding to ping request can be a big improvement in your network security since no one can ping on your server and receive an answer. The TCP/IP protocol suite has a number of loopholes that allows an attacker to leverage techniques in the form of covert channels to surreptitiously pass data in otherwise benign packets. Preventing your server from responding to ping requests can help to minimize this problem. An... [root@deep] /#echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_all ... should do the job such that your system won't respond to ping on any interface. You can add this line in your /etc/rc.d/rc.local file so the command will be automatically set if your system reboots. Not responding to pings would at least keep most "crackers" out because they would never even know it's there. To turn it backs on, simply do this: [root@deep] /#echo 0 > /proc/sys/net/ipv4/icmp_echo_ignore_all You can add this line in your /etc/rc.d/rc.local file so the command will be automatically set if your system reboots. Version 6.2 only Edit the /etc/sysctl.conf file and add the following line: # Enable ignoring ping request net.ipv4.icmp_echo_ignore_all = 1 You must restart your network for the change to take effect. The command to restart the network is the following: To restart all network devices manually on your system, use the following command: [root@deep] /# /etc/rc.d/init.d/network restart Setting network parameters [ OK ] Bringing up interface lo [ OK ] Bringing up interface eth0 [ OK ] Bringing up interface eth1 [ OK ] ----------------------------------------------------------------------------- 5.25. Refuse responding to broadcasts request As for the ping request, it's also important to disable broadcast request. When a packet is sent to an IP broadcast address (i.e. 192.168.1.255) from a machine on the local network, that packet is delivered to all machines on that network. Then all the machines on a network respond to this ICMP echo request and the result can be severe network congestion or outages -denial-of-service attacks. See the RFC 2644 for more information. Version 6.1 only [root@deep] /# echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts You can add this line in your /etc/rc.d/rc.local file so the command will be automatically set if your system reboots. Version 6.2 only Edit the /etc/sysctl.conf file and add the following line: # Enable ignoring broadcasts request net.ipv4.icmp_echo_ignore_broadcasts = 1 You must restart your network for the change to take effect. The command to restart the network is the following: To restart all networks devices manually on your system, use the following command: [root@deep] /# /etc/rc.d/init.d/network restart Setting network parameters [ OK ] Bringing up interface lo [ OK ] Bringing up interface eth0 [ OK ] Bringing up interface eth1 [ OK ] ----------------------------------------------------------------------------- 5.26. Routing Protocols Routing and routing protocols can create several problems. The IP source routing, where an IP packet contains details of the path to its intended destination, is dangerous because according to RFC 1122 the destination host must respond along the same path. If an attacker was able to send a source routed packet into your network, then he would be able to intercept the replies and fool your host into thinking it is communicating with a trusted host. I strongly recommend that you disable IP source routing to protect your server from this hole. To disable IP source routing on your server, type the following command in your terminal: Version 6.1 only [root@deep] /# for f in /proc/sys/net/ipv4/conf/*/accept_source_route; do > echo 0 > $f > done [root@deep] /# Add the above commands to the /etc/rc.d/rc.local script file and you'll not have to type it again the next time you reboot your system. Version 6.2 only Edit the /etc/sysctl.conf file and add the following line: # Disables IP source routing net.ipv4.conf.all.accept_source_route = 0 You must restart your network for the change to take effect. The command to restart the network is the following: [root@deep] /# /etc/rc.d/init.d/network restart Setting network parameters [ OK ] Bringing up interface lo [ OK ] Bringing up interface eth0 [ OK ] Bringing up interface eth1 [ OK ]   Take Note that the above command for Red Hat Linux 6.1 or 6.2 will disable Source Routed Packets on all your interfaces lo, ethN, pppN etc. ----------------------------------------------------------------------------- 5.27. Enable TCP SYN Cookie Protection A SYN Attack is a denial of service DoS attack that consumes all the resources on your machine, forcing you to reboot. Denial of service attacks -attacks which incapacitate a server due to high traffic volume or ones that tie-up system resources enough that the server cannot respond to a legitimate connection request from a remote system) are easily achievable from internal resources or external connections via extranets and Internet. To enable it, you have to do: Version 6.1.only [root@deep] /# echo 1 > /proc/sys/net/ipv4/tcp_syncookies Add the above commands to the /etc/rc.d/rc.local script file and you'll not have to type it again the next time you reboot your system. Version 6.2 only Edit the /etc/sysctl.conf file and add the following line: # Enable TCP SYN Cookie Protection net.ipv4.tcp_syncookies = 1 You must restart your network for the change to take effect. The command to restart the network is the following: [root@deep] /# /etc/rc.d/init.d/network restart Setting network parameters [ OK ] Bringing up interface lo [ OK ] Bringing up interface eth0 [ OK ] Bringing up interface eth1 [ OK ] If you receive an error message during execution of the above command, check that you have enabled the TCP syncookies option in your kernel configuration: IP: TCP syncookie support not enabled per default CONFIG_SYN_COOKIES Y/n/?. ----------------------------------------------------------------------------- 5.28. Disable ICMP Redirect Acceptance When hosts use a non-optimal or defunct route to a particular destination, an ICMP redirect packet is used by routers to inform the hosts what the correct route should be. If an attacker is able to forge ICMP redirect packets, he or she can alter the routing tables on the host and possibly subvert the security of the host by causing traffic to flow via a path you didn't intend. It's strongly recommended to disable ICMP Redirect Acceptance to protect your server from this hole. version 6.1 only [root@deep] /# for f in /proc/sys/net/ipv4/conf/*/accept_redirects; do > echo 0 > $f > done [root@deep] /# Add the above commands to the /etc/rc.d/rc.local script file and you'll not have to type it again the next time you reboot your system. Version 6.2 only Edit the /etc/sysctl.conf file and add the following line: # Disable ICMP Redirect Acceptance net.ipv4.conf.all.accept_redirects = 0 You must restart your network for the change to take effect. The command to restart manually the network is the following: [root@deep] /# /etc/rc.d/init.d/network restart Setting network parameters [ OK ] Bringing up interface lo [ OK ] Bringing up interface eth0 [ OK ] Bringing up interface eth1 [ OK ] Take Note that the above command for Red Hat Linux 6.1 or 6.2 will disable Redirect Acceptance Packets on all your interfaces lo, ethN, pppN etc. ----------------------------------------------------------------------------- 5.29. Enable always-defragging Protection Version 6.1 only This protection must be enabled if you use your Linux server as a gateway to masquerade internal traffic to the Internet IP Masquerading. [root@deep] /#echo 1 > /proc/sys/net/ipv4/ip_always_defrag Add the above commands to the /etc/rc.d/rc.local script file and you'll not have to type it again the next time you reboot your system. Version 6.2 only Edit the /etc/sysctl.conf file and add the following line: # Enable always defragging Protection net.ipv4.ip_always_defrag = 1 You must restart your network for the change to take effect. The command to manually restart the network is the following: [root@deep] /# /etc/rc.d/init.d/network restart Setting network parameters [ OK ] Bringing up interface lo [ OK ] Bringing up interface eth0 [ OK ] Bringing up interface eth1 [ OK ] ----------------------------------------------------------------------------- 5.30. Enable bad error message Protection Version 6.1 only This option will alert you to all bad error messages in your network. [root@deep] /#echo 1 > /proc/sys/net/ipv4/icmp_ignore_bogus_error_responses Add the above commands to the /etc/rc.d/rc.local script file and you'll not have to type it again the next time you reboot your system. Edit the /etc/sysctl.conf file and add the following line: Version 6.2 only # Enable bad error message Protection net.ipv4.icmp_ignore_bogus_error_responses = 1 You must restart your network for the change to take effect. The command to manually restart the network is the following: [root@deep] /# /etc/rc.d/init.d/network restart Setting network parameters [ OK ] Bringing up interface lo [ OK ] Bringing up interface eth0 [ OK ] Bringing up interface eth1 [ OK ] ----------------------------------------------------------------------------- 5.31. Enable IP spoofing protection The spoofing protection prevents your network from being the source of spoofed i.e. forged communications that are often used in DoS attacks. Version 6.1 only [root@deep] /# for f in /proc/sys/net/ipv4/conf/*/rp_filter; do > echo 1 > $f > done [root@deep] /# Add the above commands to the /etc/rc.d/rc.local script file and you'll not have to type it again the next time you reboot your system. Version 6.2 only Edit the /etc/sysctl.conf file and add the following line: # Enable IP spoofing protection, turn on Source Address Verification net.ipv4.conf.all.rp_filter = 1 You must restart your network for the change to take effect. The command to manually restart the network is the following: [root@deep] /# /etc/rc.d/init.d/network restart Setting network parameters [ OK ] Bringing up interface lo [ OK ] Bringing up interface eth0 [ OK ] Bringing up interface eth1 [ OK ] ----------------------------------------------------------------------------- 5.32. Log Spoofed, Source Routed and Redirect Packets This protection will log all Spoofed Packets, Source Routed Packets, and Redirect Packets to your log files. Version 6.1 only [root@deep] /# for f in /proc/sys/net/ipv4/conf/*/log_martians; do > echo 1 > $f > done [root@deep] /# Add the above commands to the /etc/rc.d/rc.local script file and you'll not have to type it again the next time you reboot your system. Version 6.2 only Edit the /etc/sysctl.conf file and add the following line: # Log Spoofed Packets, Source Routed Packets, Redirect Packets net.ipv4.conf.all.log_martians = 1 You must restart your network for the change to take effect. The command to manually restart the network is the following: [root@deep] /# /etc/rc.d/init.d/network restart Setting network parameters [ OK ] Bringing up interface lo [ OK ] Bringing up interface eth0 [ OK ] Bringing up interface eth1 [ OK ] ----------------------------------------------------------------------------- 5.33. Unusual or hidden files It is important to not forget to look everywhere on the system for unusual or hidden files -files that start with a period and are normally not shown by the ls command, as these can be used to hide tools and information password cracking programs, password files from other systems, etc.. A common technique on UNIX systems is to put a hidden directory or file in a user's account with an unusual name, something like '...' or '.. ' -dot dot space or ..-^G -dot dot ctrl-G. The find program can be used to look for hidden files. Example 5-5. Use find to find [root@deep] /# find / -name ".. " -print -xdev [root@deep] /# find / -name ".*" -print -xdev | cat -v Note : Files with names such as .xx and .mail have been used that is, files that might appear to be normal. All SUID and SGID files that still exist on your system after we have removed those that won't absolutely require such privilege are a potential security risk, and should be monitored closely. Because these programs grant special privileges to the user who is executing them, it is necessary to ensure that insecure programs are not installed. A favorite trick of crackers is to exploit SUID root programs, and leave a SUID program as a backdoor to get in the next time. Find all SUID and SGID programs on your system, and keep track of what they are so that you are aware of any changes, which could indicate a potential intruder. Use the following command to find all SUID/SGID programs on your system: [root@deep] /# find / -type f \( -perm -04000 -o -perm -02000 \) \-exec ls -lg {} \; Tip : See in this book under Securities Software/Monitoring Tools for more information about the software sXidthat will do the job for you automatically each day and report the results via mail. Group and world writable files and directories particularly system files partitions, can be a security hole if a cracker gains access to your system and modifies them. Additionally, world-writable directories are dangerous, since they allow a cracker to add or delete files as he or she wishes in these directories. In the normal course of operation, several files will be writable, including some from the /dev, /var/catman directories, and all symbolic links on your system. To locate all group & world-writable files on your system, use the command: [root@deep] /# find / -type f \( -perm -2 -o -perm -20 \) -exec ls -lg {} \; To locate all group & world-writable directories on your system, use the command: [root@deep] /# find / -type d \( -perm -2 -o -perm -20 \) -exec ls -ldg {} \; Tip : A file and directory integrity checker like Tripwire software can be used regularly to scan, manage and find modified group or world writable files and directories easily. See in this book under Securities Software/Monitoring Tools for more information about Tripwire. Don't permit any unowned file. Unowned files may also be an indication that an intruder has accessed your system. If you find unowned file or directory on your system, verify its integrity, and if all looks fine, give it an owner name. Some time you may uninstall a program and get an unowned file or directory related to this software; in this case you can remove the file or directory safely. To locate files on your system that do not have an owner, use the following command: [root@deep] /#find / -nouser -o -nogroup Please Note Once again, files reported under /dev directory don't count. Finding all the .rhosts files that could exist on your server should be a part of your regular system administration duties, as these files should not be permitted on your system. Remember that a cracker only needs one insecure account to potentially gain access to your entire network. You can locate all .rhosts files on your system with the following command: [root@deep] /#find /home -name .rhosts You can also use a cron job to periodically check for, report the contents of, and delete $HOME/.rhosts files. Also, users should be made aware that you regularly perform this type of audit, as directed by policy. To use a cron job to periodically check and report via mail all .rhosts files, do the following: Create as root the find_rhosts_files script file under /etc/cron.daily directory touch /etc/cron.daily/find_rhosts_files and add the following lines in this script file: #!/bin/sh /usr/bin/find /home -name .rhosts | (cat <               CERT Hotline:(+1) 412-268-7090               Facsimile:    (+1) 412-268-6989                CERT/CC personnel answer 8:00 a.m. to 8:00 p.m. EST (GMT 5)/EDT (GMT 4)) on working days; they are on call for emergencies during other hours and on weekends and holidays. ----------------------------------------------------------------------------- Chapter 6. Linux General Optimization At this stage of your configuration, you should now have a Linux server optimally configured and secured. Our server contains the most essential package and programs installed to be able to work properly and the most essential general security configuration. Before we continue and begin to install the services we want to share with our clients/users, it is important to now tune our Linux server. The tuning we will perform in the following chapter will be applied to the whole system. It also applies to present as well as future programs, such as services that we will later install. Generally, if you don't use a x386 Intel processor, Red Hat Linux out of the box is not optimized for your specific CPU architecture, most people now run Linux on a Pentium processor. The sections below will guide you through different steps to optimize your Linux server for your specific processor, memory, and network, as well as your file system. ----------------------------------------------------------------------------- 6.1. The /etc/profile file The /etc/profile file contains system wide environment stuff and startup programs. All customizations that you put in this file will apply for the entire environment variable on your system, so putting optimization flags in this file is a good choice. To squeeze the most performance from your x86 programs, you can use full optimization when compiling with the -O9 flag. Many programs contain -O2 in the Makefile. -O9 is the highest level of optimization. It will increase the size of what it produces, but it runs faster. Please Note it is not always true that the -O9 flag will make the best performance for your processor. If you have an x686 and above processor, surely, but below x686, not necessarily. When compiling, use the -fomit-frame-pointer switch for any kind of processor you may have. This will use the stack for accessing variables. Unfortunately, debugging is almost impossible with this option. You can also use the -mcpu=cpu_type and -march=cpu_type switch to optimize the program for the CPU listed to the best of GCC's ability. However, the resulting code will only be run able on the indicated CPU or higher. The optimization options apply only when we compile and install a new program in our server. These optimizations don't play any role in our Linux base system; it just tells our compiler to optimize the new programs that we will install with the optimization flags we have specified in the /etc/ profile file. Below are the optimization flags that we recommend you put in your /etc/ profile file depending on your CPU architecture. Recommended optimization flags 1. For CPU i686 or PentiumPro, Pentium II, Pentium III In the /etc/profile file, put this line for a PentiumPro, Pentium II and III Pro Processor family: CFLAGS=-O9 -funroll-loops -ffast-math -malign-double -mcpu=pentiumpro -march=pentiumpro -fomit-frame-pointer -fno-exceptions For CPU i586 or Pentium: In the /etc/profile file, put this line for a Pentium Processor family: CFLAGS=-O3 -march=pentium -mcpu=pentium -ffast-math -funroll-loops -fomit-frame-pointer -fforce-mem -fforce-addr -malign-double -fno-exceptions For CPU i486: In the /etc/profile file, put this line for a i486 Processor family: CFLAGS=-O3 -funroll-all-loops -malign-double -mcpu=i486 -march=i486 -fomit-frame-pointer -fno-exceptions 2. Now after the selection of your CPU settings -i686, i586, or i486 a bit further down in the /etc/profile file, add CFLAGS LANG LESSCHARSET to the export line: export PATH PS1 HOSTNAME HISTSIZE HISTFILESIZE USER LOGNAME MAIL INPUTRC CFLAGS LANG LESSCHARSET 3. Log out and log back in; after this, the new CFLAGS environment variable is set, and software and other configure tool will recognize that. Pentium Pro/II/III optimizations will only work with egcs or pgcc compilers. The egcs compiler is already installed on your Server by default so you don't need to worry about it. Below is the explanation of the different optimization options we use: -funroll-loops The -funroll-loops optimization option will perform the optimization of loop unrolling and will do it only for loops whose number of iterations can be determined at compile time or run time. -funroll-all-loops The -funroll-all-loops optimization option will also perform the optimization of loop unrolling and is done for all loops. -ffast-math The -ffast-math optimization option will allow the GCC compiler, in the interest of optimizing code for speed, to violate some ANSI or IEEE rules /specifications. -malign-double The -malign-double optimization option will control whether the GCC compiler aligns double, long double, and long long variables on a two-word boundary or a one-word boundary. This will produce code that runs somewhat faster on a Pentium at the expense of more memory. -mcpu=cpu_type The -mcpu=cpu_type optimization option will set the default CPU to use for the machine type when scheduling instructions. -fforce-mem The -fforce-mem optimization option will produce better code by forcing memory operands to be copied into registers before doing arithmetic on them and by making all memory references potential common subexpressions. -fforce-addr The -fforce-addr optimization option will produce better code by forcing memory address constants to be copied into registers before doing arithmetic on them. -fomit-frame-pointer The -fomit-frame-pointer optimization option, one of the most interesting, will allow the program to not keep the frame pointer in a register for functions that don't need one. This avoids the instructions to save, set up and restores frame pointers; it also makes an extra register available in many functions and makes debugging impossible on most machines. Important : All future optimizations that we will describe in this book refer by default to a Pentium II/III CPU family. So you must, if required, adjust the compilation flags for your specific CPU processor type in the /etc/profile file and also during your compilation time. ----------------------------------------------------------------------------- 6.2. Benchmark Results Summaries by Architecture: Depending on your processor architecture and the version of your compiler GCC/EGCS, optimization results may vary. The charts below will help you to choose the best compilation flags for your compiler/ CPU architecture. The compiler version installed on your Red Hat Linux version 6.1 and 6.2 is egcs 2.91.66, but be sure to check it even so before choosing your compiler optimization options. To verify the compiler version installed on your system, use the command: [root@deep] /# egcs --version egcs-2.91.66 All benchmark results, and future results, can be retrieved from the GCC home page at the following address: http://egcs.cygnus.com/ For a Pentium II/III CPU i686 with compiler version egcs-2.91.66, the best optimization options would be: CFLAGS=-O9 -funroll-loops -ffast-math -malign-double -mcpu=pentiumpro -march=pentiumpro -fomit-frame-pointer -fno-exceptions Otimization chart for i686 Comparitive analysis chart with the above mentioned flags ----------------------------------------------------------------------------- 6.3. Benchmark results-i586 For a Pentium CPU i586 with compiler version egcs-2.91.66, the best optimization options would be: CFLAGS=-O3 -march=pentium -mcpu=pentium -ffast-math -funroll-loops -fomit-frame-pointer -fforce-mem -fforce-addr -malign-double -fno-exceptions Otimization chart for i586 Comparitive analysis chart with the above mentioned flags ----------------------------------------------------------------------------- 6.4. Benchmark results -i486 For a i486 CPU with compiler version egcs-2.91.66, the best optimization options would be: CFLAGS=-O3 -funroll-all-loops -malign-double -mcpu=i486 -march=i486 -fomit-frame-pointer -fno-exceptions Otimization chart for i486 Comparitive analysis chart with the above mentioned flags ----------------------------------------------------------------------------- 6.5. The bdflush parameters The bdflush file is closely related to the operation of the virtual memory VM subsystem of the Linux kernel and has a little influence on disk usage. This file /proc/sys/vm/bdflush controls the operation of the bdflush kernel daemon. We generally tune this file to improve file system performance. By changing some values from the default as shown below, the system seems more responsive; e.g. it waits a little more to write to disk and thus avoids some disk access contention. The default setup for the bdflush parameters under Red Hat Linux is: "40 500 64 256 500 3000 500 1884 2" To change the values of bdflush, type the following command on your terminal: Version 6.1 only [root@deep] /# echo "100 1200 128 512 15 5000 500 1884 2">/proc/sys/vm/bdflush You may add the above commands to the /etc/rc.d/rc.local script file and you'll not have to type it again the next time you reboot your system. Version 6.2 only Edit the /etc/sysctl.conf file and add the following line: # Improve file system performance vm.bdflush = 100 1200 128 512 15 5000 500 1884 2 You must restart your network for the change to take effect. The command to manually restart the network is the following: [root@deep] /# /etc/rc.d/init.d/network restart Setting network parameters [ OK ] Bringing up interface lo [ OK ] Bringing up interface eth0 [ OK ] Bringing up interface eth1 [ OK ] In our example above, according to the/usr/src/linux/Documentation/sysctl/ vm.txt file- The first parameter 100 % governs the maximum number of dirty buffers in the buffer cache. Dirty means that the contents of the buffer still have to be written to disk as opposed to a clean buffer, which can just be forgotten about. Setting this to a high value means that Linux can delay disk writes for a long time, but it also means that it will have to do a lot of I/O at once when memory becomes short. A low value will spread out disk I/O more evenly. The second parameter 1200 ndirty This gives the maximum number of dirty buffers that bdflush can write to the disk in one time. A high value will mean delayed, bursty I/O, while a small value can lead to memory shortage when bdflush isn't woken up often enough. The third parameter 128 nrefill This is the number of buffers that bdflush will add to the list of free buffers when refill_freelist() is called. It is necessary to allocate free buffers beforehand, since the buffers often are of a different size than memory pages and some bookkeeping needs to be done beforehand. The higher the number, the more memory will be wasted and the less often refill_freelist() will need to run. refill_freelist() 512 When this comes across more than nref_dirt dirty buffers, it will wake up bdflush. age_buffer 50*HZ, age_super parameters 5*HZ Finally, the age_buffer 50*HZ and age_super parameters 5*HZ govern the maximum time Linux waits before writing out a dirty buffer to disk. The value is expressed in jiffies (clockticks); the number of jiffies per second is 100. Age_buffer is the maximum age for data blocks, while age_super is for file system metadata. The fifth 15 and the last two parameters 1884 and 2 These are unused by the system so we don't need to change the default ones. Tip : Look at /usr/src/linux/Documentation/sysctl/vm.txt for more information on how to improve kernel parameters related to virtual memory. ----------------------------------------------------------------------------- 6.6. The buffermem parameters The buffermem file is also closely related to the operation of the virtual memory VM subsystem of the Linux kernel. The value in this file /proc/sys/vm/ buffermem controls how much memory should be used for buffer memory in percentage. It is important to note that the percentage is calculated as a percentage of total system memory. The default setup for the buffermem parameters under Red Hat Linux is: "2 10 60" Version 6.1 only To change the values of buffermem, type the following command on your terminal: [root@deep] /# echo "70 10 60" >/proc/sys/vm/buffermem You may add the above commands to the /etc/rc.d/rc.local script file and you'll not have to type it again the next time you reboot your system. Version 6.2 only Edit the /etc/sysctl.conf file and add the following line: # Improve virtual memory performance vm.buffermem = 70 10 60 You must restart your network for the change to take effect. The command to manually restart the network is the following: [root@deep] /# /etc/rc.d/init.d/network restart Setting network parameters [ OK ] Bringing up interface lo [ OK ] Bringing up interface eth0 [ OK ] Bringing up interface eth1 [ OK ] According to the /usr/src/linux/Documentation/sysctl/vm.txt file, the first parameter 80 % means to use a minimum of 80 percent of memory for the buffer cache; the minimum percentage of memory that should be spent on buffer memory.The last two parameters 10 and 60 are unused by the system so we dont need to change the defaults. Depending of the amount of RAM you have in the server the value of 80% may vary. When your server is highly loaded and when all application are used, you can know in detail how much memory are required and used by the system. 80 % for the buffermem parameters seem to be too much for systems under 256 MB of RAM. Doing a free -m command on the prompt your system will display amount of free and used memory in the system. Once you have executed this command free -m, check for -/+ buffers/cache:values and get the one related to the minimal (-) to set your value for buffermem. Example 6-1. For 128 MB of RAM 128 * 80% = 102.4 MB 128 - 102.4 = 25.6 MB [root@deep] /#free -m total used free shared buffers cached Mem: 124 121 3 30 43 48 -/+ buffers/cache: 29 95 Swap: 128 2 126 The result shows us that the -/+ buffers/cache: need 29 MB at minimum to run the system properly and with 128 MB of RAM set at 80% we have only 25.6 MB available. Hmmm! problem, i guess. so we go back to the calculator again and do this: 128 * 70% = 89.6 128 - 89.6 = 38.4 MB well solved good!. Tip : Look at /usr/src/linux/Documentation/sysctl/vm.txt for more information on how to improve kernel parameters related to virtual memory. ----------------------------------------------------------------------------- 6.7. The ip_local_port_range parameters The /proc/sys/net/ipv4/ip_local_port_range defines the local port range that is used by TCP and UDP traffic to choose the local port. You will see in the parameters of this file two numbers: The first number is the first local port allowed for TCP and UDP traffic on the server, the second is the last local port number. For high-usage systems you may change its default parameters to 32768-61000 -first-last. The default setup for the ip_local_port_range parameters under Red Hat Linux is: "1024 4999" Version 6.1 only To change the values of ip_local_port_range, type the following command on your terminal: [root@deep] /# echo "32768 61000" >/proc/sys/net/ipv4/ip_local_port_range Add the above commands to the /etc/rc.d/rc.local script file and you'll not have to type it again the next time you reboot your system. Version 6.2 only Edit the /etc/sysctl.conf file and add the following line: # Allowed local port range net.ipv4.ip_local_port_range = 32768 61000 You must restart your network for the change to take effect. The command to manually restart the network is the following: [root@deep] /# /etc/rc.d/init.d/network restart Setting network parameters [ OK ] Bringing up interface lo [ OK ] Bringing up interface eth0 [ OK ] Bringing up interface eth1 [ OK ]   ----------------------------------------------------------------------------- 6.8. The /etc/nsswitch.conf file The /etc/nsswitch.conf file is used to configure which services are to be used to determine information such as hostnames, password files, and group files. The last two ones, password files, and group files in our case are not used, since we don't use NIS services on our server. Thus, we will focus on the hosts line in this file. Edit the nsswitch.conf file vi /etc/nsswitch.conf and change the hosts line to read: "hosts: dns files" Which means, for programs that want to resolve an address. They should use the dns feature first, and the /etc/hosts file if the DNS servers are not available or can't resolve the address. Also, we would recommend deleting all instances of NIS services from each line of this file unless you are using NIS! The result should look like this: passwd:files shadow:files group:files hosts:dns files bootparams:files ethers:files netmasks:files networks:files protocols:files rpc:files services:files automount:files aliases:files ----------------------------------------------------------------------------- 6.9. The file-max parameter The file-max file /proc/sys/fs/file-max sets the maximum number of file-handles that the Linux kernel will allocate. We generally tune this file to improve the number of open files by increasing the value of /proc/sys/fs/ file-max to something reasonable like 256 for every 4M of RAM we have: i.e. for a machine with 128 MB of RAM, set it to 8192 - 128/4=32 32*256=8192. The default setup for the file-max parameter under Red Hat Linux is: "4096" To adjust the value of file-max to 128 MB of RAM, type the following on your terminal: Version 6.1 only [root@deep] /# echo "8192" >/proc/sys/fs/file-max Add the above commands to the /etc/rc.d/rc.local script file and you'll not have to type it again the next time your server reboots. Version 6.2 only Edit the /etc/sysctl.conf file and add the following line: # Improve the number of open files fs.file-max = 8192 You must restart your network for the change to take effect. The command to manually restart the network is the following: [root@deep] /# /etc/rc.d/init.d/network restart Setting network parameters [ OK ] Bringing up interface lo [ OK ] Bringing up interface eth0 [ OK ] Bringing up interface eth1 [ OK ] Tip : When you regularly receive from your server a lot of messages with errors about running out of open files, you might want to raise this limit. The default value is 4096. A file server or web server needs a lot of open files. ----------------------------------------------------------------------------- 6.10. The ulimit parameter Linux itself has a Max Processes per user limit. This feature allows us to control the number of processes an existing user on the server may be authorized to have. To improve performance, we can safely set the limit of processes for the super-user root to be unlimited. Edit the .bashrc file vi / root/.bashrc and add the following line: ulimit -u unlimited You must exit and re-login from your terminal for the change to take effect. [root@deep] /# ulimit -a core file size (blocks) 1000000 data seg size (kbytes) unlimited file size (blocks) unlimited max memory size (kbytes) unlimited stack size (kbytes) 8192 cpu time (seconds) unlimited max user processes unlimited (1) pipe size (512 bytes) 8 open files 1024 virtual memory (kbytes) 2105343 (1) Make sure that when you type as root the command ulimit -a on your terminal, it shows unlimited next to max user processes. Tip : You may also do ulimit -u unlimited at the command prompt instead of adding it to the /root/.bashrc file. Increases the system limit on open files for instance a process on Red Hat 6.0 with kernel 2.2.5 could open at least 31000 file descriptors this way and a process on kernel 2.2.12 can open at least 90000 file descriptors this way. The upper bound seems to be available memory. To increases the number of open files to 90000 for the root account do the following: Edit the .bashrc file vi /root/.bashrc and add the following line: ulimit -n 90000 You must exit from your terminal and re-login for the change to take effect. [root@deep] /# ulimit -a core file size (blocks) 1000000 data seg size (kbytes) unlimited file size (blocks) unlimited max memory size (kbytes) unlimited stack size (kbytes) 8192 cpu time (seconds) unlimited max user processes unlimited pipe size (512 bytes) 8 open files 90000 (1) virtual memory (kbytes) 2105343 (1) Make sure that when you type as root the command ulimit -a on your terminal, it shows 90000 next to open files. Note : In older 2.2 kernels, though, the number of open files per process is still limited to 1024, even with the above changes. ----------------------------------------------------------------------------- 6.11. The atime and noatime attribute Linux records information about when files were created and last modified as well as when it was last accessed. There is a cost associated with recording the last access time. The ext2 file system of Linux has an attribute that allows the super-user to mark individual files such that their last access time is not recorded. This may lead to significant performance improvements on often accessed frequently changing files such as the contents of the /var/spool/news directory. To set the attribute to a file, use: [root@deep] /#chattr +A filename (1) (1) For a specific file For a whole directory tree, do something like: [root@deep /root]#chattr -R +A /var/spool/ (1) [root@deep /root]#chattr -R +A /cache/ (2) [root@deep /root]#chattr -R +A /home/httpd/ona/ (3) (1) For a news and mail (2) For a proxy caches (3) For a web pages Linux has a special mount option for file systems called noatime that can be added to each line that addresses one file system in the /etc/fstab file. If a file system has been mounted with this option, reading accesses to the file system will no longer result in an update to the atime information associated with the file like we have explained above. The importance of the noatime setting is that it eliminates the need by the system to make writes to the file system for files which are simply being read. Since writes can be somewhat expensive, this can result in measurable performance gains. Note that the write time information to a file will continue to be updated anytime the file is written to. In our example below, we will set the noatime option to our /chroot file system. Edit the fstab file vi /etc/fstab and add in the line that refer to / chrootfile system the noatime option after the defaults option as show below: /dev/sda7 /chroot ext2 defaults,noatime 1 2 You need not reboot your system for the change to take effect, just make the Linux system aware about the modification you have made to the /etc/fstab file. This can be accomplished with the following commands: [root@deep] /#mount -oremount /chroot/ Then test your results with the flowing command: [root@deep]# cat /proc/mounts /dev/root / ext2 rw 0 0 /proc /proc proc rw 0 0 /dev/sda1 /boot ext2 rw 0 0 /dev/sda8 /cache ext2 rw 0 0 /dev/sda7 /chroot ext2 rw,noatime 0 0 /dev/sda6 /home ext2 rw 0 0 /dev/sda11 /tmp ext2 rw 0 0 /dev/sda5 /usr ext2 rw 0 0 /dev /sda9 /var ext2 rw 0 0 none /dev/pts devpts rw 0 0 If you see something like: /dev/sda7 /chroot ext2 rw,noatime 0 0, congratulations! ----------------------------------------------------------------------------- 6.12. Tuning IDE Hard Disk Performance Putting your swap partitions near the beginning of your drive, see This chart to get a better idea, may give you some acceptable improvement. The beginning of the drive is physically located on the outer portion of the cylinder, and the read/write head can cover much more ground per revolution. We typically see partitions placed at the end of the drive work 3MB/s slower using the hdparm -t command. Performance increases have been reported on massive disk I/O operations by setting the IDE drivers to use DMA, 32-bit transfers and multiple sector modes. The kernel seems to use more conservative settings unless told otherwise. The magic command to change the setting of your drive is hdparm. To enable 32-bit I/O over the PCI buses, use the command: [root@deep] /# /sbin/hdparm -c1 /dev/hda or hdb, hdc etc. This will usually, depending on your IDE Disk Drive model, cut the timing buffered disk reads time by 2. The hdparm(8) manpage says that you may need to use -c 3 for some chipsets. All (E)IDE drives still have only a 16-bit connection over the ribbon cable from the interface card. To enable DMA, use the command: [root@deep] /# /sbin/hdparm -d1 /dev/hda or hdb, hdc etc. This may depend on support for your motherboard chipset being compiled into your kernel. Also, this command will enable DMA support for your hard drive, it will cut the timing buffered disk reads time and will improve the performance by 2. To enable multiword DMA mode 2 transfers, use the command: [root@deep] /#/sbin/hdparm -d1 -X34 /dev/hda or hdb, hdc etc. This sets the IDE transfer mode for newer (E)IDE/ATA2 drives. check your hardware manual to see if you have it. To enable UltraDMA mode2 transfers, use the command: [root@deep] /# /sbin/hdparm -d1 -X66 /dev/hda or hdb, hdc etc. You'll need to prepare the chipset for UltraDMA beforehand. Also, see your manual page about hdparm for more information. Use this with extreme caution! To set multiple sector mode I/O, use the command: [root@deep] /#/sbin/hdparm -m XX /dev/hda or hdb, hdc etc. Where XX is the maximum setting supported by your drive. The -i flag can be used to find the maximum setting supported by an installed drive: look for MaxMultSect in the output. [root@deep] /#/sbin/hdparm -i /dev/hda or hdb, hdc etc. /dev/hda: Model=Maxtor 7540 AV, FwRev=GA7X4647, SerialNo=L1007YZS Config={ HardSect NotMFM HdSw>15uSec Fixed DTR>5Mbs FmtGapReq } RawCHS=1046/16/63, TrkSize=0, SectSize=0, ECCbytes=11 BuffType=3(DualPortCache), BuffSize=32kB, MaxMultSect=8, MultSect=8 DblWordIO=yes, maxPIO=2(fast), DMA=yes, maxDMA=1(medium) CurCHS=523/32/63, CurSects=379584528, LBA=yes, LBA=yes, LBAsects=1054368 tDMA={min:150,rec:150}, DMA modes: sword0 sword1 *sword2 *mword0 IORDY=on/off, tPIO={min:240,w/IORDY:180}, PIO modes: mode3 Multiple sector mode aka IDE Block Mode, is a feature of most modern IDE hard drives, permitting the transfer of multiple sectors per I/O interrupt, rather than the usual one sector per interrupt. When this feature is enabled, it typically reduces operating system overhead for disk I/O by 30-50%. On many systems it also provides increased data throughput of anywhere from 5% to 50%. You can test the results of your changes by running hdparm in performance test mode: [root@deep] /#/sbin/hdparm -t /dev/hda or hdb, hdc etc. Tip : Once you have a set of hdparm options, you can put the commands in your /etc/rc.d/rc.local file to run it every time you reboot the machine. ----------------------------------------------------------------------------- 6.13. Better manage your TCP/IP resources This hack just make the time default values for TCP/IP connection lower so that more connections can be handled by time on your TCP/IP protocol. The following will decrease the amount of time your Linux box will try take to finish closing a connection and the amount of time before it will kill a stale connection. This will also turn off some IP extensions that aren't needed. The default setup for the TCP/IP parameters we'll change under Red Hat Linux are:   *  For the tcp_fin_timeout 180   *  For the tcp_keepalive_time 7200   *  For the tcp_window_scaling 1   *  For the tcp_sack 1   *  For the tcp_timestamps 1 To adjust the new TCP/IP values, type the following commands on your terminal: [Version6] [root@deep] /#echo 30 >/proc/sys/net/ipv4/tcp_fin_timeout [root@deep] /#echo 1800 >/proc/sys/net/ipv4/tcp_keepalive_time [root@deep] /#echo 0 >/proc/sys/net/ipv4/tcp_window_scaling [root@deep] /#echo 0 >/proc/sys/net/ipv4/tcp_sack [root@deep] /#echo 0 >/proc/sys/net/ipv4/tcp_timestamps Execute the above commands and put them in your /etc/rc.d/rc.local file so you don't need to type them again each time your system reboots. Version 6.2 only Edit the /etc/sysctl.conf file and add the following lines: # Decrease the time default value for tcp_fin_timeout connection net.ipv4.tcp_fin_timeout = 30 # Decrease the time default value for tcp_keepalive_time connection net.ipv4.tcp_keepalive_time = 1800 # Turn off the tcp_window_scaling net.ipv4.tcp_window_scaling = 0 # Turn off the tcp_sack net.ipv4.tcp_sack = 0 # Turn off the tcp_timestamps net.ipv4.tcp_timestamps = 0 You must restart your network for the change to take effect. The command to manually restart the network is the following: [root@deep] /# /etc/rc.d/init.d/network restart Setting network parameters [ OK ] Bringing up interface lo [ OK ] Bringing up interface eth0 [ OK ] Bringing up interface eth1 [ OK ] ----------------------------------------------------------------------------- Chapter 7. Configuring and Building a Secure, Optimized Kernel Well, our Linux server seems to be getting in shape now! But wait, what is the most important part of our server? Yes, it's the kernel. The Linux kernel is the core of our operating system, and without it there is no Linux at all. So we must take care of our kernel and configure it to fit our needs and compile just features we really need. The first thing to do next is to build a kernel that best suits your system. It's very simple to do but, in any case, refer to the README file in the /usr/src/linux/ directory. When configuring your kernel only compile in code that you need and use. Few main reasons that come to mind are;   *  The Kernel will be faster less code to run,   *  You will have more memory, Kernel parts are NEVER swapped to the virtual memory,   *  More stable. Try probing for a non-existent card?,   *  Unnecessary parts can be used by an attacker to gain access to the machine or other machines on the network.   *  Modules are also slower than support compiled directly in the kernel. ----------------------------------------------------------------------------- 7.1. Pre-Install In our configuration and compilation we will build a monolithic kernel. Monolithic kernel means to only answer Yes or No to the questions, don't make anything modular and omit the steps:   *  make_modules   *  make_modules_install. Also, we will patch our new kernel with the buffer overflow protection from kernel patches. Patches for the Linux kernel exist, like Solar Designer's non-executable stack patch, which disallows the execution of code on the stack, making a number of buffer overflow attacks harder - and defeating completely a number of current exploits used by "script kiddies" worldwide. Important : Remember to only answer Yes or No to the questions when configuring your new kernel if you're intending to build a monolithic kernel. If you intend to use firewall masquerading functions or a dial-up ppp connection, you cannot build a monolithic kernel, since these function require the build of some modules, by default. Build, instead, a modularized kernel. A new kernel is very specific to your computer hardware, in the kernel configuration part; we are using the following hardware for our example. Of course you must change them to fit your system components. 1 Pentium II 400 MHz (i686) processor 1 Motherboard SCSI 1 Hard Disk SCSI 1 SCSI Controler Adaptec AIC 7xxx 1 CD-ROM ATAPI IDE 1 Floppy Disk 2 Ethernet Cards Intel EtherExpressPro 10/100 1 Mouse PS/2 These installation instructions assume Commands are Unix-compatible. The source path is /usr/src. Installations were tested on Red Hat Linux 6.1 and 6.2. All steps in the installation will happen in super-user account root. Latest Kernel version number is 2.2.14 Latest Secure Linux Kernel Patches version number is 2_2_14-ow2 All these below mentioned Packages were available in the following sites as of this writing but we suggest you can get additional information regarding mirror sites by searching on their respective home pages.   *  Kernel Homepage:http://www.kernelnotes.org/ Be sure to download: linux-2_2_14_tar.gz Kernel FTP Site: 139.142.90.113   *  Secure Linux Kernel Patches Homepage:http://www.openwall.com/linux/ You must be sure to download: linux-2_2_14-ow2_tar.gz Secure Linux Kernel Patches FTP Site: 195.42.162.180 ----------------------------------------------------------------------------- 7.1.1. Make an emergency boot floppy The first of the pre-install step is to make an emergency boot floppy. Linux has a small utility named mkbootdisk to simply do this. The first step is to find out what kernel version, you are currently using. Check out your / etc/lilo.conf file and see which image was booted from and from this image, we can find the kernel version we need to make our emergency boot floppy. [root@deep] /#cat /etc/lilo.conf In my example, I have the following in the lilo.conf file: boot=/dev/sda map=/boot/map install=/boot/boot.b prompt timeout=50 image=/boot/vmlinuz-2.2.12-20 (1) label=linux (2) root=/dev/sda6 initrd=/boot/initrd-2.2.12-20.img read-only (1) the kernel version (2) the image we booted from Now you'll need to find the image that you booted from. On a standard new first install, it will be the one-labeled linux. In the above example we show that the machine booted using the /boot/vmlinuz-2.2.12-20 original kernel version of the system. Now we simply need to put a formatted 1.44 floppy in our system and execute the following command as root: [root@deep] /#mkbootdisk --device /dev/fd0 2.2.12-20                     Insert a disk in /dev/fd0. Any information on the disk will be lost. Press to continue or ^C to abort:                   Following these guidelines, you will now have a boot floppy with a known working kernel in case of problems with the upgrade. I recommend rebooting the system with the floppy to make sure that the floppy works correctly. ----------------------------------------------------------------------------- 7.2. Uninstallation and Optimization 1. We must copy the archive file of the Kernel to the /usr/src directory and move to this directory. [root@deep] /#cp linux-version_tar.gz /usr/src/ [root@deep] /#cd /usr/src/ These steps are required only if you already have installed a Linux kernel with a tar archive before. If it is a first, fresh install of Linux kernel, then instead uninstall the kernel-headers-version.i386.rpm, kernel-version.i386.rpm package that are on your system. Remove the Linux symbolic link with the following command: [root@deep ] /src#rm -rf linux Remove the Linux kernel headers directory with the following command: [root@deep ] /src#rm -rf linux-2.2.xx Remove the Linux kernel modules directory with the following command: [root@deep ] /src#rm -rf /lib/modules/2.2.xx Important : Removing the old kernel modules is required only if you have installed a modularized kernel version before. If the modules directory doesn't exist under the /lib directory it's because your old kernel version is not a modularized kernel. If the original kernels RPM package are installed on your system instead of the Linux kernel tar archive, because you have just finished installing your new Linux system, or have used an RPM package before to upgrade your Linux system, then use the following command to uninstall the Linux kernel: You can verify that a kernel RPM package is installed on your system with the following command: [root@deep ] /src#rpm -qa |grep kernel kernel-headers-2.2.xx.i386.rpm kernel-2.2.xx.i386.rpm                 To uninstall the linux kernel RPM, use the following command: [root@deep ] /src#rpm -e --nodeps kernel-headers kernel                 cannot remove /usr/src/linux-2.2.xx - directory not empty cannot remove /lib/modules/2.2.xx - directory not empty                 [root@deep ] /src#rm -rf /usr/src/linux-2.2.xx/ [root@deep ] /src#rm -rf /lib/modules/2.2.xx/ In the steps below, we remove manually the empty /usr/src/linux-2.2.xx and /lib/modules/2.2.xx directories after the uninstallation of the kernels RPM, the RPM uninstall program will not completely remove those directories. 2. Now, we must decompress the tar archive of the kernel and remove the Linux tar archive from the system. [root@deep ] /src#tar xzpf linux-version_tar.gz [root@deep ] /src#rm -f linux-version_tar.gz 3. To increase the number of tasks allowed the maximum number of processes per user, you may need to edit the /usr/src/linux/include/linux/tasks.h file and change the following parameters. Edit the tasks.h file, vi +14 / usr/src/linux/include/linux/tasks.h and change the following parameters: NR_TASKS from 512 to 3072 and MIN_TASKS_LEFT_FOR_ROOT from 4 to 24 Important : The value in the NR_TASKS line denotes the maximum number of tasks (processes) handles that the Linux kernel will allocate per users. Increasing this number will allow you to handle more connections from clients on your server, example: an HTTP web server will be able to serve more client connections. Please don't forget, Linux is protected from allocation of all process slots for normal users. There is a special parameter line MIN_TASKS_LEFT_FOR_ROOT reserved especially for the super-user root that you may set for the number of process reserved to root -24 is a good value. 4. To optimize the Linux kernel to fit your specific CPU architecture and optimization flags you may need to edit the /usr/src/linux/Makefile file and change the following parameters. a. Edit the Makefile file (vi +18 /usr/src/linux/Makefile) and change the line: HOSTCC =gcc to read: HOSTCC =egcs. b. Edit the Makefile file, vi +25 /usr/src/linux/Makefile and change the line: CC =$(CROSS_COMPILE)gcc D__KERNEL__ -I$(HPATH) to read: CC =$(CROSS_COMPILE)egcs D__KERNEL__ -I$(HPATH). c. Edit the Makefile file vi +90 /usr/src/linux/Makefile and change the line: CFLAGS = -Wall -Wstrict-prototypes -O2 -fomit-frame-pointer to read: CFLAGS = -Wall -Wstrict-prototypes -O9 -funroll-loops -ffast-math -malign-double -mcpu=pentiumpro -march=pentiumpro -fomit-frame-pointer -fno-exceptions d. Edit the Makefile file vi +19 /usr/src/linux/Makefile and change the line: HOSTCFLAGS =-Wall -Wstrict-prototypes -O2 -fomit-frame-pointer to read: HOSTCFLAGS =-Wall -Wstrict-prototypes -O9 -funroll-loops -ffast-math -malign-double -mcpu=pentiumpro -march=pentiumpro -fomit-frame-pointer -fno-exceptions Important : These changes turn on aggressive optimization tricks that may or may not work with all kernels. Please, if the optimization flags above, or the ones you have chosen for your CPU architecture do not work for you, don't try to absolutely force it to work. I wouldn't want to make your system unstable like Microsoft Windows. ----------------------------------------------------------------------------- 7.3. Securing the kernel The secure Linux kernel patches from the Openwall Project are a great way to prevent attacks like Stack Buffer Overflows, and others. The Openwall patch is a collection of security-related features for the Linux kernel, all configurable via the new Security options configuration section that will be added to your new Linux kernel. This patch may change from version to version, and some may contain various other security fixes. New features of patch version linux-2_2_14-ow2_tar.gz are:   *  Non-executable user stack area   *  Restricted links in /tmp   *  Restricted FIFOs in /tmp   *  Restricted /proc   *  Special handling of fd 0, 1, and 2   *  Enforce RLIMIT_NPROC on execve(2)   *  Destroy shared memory segments not in use Important : When applying the linux-2_2_14-ow2 patch, a new Security options section will be added at the end of your kernel configuration. For more information and description of the different features available with this patch, see the README file that come with the source code of the patch. Applying the patch [root@deep] /#cp linux-2_2_14-ow2_tar.gz /usr/src/ (1) [root@deep] /#cd /usr/src/ (2) [root@deep ]/src#tar xzpf linux.2_2_14-ow2_tar.gz (3) [root@deep ]/src#cd linux-2.2.14-ow2/ (4) [root@deep ] /linux-2.2.14-ow2#mv linux-2.2.14-ow2.diff /usr/src/ (5) [root@deep ] /linux-2.2.14-ow2#cd .. (6) [root@deep ]/src#patch -p0 16Mb of memory) (CONFIG_SKB_LARGE) Y/n/? The IPX protocol (CONFIG_IPX) N/y/? Appletalk DDP (CONFIG_ATALK) N/y/? Telephony support. Linux telephony support (CONFIG_PHONE) N/y/? (NEW) SCSI support. SCSI support (CONFIG_SCSI) Y/n/? SCSI disk support (CONFIG_BLK_DEV_SD) Y/n/? SCSI tape support (CONFIG_CHR_DEV_ST) N/y/? SCSI CD-ROM support (CONFIG_BLK_DEV_SR) N/y/? SCSI generic support (CONFIG_CHR_DEV_SG) N/y/? Probe all LUNs on each SCSI device (CONFIG_SCSI_MULTI_LUN) Y/n/? N Verbose SCSI error reporting (kernel size +=12K) (CONFIG_SCSI_CONSTANTS) Y/n/? N SCSI logging facility (CONFIG_SCSI_LOGGING) N/y/? SCSI low-level drivers. 7000FASST SCSI support (CONFIG_SCSI_7000FASST) N/y/? ACARD SCSI support (CONFIG_SCSI_ACARD) N/y/? Adaptec AHA152X/2825 support (CONFIG_SCSI_AHA152X) N/y/? Adaptec AHA1542 support (CONFIG_SCSI_AHA1542) N/y/? Adaptec AHA1740 support (CONFIG_SCSI_AHA1740) N/y/? Adaptec AIC7xxx support (CONFIG_SCSI_AIC7XXX) N/y/? Y Enable Tagged Command Queueing TCQ by default N/y/? (NEW) Y Maximum number of TCQ commands per device (CONFIG_AIC7XXX_CMDS_PER_DEVICE) [8] (NEW) Collect statistics to report in /proc (CONFIG_AIC7XXX_PROC_STATS) N/y/? (NEW) Delay in seconds after SCSI bus reset (CONFIG_AIC7XXX_RESET_DELAY) [5] (NEW) IBM ServeRAID support (CONFIG_SCSI_IPS) N/y/? (NEW) AdvanSys SCSI support (CONFIG_SCSI_ADVANSYS) N/y/? Always IN2000 SCSI support (CONFIG_SCSI_IN2000) N/y/? AM53/79C974 PCI SCSI support (CONFIG_SCSI_AM53C974) N/y/? AMI MegaRAID support (CONFIG_SCSI_MEGARAID) N/y/? BusLogic SCSI support (CONFIG_SCSI_BUSLOGIC) N/y/? DTC3180/3280 SCSI support (CONFIG_SCSI_DTC3280) N/y/? EATA ISA/EISA/PCI (DPT and generic EATA/DMA) support (CONFIG_SCSI_EATA) N/y/? EATA-DMA [Obsolete] (DPT, NEC, AT&T, SNI, AST, Olivetti, Alphatronix) support (CONFIG_SCSI_EATA_DMA) N/y/? EATA-PIO (old DPT PM2001, PM2012A) support (CONFIG_SCSI_EATA_PIO) N/y/? Future Domain 16xx SCSI/AHA-2920A support (CONFIG_SCSI_FUTURE_DOMAIN) N/y/? GDT SCSI Disk Array Controller support (CONFIG_SCSI_GDTH) N/y/? Generic NCR5380/53c400 SCSI support (CONFIG_SCSI_GENERIC_NCR5380) N/y/? Initio 9100U(W) support (CONFIG_SCSI_INITIO) N/y/? Initio INI-A100U2W support (CONFIG_SCSI_INIA100) N/y/? NCR53c406a SCSI support (CONFIG_SCSI_NCR53C406A) N/y/? symbios 53c416 SCSI support (CONFIG_SCSI_SYM53C416) N/y/? Simple 53c710 SCSI support (Compaq, NCR machines) (CONFIG_SCSI_SIM710) N/y/? (NEW) NCR53c7,8xx SCSI support (CONFIG_SCSI_NCR53C7xx) N/y/? NCR53C8XX SCSI support (CONFIG_SCSI_NCR53C8XX) N/y/? SYM53C8XX SCSI support (CONFIG_SCSI_SYM53C8XX) Y/n/? N PAS16 SCSI support (CONFIG_SCSI_PAS16) N/y/? PCI2000 support (CONFIG_SCSI_PCI2000) N/y/? PCI2220i support (CONFIG_SCSI_PCI2220I) N/y/? PSI240i support (CONFIG_SCSI_PSI240I) N/y/? Qlogic FAS SCSI support (CONFIG_SCSI_QLOGIC_FAS) N/y/? Qlogic ISP SCSI support (CONFIG_SCSI_QLOGIC_ISP) N/y/? Qlogic ISP FC SCSI support (CONFIG_SCSI_QLOGIC_FC) N/y/? Seagate ST-02 and Future Domain TMC-8xx SCSI support (CONFIG_SCSI_SEAGATE) N/y/? Tekram DC390(T) and Am53/79C974 SCSI support (CONFIG_SCSI_DC390T) N/y/? Trantor T128/T128F/T228 SCSI support (CONFIG_SCSI_T128) N/y/? UltraStor 14F/34F support (CONFIG_SCSI_U14_34F) N/y/? UltraStor SCSI support (CONFIG_SCSI_ULTRASTOR) N/y/? ----------------------------------------------------------------------------- 7.7. Kernel configuration -Part "C" Network device support. Network device support (CONFIG_NETDEVICES) Y/n/? ARCnet devices. ARCnet support (CONFIG_ARCNET) N/y/? Dummy net driver support (CONFIG_DUMMY) Y/n/? EQL -serial line load balancing support (CONFIG_EQUALIZER) N/y/? General Instruments Surfboard 1000 (CONFIG_NET_SB1000) N/y/? (NEW) Ethernet (10 or 100Mbit). Ethernet (10 or 100Mbit) (CONFIG_NET_ETHERNET) Y/n/? 3COM cards (CONFIG_NET_VENDOR_3COM) N/y/? AMD LANCE and PCnet (AT1500 and NE2100) support (CONFIG_LANCE) N/y/? Western Digital/SMC cards (CONFIG_NET_VENDOR_SMC) N/y/? Racal-Interlan (Micom) NI cards (CONFIG_NET_VENDOR_RACAL) N/y/? Other ISA cards (CONFIG_NET_ISA) N/y/? EISA, VLB, PCI and on board controllers (CONFIG_NET_EISA) Y/n/? AMD PCnet32 (VLB and PCI) support (CONFIG_PCNET32) N/y/? Apricot Xen-II on board Ethernet (CONFIG_APRICOT) N/y/? CS89x0 support (CONFIG_CS89x0) N/y/? DM9102 PCI Fast Ethernet Adapter support (EXPERIMENTAL) (CONFIG_DM9102) N/y/? (NEW) Generic DECchip & DIGITAL EtherWORKS PCI/EISA (CONFIG_DE4X5) N/y/? DECchip Tulip (dc21x4x) PCI support (CONFIG_DEC_ELCP) N/y/? Old DECchip Tulip (dc21x4x) PCI support (CONFIG_DEC_ELCP_OLD) N/y/? (NEW) Digi Intl. RightSwitch SE-X support (CONFIG_DGRS) N/y/? EtherExpressPro/100 support (CONFIG_EEXPRESS_PRO100) Y/n/? PCI NE2000 support (CONFIG_NE2K_PCI) N/y/? TI ThunderLAN support (CONFIG_TLAN) N/y/? VIA Rhine support (CONFIG_VIA_RHINE) N/y/? SiS 900/7016 PCI Fast Ethernet Adapter support (CONFIG_SIS900) N/y/? (NEW) Pocket and portable adaptors (CONFIG_NET_POCKET) N/y/? Ethernet (1000 Mbit). SysKonnect SK-98xx support (CONFIG_SK98LIN) N/y/? (NEW) FDDI driver support (CONFIG_FDDI) N/y/? PPP (point-to-point) support (CONFIG_PPP) N/y/? SLIP (serial line) support (CONFIG_SLIP) N/y/? Wireless LAN (non-hamradio) (CONFIG_NET_RADIO) N/y/? Token ring devices. Token Ring driver support (CONFIG_TR) N/y/? Fibre Channel driver support (CONFIG_NET_FC) N/y/? (NEW) Wan interfaces. MultiGate (COMX) synchronous serial boards support (CONFIG_COMX) N/y/? (NEW) Frame relay DLCI support (CONFIG_DLCI) N/y/? WAN drivers (CONFIG_WAN_DRIVERS) N/y/? SBNI12-xx support (CONFIG_SBNI) N/y/? (NEW) Amateur Radio support. Amateur Radio support (CONFIG_HAMRADIO) N/y/? IrDA subsystem support. IrDA subsystem support (CONFIG_IRDA) N/y/? ISDN subsystem. ISDN support (CONFIG_ISDN) N/y/? Old CD-ROM drivers (not SCSI, not IDE). Support non-SCSI/IDE/ATAPI CDROM drives (CONFIG_CD_NO_IDESCSI) N/y/? Character devices. Virtual terminal (CONFIG_VT) Y/n/? Support for console on virtual terminal (CONFIG_VT_CONSOLE) Y/n/? Standard/generic (dumb) serial support (CONFIG_SERIAL) Y/n/? Support for console on serial port (CONFIG_SERIAL_CONSOLE) N/y/? Extended dumb serial driver options (CONFIG_SERIAL_EXTENDED) N/y/? Non-standard serial port support (CONFIG_SERIAL_NONSTANDARD) N/y/? Unix98 PTY support (CONFIG_UNIX98_PTYS) Y/n/? Maximum number of Unix98 PTYs in use (0-2048) (CONFIG_UNIX98_PTY_COUNT) [256] 128 Mouse Support (not serial mice) (CONFIG_MOUSE) Y/n/? ----------------------------------------------------------------------------- 7.8. Kernel configuration -Part "D" Mice. ATIXL busmouse support (CONFIG_ATIXL_BUSMOUSE) N/y/? Logitech busmouse support (CONFIG_BUSMOUSE) N/y/? Microsoft busmouse support (CONFIG_MS_BUSMOUSE) N/y/? PS/2 mouse (aka "auxiliary device") support (CONFIG_PSMOUSE) N/y/? C&T 82C710 mouse port support (as on TI Travelmate) (CONFIG_82C710_MOUSE) Y/n/? N PC110 digitizer pad support (CONFIG_PC110_PAD) N/y/? Joystick support. Joystick support (CONFIG_JOYSTICK) N/y/? QIC-02 tape support (CONFIG_QIC02_TAPE) N/y/? Watchdog Timer Support (CONFIG_WATCHDOG) N/y/? /dev/nvram support (CONFIG_NVRAM) N/y/? Enhanced Real Time Clock Support (CONFIG_RTC) N/y/? Video for Linux. Video For Linux (CONFIG_VIDEO_DEV) N/y/? Double Talk PC internal speech card support (CONFIG_DTLK) N/y/? Ftape, the floppy tape device driver. Ftape (QIC-80/Travan) support (CONFIG_FTAPE) N/y/? Filesystems. Quota support (CONFIG_QUOTA) N/y/? Y Kernel automounter support (CONFIG_AUTOFS_FS) Y/n/? N Amiga FFS filesystem support (CONFIG_AFFS_FS) N/y/? Apple Macintosh filesystem support (experimental) (CONFIG_HFS_FS) N/y/? DOS FAT fs support (CONFIG_FAT_FS) N/y/? ISO 9660 CDROM filesystem support (CONFIG_ISO9660_FS) Y/n/? Microsoft Joliet CDROM extensions (CONFIG_JOLIET) N/y/? Minix fs support (CONFIG_MINIX_FS) N/y/? NTFS filesystem support (read only) (CONFIG_NTFS_FS) N/y/? OS/2 HPFS filesystem support (read only) (CONFIG_HPFS_FS) N/y/? /proc filesystem support (CONFIG_PROC_FS) Y/n/? /dev/pts filesystem for Unix98 PTYs (CONFIG_DEVPTS_FS) Y/n/? ROM filesystem support (CONFIG_ROMFS_FS) N/y/? Second extended fs support (CONFIG_EXT2_FS) Y/n/? System V and Coherent filesystem support (CONFIG_SYSV_FS) N/y/? UFS filesystem support (CONFIG_UFS_FS) N/y/? Network File Systems. Coda filesystem support (advanced network fs) (CONFIG_CODA_FS) N/y/? NFS filesystem support (CONFIG_NFS_FS) Y/n/? N SMB filesystem support (to mount WfW shares etc.) (CONFIG_SMB_FS) N/y/? NCP filesystem support (to mount NetWare volumes) (CONFIG_NCP_FS) N/y/? Partition Types. BSD disklabel (BSD partition tables) support (CONFIG_BSD_DISKLABEL) N/y/? Macintosh partition map support (CONFIG_MAC_PARTITION) N/y/? SMD disklabel (Sun partition tables) support (CONFIG_SMD_DISKLABEL) N/y/? Solaris (x86) partition table support (CONFIG_SOLARIS_X86_PARTITION) N/y/? Console drivers. VGA text console (CONFIG_VGA_CONSOLE) Y/n/? Video mode selection support (CONFIG_VIDEO_SELECT) N/y/? Sound . Sound card support (CONFIG_SOUND) N/y/? ----------------------------------------------------------------------------- 7.9. Kernel configuration -Part "E" Security options. Security options will appear only if you have patched your kernel with the Openwall Project patch. Non-executable user stack area (CONFIG_SECURE_STACK) Y Autodetect and emulate GCC trampolines (CONFIG_SECURE_STACK_SMART) Y Restricted links in /tmp (CONFIG_SECURE_LINK) Y Restricted FIFOs in /tmp (CONFIG_SECURE_FIFO) Y Restricted /proc (CONFIG_SECURE_PROC) N Y Special handling of fd 0, 1, and 2 (CONFIG_SECURE_FD_0_1_2) Y Enforce RLIMIT_NPROC on execve(2) (CONFIG_SECURE_RLIMIT_NPROC) Y Destroy shared memory segments not in use (CONFIG_SECURE_SHM) N Y Kernel hacking. Magic SysRq key (CONFIG_MAGIC_SYSRQ) N/y/? Now, return to the /usr/src/linux/ directory, if you are not already in it. You need to compile the new kernel. You do so by using the following command: [root@deep ] /linux# make dep; make clean; make bzImage This line contains three commands in one.   *  The first one, make dep, actually takes your configuration and builds the corresponding dependency tree. This process determines what gets compiled and what doesn't.   *  The next step, make clean, erase all previous traces of a compilation so as to avoid any mistakes in which version of a feature gets tied into the kernel.   *  Finally, make bzImage does the full compilation of the kernel. After the process is complete, the kernel is compressed and ready to be installed on your system. Before we can install the new kernel, we must know if we need to compile the corresponding modules. This is required only if you said Yes to Enable loadable module support CONFIG_MODULES and have compiled some options in the kernel configuration above as a module. In this case, you must execute the following commands: [root@deep ] /linux#make modules [root@deep ] /linux#make modules_install Note : The make modules and make modules_install commands are required only if you say Yes to Enable loadable module support CONFIG_MODULES in your kernel configuration above. ----------------------------------------------------------------------------- 7.10. Installing the new kernel 1. Copy the file /usr/src/linux/arch/i386/boot/bzImage from the kernel source tree to the /boot directory, and give it an appropriate new name. [root@deep ] /linux#cp /usr/src/linux/arch/i386/boot/bzImage /boot/vmlinuz-kernel.version.number An appropriated or recommended new name is something like vmlinuz-2.2.14, this is important if you want a new rescue floppy or emergency boot floppy using the mkbootdisk program that require some specific needs like for example: vmlinuz-2.2.14 instead of vmlinuz-2.2.14.a 2. Copy the file /usr/src/linux/System.map from the kernel source tree to the /boot directory, and give it an appropriate new name. [root@deep ] /linux#cp /usr/src/linux/System.map /boot/System.map-kernel.version.number 3. Move into the /boot directory and rebuild the links to vmlinuz and System.map with the following commands: [root@deep ] /linux#cd /boot [root@deep ] /boot#ln -fs vmlinuz-kernel.version.number vmlinuz [root@deep ] /boot#ln -fs System.map-kernel.version.number System.map We must rebuild the links of vmlinuz and System.map to point them to the new kernel version installed. Without the new links LILO program will look by default for the old version of your Linux kernel. 4. Remove obsolete and unnecessary files under the /boot directory to make space: [root@deep ] /boot#rm -f module-info [root@deep ] /boot#rm -f initrd-2.2.xx.img The module-info link point to the old modules directory of your original kernel. Since we have installed a brand new kernel, we don't need to keep this broken link. The initrd-2.2.xx is a file that contains an initial RAM disk image that serves as a system before the disk is available. This file is only available and is installed from the Linux setup installation if your system has a SCSI adapter present. If we use and have a SCSI system, the driver now will be incorporated into our new Linux kernel since we have build a monolithic kernel, so we can remove this file initrd-2.2.xx.img safely. 5. Create a new Linux kernel directory that will handle all header files related to Linux kernel for future compilation of other programs on your system. Recall, we had created two symlinks under the /usr/include directory that point to the Linux kernel to be able to compile it without receiving error and also be able to compile future programs. The /usr/ include directory is where all header files of your Linux system are kept for reference and dependencies when you compile and install new programs. The asm, and linux links are used when program need to know some functions from compile-time specific to the kernel installed on your system. Programs call other headers in the include directory when they must know specific information, dependencies, etc. of your system. [root@deep] /#mkdir -p /usr/src/linux-2.2.14/include [root@deep] /#cp -r /usr/src/linux/include/asm-generic /usr/src/linux-2.2.14/include [root@deep] /#cp -r /usr/src/linux/include/asm-i386 /usr/src/linux-2.2.14/include [root@deep] /#cp -r /usr/src/linux/include/linux /usr/src/linux-2.2.14/include [root@deep] /#cp -r /usr/src/linux/include/net /usr/src/linux-2.2.14/include [root@deep] /#cp -r /usr/src/linux/include/video /usr/src/linux-2.2.14/include [root@deep] /#cp -r /usr/src/linux/include/scsi /usr/src/linux-2.2.14/include [root@deep] /#rm -rf /usr/src/linux [root@deep] /#cd /usr/src [root@deep ] /src#ln -s /usr/src/linux-2.2.14 linux First we create a new directory named linux-2.2.14 based on the version of the kernel we have installed for easy interpretation, then we copy directories asm-generic, asm-i386, linux, net, video, and scsi from /usr/ linux/include to our new place /usr/src/linux-2.2.14/include. After We remove the entire source directory where we had compiled the new kernel, create a new symbolic link named linux under /usr/src that points to our new /usr/src/linux-2.2.14/include directory. With these steps, future compiled programs will know where to look for headers related to the kernel on your server. Note : This step will allow us to gain space on our hard drive and will reduce the risk of security. The Linux kernel source directory handles a of lot files and is about 75 MB in size when uncompressed. With the procedure described above, our Linux kernel directory began approximately 3 MB in size so we save 72 MB for the same functionalities. 6. Finally, you need to edit the /etc/lilo.conf file to make your new kernel one of the boot time options: a. Edit the lilo.conf file - vi /etc/lilo.conf and make the appropriated change on the line that read image=/boot/. [root@deep] /#vi /etc/lilo.conf                 boot=/dev/sda map=/boot/map install=/boot/boot.b prompt timeout=00 restricted password=somepasswd image=/boot/ vmlinuz-kernel.version.number #add your new kernel name file here. label=linux root=/dev/sda6 read-only               Important : Don't forget to remove the line that read initrd=/ boot/initrd-2.2.12-20.img in the lilo.conf file, since this line is not necessary now monolithic kernel doesn't need an initrd file. b. Once the name of the new kernel version has been put in the lilo.conf file as shown above, we update our lilo.conf file for the change to take effect with the following command: [root@deep] /#/sbin/lilo -v                 LILO version 21, [Copyright 1992-1998 Werner Almesberger Reading boot sector from /dev/sda Merging with /boot/ boot.b Boot image: /boot/vmlinuz-2.2.14 Added linux * /boot/boot.0800 exits no backup copy made. Writing boot sector.               Important : If you say NO to the configuration option Unix98 PTY support CONFIG_UNIX98_PTYS during your kernel configuration, you must edit the /etc/fstab file and remove the line that read: none /dev/pts devpts gid=5,mode=620 0 0 ----------------------------------------------------------------------------- 7.11. Delete programs, Edit files pertaining to modules By default when you install Red Hat Linux for the first time like we do, the kernel is built as a modularized kernel. This means that each device or function we need exists as modules and is controlled by the Kernel Daemon program named kmod, which automatically loads some modules and functions support into memory as it is needed, and unloads it when it's no longer being used. 1. kmod and other module management programs included in the modutils RPM package use the conf.modules file located in the /etc directory to know, for example which Ethernet card you have, if your Ethernet card requires special configuration and so on. Since we are not using any modules in our new compiled kernel, we can remove the conf.modules file and uninstall completely the modutils package program. To remove the conf.modules file, use the command: [root@deep] /#rm -f /etc/conf.modules To uninstall the modutils package, use the following command: [root@deep] /#rpm -e --nodeps modutils 2. One last thing to do is to edit the file rc.sysinit and comment out all the lines related to depmod -a by inserting a # at the beginning of the lines. This is needed since at boot time the system read the rc.sysinit script to find module dependencies in the kernel by default. Version 6.2 only Comment out the line 260 in the rc.sysinit file vi +260 /etc/rc.d/ rc.sysinit: if [ -x /sbin/depmod -a -n "$USEMODULES" ]; then, To read: #if [ -x /sbin/depmod -a -n "$USEMODULES" ]; then Comment out the lines 272 to 277 in the rc.sysinit file vi +272 /etc/rc.d /rc.sysinit: if [ -L /lib/modules/default ]; then INITLOG_ARGS= action "Finding module dependencies" depmod -a default else INITLOG_ARGS= action "Finding module dependencies" depmod -a fi fi To read: # if [ -L /lib/modules/default ]; then # INITLOG_ARGS= action "Finding module dependencies" depmod -a default # else # INITLOG_ARGS= action "Finding module dependencies" depmod -a # fi #fi Important : The procedure described above relates to initscripts-4_70-1 package under Red Hat Linux version 6.1. Version 6.2 only Comment out the line 243 in the rc.sysinit file vi +243 /etc/rc.d/ rc.sysinit: if [ -x /sbin/depmod -a -n "$USEMODULES" ]; then, To read: #if [ -x /sbin/depmod -a -n "$USEMODULES" ]; then Comment out the lines 255 to 260 in the rc.sysinit file vi +255 /etc/rc.d /rc.sysinit: if [ -L /lib/modules/default ]; then INITLOG_ARGS= action "Finding module dependencies" depmod -a default else INITLOG_ARGS= action "Finding module dependencies" depmod -a fi fi To read: # if [ -L /lib/modules/default ]; then # INITLOG_ARGS= action "Finding module dependencies" depmod -a default # else # INITLOG_ARGS= action "Finding module dependencies" depmod -a # fi #fi Once again, all of this part Delete program, file and lines related to modules is required only if you said No to Enable loadable module support CONFIG_MODULES in your kernel configuration above. 3. Now you must Reboot your system and test your results. [root@deep] /#reboot When the system is rebooted and you are logged in, verify the new version of your kernel with the following command: To verify the version of your new kernel, use the following command: [root@deep] /#uname -a               Linux deep.openna.com 2.2.14 #1 Mon Jan 10 10:40:35 EDT 2000 i686 unknown [root@deep]#             Congratulation !. ----------------------------------------------------------------------------- 7.12. Create a emergency Rescue and Boot floppy disk After the reboot of your Linux server, you should have now a system with an upgraded kernel. Therefore, it's time is to make a new rescue image with the new kernel in case of future emergencies. To do this, follow the simple step below; Login as root, and insert a new floppy, then execute the following command: [root@deep] /#mkbootdisk --device /dev/fd0 2.2.14                 Insert a disk in /dev/fd0. Any information on the disk will be lost. Press --device ^C to abort:               Important : The mkbootdisk program runs only on modularized kernel. So you can't use it on a monolithic kernel; instead create an emergency boot floppy as shown below if you have a problem with your system in the future. Because it is possible to create a rescue floppy only on modularized kernel, we must find another way to boot our Linux system if the Linux kernel on the hard disk is damaged. This is possible with a Linux emergency boot floppy disk. You should immediately create it after you successfully start your system and log in as root. 1. To create the emergency boot floppy disk, follow these steps: a. Insert a floppy disk and format it with the following command: [root@deep] /#fdformat /dev/fd0H1440                 Double-sided, 80 tracks, 18 sec/track. Total capacity 1440 kB. Formatting ... done Verifying ... done               b. Copy the file vmlinuz from the /boot directory to the floppy disk: [root@deep] /#cp /boot/vmlinuz /dev/fd0                 cp: overwrite '/dev/fd0'? y               The vmlinuz file is a symbolic link that point to the real Linux kernel. c. Determine the kernel's root device with the following command: [root@deep] /#rdev /dev/sda12 / The kernel's root device is the disk partition where the root file system is located. In this example, the root device is dev/sda12; the device name may be different on your system. d. Set the kernel's root device with the following command: [root@deep] /#rdev /dev/fd0 /dev/sda12 To set the kernel's root device, use the device reported by the rdev command utility in the previous step. e. 5.Mark the root device as read-only with the following command: [root@deep] /#rdev -R /dev/fd0 1 This causes Linux initially to mount the root file system as read-only. By setting the root device as read-only, you avoid several warning and error messages. f. Now put the boot floppy in the drive A: and reboot your system with the following command: [root@deep] /#reboot 2. Update your /dev entries:If you have added new devices to your system or have done recently a major kernel upgrade (a major kernel upgrade is for example when you pass from kernel version 2.2.9 to 2.2.15 directly), it may be important to update your /dev entries to avoid problems related to missing devices. We can accomplish this task with the MAKEDEV script utility that scan the /dev directory where all devices that interfaces with drivers in the kernel are kept. A special option named update allow the MAKEDEV utility to create new devices that you have configured in your kernel and delete those which are no longer configured.To update your /dev entries, execute the following commands: [root@deep] /#cd /dev [root@deep ] /dev#./MAKEDEV update 4. Networking -Management, Firewall, Masquerading and Forwarding PIG Until now, we have not tinkered with the networking capabilities of Linux. Linux is one of the best existing operating systems in the world for networking features. Most Internet sites around the world already know this, and have used it for quite some time. Understanding your hardware network and all files related to it is very important if you want to have a full control of what happens on your server. Good knowledge of primary networking commands is vital. Network management covers a wide variety of topics. In general, it includes gathering statistical data and status of parts of your network, and taking action as necessary to deal with failures and other changes. Table of Contents 8. TCP/IP -Network Management 8.1. Multiple Ethernet Card per Machine 9. Files -Networking Functionality 9.1. The /etc/HOSTNAME file 9.2. The /etc/sysconfig/network-scripts/ifcfg-ethN files 9.3. The /etc/resolv.conf file 9.4. The /etc/host.conf file 9.5. The /etc/sysconfig/network file 9.6. The /etc/sysctl.conf file 9.7. The /etc/hosts file 9.8. Config TCP/IP Networking manually -command line 10. Networking -Firewall 10.1. Policy, Guidelines etc. 10.2. The topology 10.3. Build a kernel with IPCHAINS Firewall support 10.4. Rules used in the Firewall script files 10.5. Source Address Filtering 11. The firewall scripts files 11.1. Config /etc/rc.d/init.d/firewall script file -Web Server 11.2. Config /etc/rc.d/init.d/firewall script file - Mail Server 12. Networking Firewall -Masquerading and Forwarding 12.1. Build a kernel with Firewall Masquerading and Forwarding support 12.2. Config /etc/rc.d/init.d/firewall script file -Gateway Server 12.3. Configure script for Example Gateway Server 12.4. Deny access to some address 12.5. IPCHAINS Administrative Tools ----------------------------------------------------------------------------- Chapter 8. TCP/IP -Network Management The most primitive technique for network monitoring is periodic pinging of critical hosts. More sophisticated network monitoring requires the ability to get specific status and statistical information from various devices on the network. These should include various sorts of data gram counts, as well as counts of errors of various kinds. For these reasons, in this part we will try to answer fundamental questions about networking devices, files related to networking functionality, and essential networking commands. ----------------------------------------------------------------------------- 8.1. Multiple Ethernet Card per Machine You can use Linux as a gateway between two Ethernet networks. In that case, you might have two Ethernet cards on your server. To eliminate problems at boot time, the Linux kernel doesn't detect multiple cards automatically. If you happen to have two or more cards, you should specify the parameters of the cards in the lilo.conf file for a monolithic kernel or in the conf.modules file for a modularized kernel. The following are problems you may encounter with your network cards. Problem 1. If the driver(s) of the card(s) is/are being used as a loadable module modularized kernel, in the case of PCI drivers, the module will typically detect all of the installed cards automatically. For ISA cards, you need to supply the I/O base address of the card so the module knows where to look. This information is stored in the file /etc/conf.modules. Example 8-1. Two ISA ethernet cards Consider we have two ISA 3c509 cards, one at I/O 0x300 and one at I/O 0x320. For ISA cards, edit the conf.modules file, vi /etc/conf.modules and add: alias eth0 3c509 alias eth1 3c509 options 3c509 io=0x300,0x320 This says that the 3c509 driver should be loaded for either eth0 or eth1 alias eth0, eth1 and it should be loaded with the options io=0x300,0x320 so that the drivers knows where to look for the cards. Note that 0x is important, things like 300h as commonly used in the DOS world wont work. For PCI cards, you typically only need the alias lines to correlate the ethN interfaces with the appropriate driver name, since the I/O base of a PCI card can be safely detected. For PCI cards, edit the conf.modules file vi / etc/conf.modules and add: alias eth0 3c509 alias eth1 3c509 Problem 2. If the drivers(s) of the card(s) is/are compiled into the kernel - monolithic kernel, the PCI probes will find all related cards automatically. ISA cards will also find all related cards automatically, but in some circumstance ISA cards still need to do the following. This information is stored in the file /etc/lilo.conf. The method is to pass boot-time arguments to the kernel, which is usually done by LILO. For ISA cards, edit the lilo.conf file, vi /etc/lilo.conf and add: append=ether=0,0,eth1 Important : First test your ISA cards without the boot-time arguments in the lilo.conf file, and if this fails, use the boot-time arguments. In this case eth0 and eth1 will be assigned in the order that the cards are found at boot. Since we have recompiled the kernel, we must use the second method. If the drivers(s) is/are compiled into the kernel to install our second Ethernet card on the system. Remember that this is required only in some circumstance for ISA cards, PCI cards will be found automatically. ----------------------------------------------------------------------------- Chapter 9. Files -Networking Functionality This chapter deals with all the basic files usually text files related to TCP /IP networking.It's very important to know the configurations files related to TCP/IP networking, so that you can edit and configure the files if necessary. Remember that our server doesn't have an Xwindow interface to configure files via graphical interface. Even if you use a GUI in your daily activities it is important to know how to configure network in text mode. The following sections describe the basic TCP/IP configuration files. ----------------------------------------------------------------------------- 9.1. The /etc/HOSTNAME file This file stores your system's host name, your system's fully qualified domain name -FQDN, such as deep.openna.com. Following is a sample /etc/ HOSTNAME file: deep.openna.com ----------------------------------------------------------------------------- 9.2. The /etc/sysconfig/network-scripts/ifcfg-ethN files File configurations for each network device you may have or want to add on your system are located in the /etc/sysconfig/network-scripts/ directory with Red Hat Linux 6.1 or 6.2 and are named ifcfg-eth0 for the first interface and ifcfg-eth1 for the second, etc. Following is a example /etc/sysconfig/ network-scripts/ifcfg-eth0 file: DEVICE=eth0 IPADDR=208.164.186.1 NETMASK=255.255.255.0 NETWORK=208.164.186.0 BROADCAST=208.164.186.255 ONBOOT=yes BOOTPROTO=none USERCTL=no If you want to modify your network address manually, or add a new network on a new interface, edit this file -ifcfg-ethN, or create a new one and make the appropriate changes.   *  DEVICE=devicename, where devicename is the name of the physical network device.   *  IPADDR=ipaddr, where ipaddr is the IP address.   *  NETMASK=netmask, where netmask is the netmask IP value.   *  NETWORK=network, where network is the network IP address.   *  BROADCAST=broadcast, where broadcast is the broadcast IP address.   *  ONBOOT=answer, where answer is yes or no. Do the interface need to be active or inactive at boot time.   *  BOOTPROTO=proto, where proto is one of the following : i. none - No boot-time protocol should be used. ii. bootp - The bootp now pump protocol should be used. iii. dhcp - The dhcp protocol should be used.   *  USERCTL=answer, where answer is one of the following: 1. yes - Non-root users are allowed to control this device. 2. no - Only the super-user root is allowed to control this device. ----------------------------------------------------------------------------- 9.3. The /etc/resolv.conf file This file is another text file, used by the resolver a library that determines the IP address for a host name. Following is a sample /etc/ resolv.conf file: search openna.com nameserver 208.164.186.1 nameserver 208.164.186.2 Note : Name servers are queried in the order they appear in the file primary, secondary. ----------------------------------------------------------------------------- 9.4. The /etc/host.conf file This file specifies how names are resolved. Linux uses a resolver library to obtain the IP address corresponding to a host name. Following is a sample /etc/host.conf file: # Lookup names via DNS first then fall back to /etc/hosts. order bind,hosts (1) # We have machines with multiple addresses. multi on (2) # Check for IP address spoofing. nospoof on (3) (1) The order option indicates the order of services. The sample entry specifies that the resolver library should first consult the name server (DNS) to resolve a name and then check the /etc/hosts file. (2) The multi option determines whether a host in the /etc/hosts file can have multiple IP addresses multiple interface ethN. Hosts that have more than one IP address are said to be multiomed, because the presence of multiple IP addresses implies that host has several network interfaces. (3) The nospoof option indicates to take care of not permitting spoofing on this machine. IP-Spoofing is a security exploit that works by tricking computers in a trust relationship that you are someone that you really aren't. ----------------------------------------------------------------------------- 9.5. The /etc/sysconfig/network file The /etc/sysconfig/network file is used to specify information about the desired network configuration on your server. Following is a example /etc/ sysconfig/network file: NETWORKING=yes FORWARD_IPV4=yes HOSTNAME=deep. openna.com GATEWAY=0.0.0.0 GATEWAYDEV= The following values may be used:   *  NETWORKING=answer, where answer is yes or no -Configure networking or not to configure networking.   *  FORWARD_IPV4=answer, where answer is yes or no -Perform IP forwarding or not to perform IP forwarding.   *  HOSTNAME=hostname, where hostname is the hostname of your server.   *  GATEWAY=gwip, where gwip is the IP address of the remote network gateway -if available.   *  GATEWAYDEV=gwdev, where gwdev is the device name eth# you use to access the remote gateway. Important : For compatibility with older software, the /etc/HOSTNAME file should contain the same value as HOSTNAME= hostname above. With the new version of Red Hat Linux 6.2 the FORWARD_IPV4= parameter is now specified in the /etc/sysctl.conf file instead of the /etc/sysconfig/network file. ----------------------------------------------------------------------------- 9.6. The /etc/sysctl.conf file In Red Hat Linux 6.2, many kernel options related to networking security such as dropping packets that come in over interfaces they shouldn't or ignoring ping/broadcasts request, etc. can be set in the new /etc/sysctl.conf file instead of the /etc/rc.d/rc.local file. One important consideration is the IPv4 forwarding parameter which is now done via the sysctl program, as opposed to being controlled by the contents of the file in /etc/sysconfig/ network. The sysctl settings are stored in /etc/sysctl.conf, and are loaded at each boot before the /etc/rc.d/rc.local file is loaded. We've already talked about all networking security parameters that we must set into the server in General System Security, and for this reason we'll focus only on the kernel option for IPv4 forwarding. To enable IPv4 forwarding on your RH 6.2 system, use the following command: Edit the /etc/sysctl.conf file and add the following line: # Enable packet forwarding net.ipv4.ip_forward = 1 You must restart your network for the change to take effect. The command to restart the network is the following: [root@deep] /# /etc/rc.d/init.d/network restart Setting network parameters [ OK ] Bringing up interface lo [ OK ] Bringing up interface eth0 [ OK ] Bringing up interface eth1 [ OK ] Tip : Enabling IPv4 forwarding via the sysctl.conf file is only valid for Red Hat Linux 6.2 users. Users with version 6.1 of Red Hat must set this parameter into the /etc/sysconfig/network file as explained above. ----------------------------------------------------------------------------- 9.7. The /etc/hosts file As your machine gets started, it will need to know the mapping of some hostnames to IP addresses before DNS can be referenced. This mapping is kept in the /etc/hosts file. In the absence of a name server, any network program on your system consults this file to determine the IP address that corresponds to a host name. Following is a sample /etc/hosts file: IPAddress Hostname Alias 127.0.0.1 localhost deep.openna.com 208.164.186.1 deep.openna.com deep 208.164.186.2 mail.openna.com mail 208.164.186.3 web.openna.com web The leftmost column is the IP address to be resolved. The next column is that host's name. Any subsequent columns are alias for that host. In the second line, for example, the IP address 208.164.186.1 is for the host deep.openna.com. Another name for deep.openna.com is deep. After you are finished configuring your networking files, don't forget to restart your network for the changes to take effect. [root@deep] /# /etc/rc.d/init.d/network restart Setting network parameters [ OK ] Bringing up interface lo [ OK ] Bringing up interface eth0 [ OK ] Bringing up interface eth1 [ OK ] Important : Time out problems for telnet or ftp connection are often caused by the server trying to resolve the client IP address to a DNS name. Either DNS isn't configured properly on your server or the client machines aren't known to DNS. If you intend to run telnet or ftp services on your server, and aren't using DNS, don't forget to add the client machine name and IP in your /etc/hosts file on the server or you can expect to wait several minutes for the DNS lookup to time out, before you get a login: prompt. ----------------------------------------------------------------------------- 9.8. Config TCP/IP Networking manually -command line The ifconfig utility is the tool used to set up and configure your network card. You should understand this command in the event you need to configure the network by hand. An important note to take care with is when using ifconfig to configure your network devices; the settings will not survive a reboot. To assign the eth0 interface the IP-address of 208.164.186.2 use the command: [root@deep] /#ifconfig eth0 208.164.186.2 netmask 255.255.255.0 Tip : Usually, the pratice is to configure or change the TCP/IP networking manually only to make some test on the server. If you want to keep your TCP/IP values, it's preferable to set them in the files related to networking functionality. To display all the interfaces you have on your server, use the command: [root@deep] /#ifconfig The output should look something like this: eth0 Link encap:Ethernet HWaddr 00:E0:18:90:1B:56 inet addr:208.164.186.2 Bcast:208.164.186.255 Mask:255.255.255.0 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:1295 errors:0 dropped:0 overruns:0 frame:0 TX packets:1163 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:100 Interrupt:11 Base address:0xa800 lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 UP LOOPBACK RUNNING MTU:3924 Metric:1 RX packets:139 errors:0 dropped:0 overruns:0 frame:0 TX packets:139 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 If the ifconfig tool is invoked without any parameters, it displays all interfaces you have configured. An option of -a shows the inactive one as well. To display all interfaces as well as inactive interfaces you may have, use the command: [root@deep] /#ifconfig -a The output should look something like this: eth0 Link encap:Ethernet HWaddr 00:E0:18:90:1B:56 inet addr:208.164.186.2 Bcast:208.164.186.255 Mask:255.255.255.0 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:1295 errors:0 dropped:0 overruns:0 frame:0 TX packets:1163 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:100 Interrupt:11 Base address:0xa800 eth1 Link encap:Ethernet HWaddr 00:E0:18:90:1B:56 inet addr:192.168.1.1 Bcast:192.168.1.255 Mask:255.255.255.0 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:1295 errors:0 dropped:0 overruns:0 frame:0 TX packets:1163 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:100 Interrupt:5 Base address:0xa320 lo Link encap:Local Loopback inet addr:127.0.0.1 Mask:255.0.0.0 UP LOOPBACK RUNNING MTU:3924 Metric:1 RX packets:139 errors:0 dropped:0 overruns:0 frame:0 TX packets:139 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 It is important to note that the settings configured with the ifconfig toll for your network devices will not survive a reboot. To assign the default gateway for 208.164.186.12 use the command: [root@deep] /#route add default gw 208.164.186.1 In this example, the default route is set up to go to 208.164.186.12, your router. Once again, if you want to keep your default gateway value, it's preferable to set in it the files related to networking functionality -/etc/ sysconfig/network. Verify that you can reach your hosts. Choose a host from your network, for instance 208.164.186.1. Use the command: [root@deep] /#ping 208.164.186.1 The output should look something like this: [root@deep networking]# ping 208.164.186.1 PING 208.164.186.1 (208.164.186.1) from 208.164.186.2 : 56 data bytes 64 bytes from 208.164.186.2: icmp_seq=0 ttl=128 time=1.0 ms 64 bytes from 208.164.186.2: icmp_seq=1 ttl=128 time=1.0 ms 64 bytes from 208.164.186.2: icmp_seq=2 ttl=128 time=1.0 ms 64 bytes from 208.164.186.2: icmp_seq=3 ttl=128 time=1.0 ms --- 208.164.186.1 ping statistics --- 4 packets transmitted, 4 packets received, 0% packet loss round-trip min/avg/max = 1.0/1.0/1.0 ms You should now display the routing information with the command route to see if both hosts have the correct routing entry. Use the command: [root@deep] /#route -n The output should look something like this: Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface 208.164.186.2 0.0.0.0 255.255.255.255 UH 0 0 0 eth0 208.164.186.0 208.164.186.2 255.255.255.0 UG 0 0 0 eth0 208.164.186.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0 127.0.0.0 0.0.0.0 255.0.0.0 U 0 0 0 lo To check the status of the interfaces quickly, use the netstat -i command, as follows: [root@deep] /#netstat -i The output should look something like this: Kernel Interface table Iface MTU Met RX-OK RX-ERR RX-DRP RX-OVR TX-OK TX-ERR TX-DRP TX-OVR Flg eth0 1500 0 4236 0 0 0 3700 0 0 0 BRU lo 3924 0 13300 0 0 0 13300 0 0 0 LRU ppp0 1500 0 14 1 0 0 16 0 0 0 PRU Another useful netstat option is -t, which shows all active TCP connections. Following is a typical result of netstat -t: [root@deep] /#netstat -t The output should look something like this: Active Internet connections (w/o servers) Proto Recv-Q Send-Q Local Address Foreign Address State Tcp 0 0 deep.openar:netbios-ssn gate.openna.com:1045 ESTABLISHED Tcp 0 0 localhost:1032 localhost:1033 ESTABLISHED Tcp 0 0 localhost:1033 localhost:1032 ESTABLISHED Tcp 0 0 localhost:1030 localhost:1034 ESTABLISHED Tcp 0 0 localhost:1031 localhost:1030 ESTABLISHED Tcp 0 0 localhost:1028 localhost:1029 ESTABLISHED Tcp 0 0 localhost:1029 localhost:1028 ESTABLISHED Tcp 0 0 localhost:1026 localhost:1027 ESTABLISHED Tcp 0 0 localhost:1027 localhost:1026 ESTABLISHED Tcp 0 0 localhost:1024 localhost:1025 ESTABLISHED Tcp 0 0 localhost:1025 localhost:1024 ESTABLISHED To shows all active and listen TCP connections, use the command: [root@deep] /#netstat -vat The output should look something like this: Active Internet connections (servers and established) Proto Recv-Q Send-Q Local Address Foreign Address State tcp 0 0 deep.openna.co:domain *:* LISTEN tcp 0 0 localhost:domain *:* LISTEN tcp 0 0 deep.openna.com:ssh gate.openna.com:1682 ESTABLISHED tcp 0 0 *:webcache *:* LISTEN tcp 0 0 deep.openar:netbios-ssn *:* LISTEN tcp 0 0 localhost:netbios-ssn *:* LISTEN tcp 0 0 localhost:1032 localhost:1033 ESTABLISHED tcp 0 0 localhost:1033 localhost:1032 ESTABLISHED tcp 0 0 localhost:1030 localhost:1031 ESTABLISHED tcp 0 0 localhost:1031 localhost:1030 ESTABLISHED tcp 0 0 localhost:1028 localhost:1029 ESTABLISHED tcp 0 0 localhost:1029 localhost:1028 ESTABLISHED tcp 0 0 localhost:1026 localhost:1027 ESTABLISHED tcp 0 0 localhost:1027 localhost:1026 ESTABLISHED tcp 0 0 localhost:1024 localhost:1025 ESTABLISHED tcp 0 0 localhost:1025 localhost:1024 ESTABLISHED tcp 0 0 deep.openna.com:www *:* LISTEN tcp 0 0 deep.openna.com:https *:* LISTEN tcp 0 0 *:389 *:* LISTEN tcp 0 0 *:ssh *:* LISTEN To stop all network devices manually on your system, use the following command: [root@deep] /# /etc/rc.d/init.d/network stop Shutting down interface eth0 [ OK ] Disabling IPv4 packet forwarding [ OK ] To start all network devices manually on your system, use the following command: [root@deep] /# /etc/rc.d/init.d/network start Enabling IPv4 packet forwarding [ OK ] Bringing up interface lo [ OK ] Bringing up interface eth0 [ OK ] ----------------------------------------------------------------------------- Chapter 10. Networking -Firewall Can someone tell me why I might want something like a commercial firewall product rather than simply using Ipchains and restricting certain packets? What am I losing by using Ipchains? Now, there is undoubtedly room for debate on this- Ipchains is as good, and most of the time better, than commercial firewall packages from a functionality and support standpoint. You will probably have more insight into what's going on in your network using Ipchains than a commercial solution. That said, a lot of corporate types want to tell their shareholders, CEO,CTO etc. that they have the backing of reputable security Software Company. The firewall could be doing nothing more than passing through all traffic, and still the corporate type would be more comfortable than having to rely on the geeky guy in the corner cube who gets grumpy if you turn the light on before noon. In the end, a lot of companies want to be able to turn around and demand some sort of restitution from a vendor if the network is breached, whether or not they'd actually get anything or even try. All they can typically do with an open source solution is fire the guy that implemented it. At least some of the commercial firewalls are based on Linux or something similar. It's quite probable that Ipchains is secure enough for you but not those engaging in serious amounts of high stakes bond trading. Doing a cost/benefit analysis and asking a lot of pertinent questions is recommended before spending serious money on a commercial firewall---otherwise you may end up with something inferior to your Ipchains tool. Quite a few of the NT firewalls are likely to be no better than Ipchains and the general consensus on bugtraq and NT bugtraq are that NT is far too insecure to run a serious firewall. ----------------------------------------------------------------------------- 10.1. Policy, Guidelines etc. What is a Network Firewall Security Policy? Network firewall security policy defines those services that will be explicitly allowed or denied, how these services will be used and the exceptions to these rules. An organization's overall security policy must be determined according to security and business-need analysis. Since a firewall relates to network security alone, a firewall has little value unless the overall security policy is properly defined. Every rule in the network firewall security policy should be implemented on a firewall. Generally, a firewall uses one of the following methods. Everything not specifically permitted is denied. This approach blocks all traffic between two networks except for those services and applications that are permitted. Therefore, each desired service and application should be implemented one by one. No service or application that might be a potential hole on the firewall should be permitted. This is the most secure method, denying services and applications unless explicitly allowed by the administrator. On the other hand, from the point of users, it might be more restrictive and less convenient. This is the method we will use in our Firewall configuration files in this book. Everything not specifically denied is permitted This approach allows all traffic between two networks except for those services and applications that are denied. Therefore, each untrusted or potentially harmful service or application should be denied one by one. Although this is a flexible and convenient method for the users, it could potentially cause some serious security problems. What is Packet Filtering? Packet Filtering is the type of firewall built into the Linux kernel. A filtering firewall works at the network level. Data is only allowed to leave the system if the firewall rules allow it. As packets arrive they are filtered by their type, source address, destination address, and port information contained in each packet. Most of the time, packet filtering is accomplished by using a router that can forward packets according to filtering rules. When a packet arrives at the packet-filtering router, the router extracts certain information from the packet header and makes decisions according to the filter rules as to whether the packet will pass through or be discarded. The following information can be extracted from the packet header: Source IP address Destination IP address TCP/UDP source port TCP/UDP destination port ICMP message type Encapsulated protocol information (TCP, UDP, ICMP or IP tunnel) Because very little data is analyzed and logged, filtering firewalls take less CPU power and create less latency in your network. There are lots of ways to structure your network to protect your systems using a firewall. ----------------------------------------------------------------------------- 10.2. The topology All servers should be configured to block at least the unused ports, even if there are not a firewall server. This is required for more security. Imagine someone gains access to your firewall gateway server: if your neighborhoods servers are not configured to block unused ports, this is a serious network risk. The same is true for local connections; unauthorized employees can gain access from the inside to your other servers in this manner. In our configuration we will give you three different examples that can help you to configure your firewall rules depending on the type of the server you want to protect and the placement of these servers on your network architecture. The first example firewall rules file will be for a Web Server. The second for a Mail Server. The last for a Gateway Server that acts as proxy for the inside Wins, Workstations and Servers machines. See the graph below to get an idea: Firewall schematic representaion The graph above shows you the ports that I enable on the different servers by default in my firewall scripts file in this book www.openna.com Caching Only DNS 208.164.186.3 . i. Unlimited traffic on the loopback interface allowed ii. ICMP traffic allowed iii. DNS Caching and Client Server on port 53 allowed iv. SSH Server on port 22 allowed v. HTTP Server on port 80 allowed vi. HTTPS Server on port 443 allowed vii. SMTP Client on port 25 allowed viii. FTP Server on ports 20, 21 allowed ix. Outgoing traceroute request allowed deep.openna.com Master DNS Server 208.164.186.1 . i. Unlimited traffic on the loopback interface allowed ii. ICMP traffic allowed iii. DNS Server and Client on port 53 allowed iv. SSH Server and Client on port 22 allowed v. HTTP Server and Client on port 80 allowed vi. HTTPS Server and Client on port 443 allowed vii. WWW-CACHE Client on port 8080 allowed viii. External POP Client on port 110 allowed ix. External NNTP NEWS Client on port 119 allowed x. SMTP Server and Client on port 25 allowed xi. IMAP Server on port 143 allowed xii. IRC Client on port 6667 allowed xiii. ICQ Client on port 4000 allowed xiv. FTP Client on port 20, 21 allowed xv. RealAudio / QuickTime Client allowed xvi. Outgoing traceroute request allowed mail.openna.com Slave DNS Server 208.164.186.2 . i. Unlimited traffic on the loopback interface allowed ii. ICMP traffic allowed iii. DNS Server and Client on port 53 allowed iv. SSH Server on port 22 allowed v. SMTP Server and Client on port 25 allowed vi. IMAP Server on port 143 allowed vii. Outgoing traceroute request allowed The list above shows you the ports that I enable on the different servers by default in my firewall scripts file in this book. Depending on what services must be available in the server for the outside, you must configure your firewall script file to allow the traffic on the specified ports.   *  www.openna.com is our Web Server,   *  mail.openna.com is our Mail Hub Server for all the internal network,   *  deep.openna.com is our Gateway Server for all the examples explained later in this chapter. ----------------------------------------------------------------------------- 10.3. Build a kernel with IPCHAINS Firewall support The first thing you need to do is ensure that your kernel has been built with Network Firewall support enabled and Firewalling. Remember, all servers should be configured to block unused ports, even if there are no firewall server. In the 2.2.14 kernel version you need to be sure that you have answered Y to the following questions: Networking options: Network firewalls (CONFIG_FIREFALL) [N] Y IP:Firewalling (CONFIG_IP_FIREWALL) [N] Y IP:TCP syncookie support (CONFIG_SYN_COOKIES) [N] Y If you have followed the Linux Kernel section and have recompiled your kernel, the options Network firewalls, IP:Firewalling, and IP:TCP syncookie support shown above are already set. ----------------------------------------------------------------------------- 10.4. Rules used in the Firewall script files The following is an explanation of a few of the rules that will be used in the Firewalling examples below. This is shown just as a reference, the firewall scripts are well commented and very easy to modify. Constants are used, in the firewall scripts files for most values. The most basic constants are: EXTERNAL_INTERFACE This is the name of the external network interface to the Internet. It's defined as eth0 in the examples. LOCAL_INTERFACE_1 This is the name of the internal network interface to the LAN, if any. It's defined as eth1 in the examples. LOOPBACK_INTERFACE This is the name of the loopback interface. It's defined as lo in the examples. IPADDR This is the IP address of your external interface. It's either a static IP address registered with InterNIC, or else a dynamically assigned address from your ISP (usually via DHCP). LOCALNET_1 This is your LAN network address, if any - the entire range of IP addresses used by the machines on your LAN. These may be statically assigned, or you might run a local DHCP server to assign them. In these examples, the range is 192.168.1.0/24, part of the Class C private address range. ANYWHERE Anywhere is a label for an address used by ipchains to match any (non-broadcast) address. Both programs provide any/0 as a label for this address, which is 0.0.0.0/0. NAMESERVER_1 This is the IP address of your Primary DNS Server from your network or your ISP. NAMESERVER_2 This is the IP address of your Secondary DNS Server from your network or your ISP. MY_ISP This is your ISP & NOC address range. The value you specify here is used by the firewall to allow ICMP ping request and traceroute. If you don't specify an IP address range, then you will not be able to ping the Internet from your internal network. LOOPBACK The loopback address range is 127.0.0.0/8. The interface itself is addressed as 127.0.0.1 in /etc/hosts. PRIVPORTS The privileged ports, 0 through 1023, are usually referenced in total. UNPRIVPORTS The unprivileged ports, 1024 through 65535, are usually referenced in total. They are addresses dynamically assigned to the client side of a connection. Please Note a firewall has a default policy and a collection of actions to take in response to specific message types. This means that if a given packet has not been selected by any other rule, then the default policy rule will be applied. Tip : People with dynamically assigned IPs from an ISP may include the following two lines in their declarations for the firewall. The lines will determine the ppp0 IP address, and the network of the remote ppp server. IPADDR=`/sbin/ifconfig | grep -A 4 ppp0 | awk '/inet/ { print $2 } ' | sed -e s/addr://` MY_ISP=`/sbin/ifconfig | grep -A 4 ppp0 | awk '/P-t-P/ { print $3 } ' | sed -e s/P-t-P:// | cut -d '.' -f 1-3`.0/24 You need to Enable Local Traffic since the default policies for all example firewall rule script files in this book are to deny everything, some of these rules must be unset. Local network services do not go through the external network interface. They go through a special, private interface called the loopback interface. None of your local network programs will work until loopback traffic is allowed. # Unlimited traffic on the loopback interface. ipchains -A input -i $LOOPBACK_INTERFACE -j ACCEPT ipchains -A output -i $LOOPBACK_INTERFACE -j ACCEPT ----------------------------------------------------------------------------- 10.5. Source Address Filtering All IP packet headers contain the source and destination IP addresses and the type of IP protocol message; ICMP, UDP or TCP this packet contains. The only means of identification under the Internet Protocol - IP) is the source address in the IP packet header. This is a problem that opens the door to source address spoofing, where the sender may replaces its address with either a nonexistent address, or the address of some other site. # Refuse spoofed packets pretending to be from the external address. ipchains -A input -i $EXTERNAL_INTERFACE -s $IPADDR -l -j DENY Also, there are at least seven sets of source addresses you should refuse on your external interface in all cases. These are incoming packets claiming to be from: i. Your external IP address ii. Class A private IP addresses iii. Class B private IP addresses iv. Class C private IP addresses v. Class D multicast addresses vi. Class E reserved addresses vii. The loopback interface With the exception of your own IP address, blocking outgoing packets containing these source addresses protects you from possible configuration errors on your part. Important : Don't forget to exclude your own IP address from outgoing packets blocked. By default I choose to exclude the Class C private IP addresses since it's the most used by the majority of people at this time. If you used another class instead of the Class C, then you must comment out the lines that refer to your class under the SPOOFING & BAD ADDRESSES section of the firewall. script file. The rest of the rules used in the firewall scripts files are:   *  Accessing a Service from the Outside World   *  Offering a Service to the Outside World   *  Masquerading the Internal Machines ----------------------------------------------------------------------------- Chapter 11. The firewall scripts files The tool ipchains allows you to set up firewalls, IP masquerading, etc. Ipchains talks to the kernel and tells it what packets to filter. Therefore all your firewall setups are stored in the kernel, and thus will be lost on reboot. To avoid this, we recommend using the System V init scripts to make your rules permanent. To do this, create a firewall script file like shown over the next three sections in your /etc/rc.d/init.d/ directory for each servers you have. Of course, each server has different services to offer and needs a different firewall setup. For this reason, we provide you three different firewall settings, which you can play with, and examine to fit your needs. Also I assume that you have a minimum knowledge on how filtering firewalls and firewall rules works. ----------------------------------------------------------------------------- 11.1. Config /etc/rc.d/init.d/firewall script file -Web Server Errata: Important As i was giving the final look over on this book, Gerhard Mourani has released an errata for all firewall scripts and it is available here http://www.openna.com/books/errata.htm This is the configuration script file for our Web Server. This configuration allows unlimited traffic on the Loopback interface, ICMP, DNS Caching and Client Server (53), SSH Server (22), HTTP Server (80), HTTPS Server (443), SMTP Client (25), FTP Server (20, 21), and OUTGOING TRACEROUTE requests by default. If you don't want some services listed in the firewall rules files for the Web Server that I make ON by default, comment them out with a "#" at the beginning of the line. If you want some other services that I commented out with a "#", then remove the "#" at the beginning of those lines. Create the firewall script file, touch /etc/rc.d/init.d/firewall on your Web Server and add: #!/bin/sh # # ---------------------------------------------------------------------------- # Last modified by Gerhard Mourani: 04-25-2000 # ---------------------------------------------------------------------------- # Copyright (C) 1997, 1998, 1999 Robert L. Ziegler # # Permission to use, copy, modify, and distribute this software and its # documentation for educational, research, private and non-profit purposes, # without fee, and without a written agreement is hereby granted. # This software is provided as an example and basis for individual firewall # development. This software is provided without warranty. # # Any material furnished by Robert L. Ziegler is furnished on an # "as is" basis. He makes no warranties of any kind, either expressed # or implied as to any matter including, but not limited to, warranty # of fitness for a particular purpose, exclusivity or results obtained # from use of the material. # ---------------------------------------------------------------------------- # # Invoked from /etc/rc.d/init.d/firewall. # chkconfig: - 60 95 # description: Starts and stops the IPCHAINS Firewall \ # used to provide Firewall network services. # Source function library. . /etc/rc.d/init.d/functions # Source networking configuration. . /etc/sysconfig/network # Check that networking is up. if [ ${NETWORKING} = "no" ] then exit 0 fi if [ ! -x /sbin/ipchains ]; then exit 0 fi # See how we were called. case "$1" in start) echo -n "Starting Firewalling Services: " # Some definitions for easy maintenance. # ---------------------------------------------------------------------------- # EDIT THESE TO SUIT YOUR SYSTEM AND ISP. EXTERNAL_INTERFACE="eth0" # Internet connected interface LOOPBACK_INTERFACE="lo" # Your local naming convention IPADDR="my.ip.address" # Your IP address ANYWHERE="any/0" # Match any IP address NAMESERVER_1="my.name.server.1" # Everyone must have at least one NAMESERVER_2="my.name.server.2" # Your secondary name server MY_ISP="my.isp.address.range/24" # ISP & NOC address range SMTP_SERVER="my.smtp.server" # Your Mail Hub Server. SYSLOG_SERVER="syslog.internal.server" # Your syslog internal server SYSLOG_CLIENT="sys.int.client.range/24" # Your syslog internal client range LOOPBACK="127.0.0.0/8" # Reserved loopback address range CLASS_A="10.0.0.0/8" # Class A private networks CLASS_B="172.16.0.0/12" # Class B private networks CLASS_C="192.168.0.0/16" # Class C private networks CLASS_D_MULTICAST="224.0.0.0/4" # Class D multicast addresses CLASS_E_RESERVED_NET="240.0.0.0/5" # Class E reserved addresses BROADCAST_SRC="0.0.0.0" # Broadcast source address BROADCAST_DEST="255.255.255.255" # Broadcast destination address PRIVPORTS="0:1023" # Well known, privileged port range UNPRIVPORTS="1024:65535" # Unprivileged port range # ---------------------------------------------------------------------------- # SSH starts at 1023 and works down to 513 for # each additional simultaneous incoming connection. SSH_PORTS="1022:1023" # range for SSH privileged ports # traceroute usually uses -S 32769:65535 -D 33434:33523 TRACEROUTE_SRC_PORTS="32769:65535" TRACEROUTE_DEST_PORTS="33434:33523" # ---------------------------------------------------------------------------- # Default policy is DENY # Explicitly accept desired INCOMING & OUTGOING connections # Remove all existing rules belonging to this filter ipchains -F # Clearing all current rules and user defined chains ipchains -X # Set the default policy of the filter to deny. # Don't even bother sending an error message back. ipchains -P input DENY ipchains -P output DENY ipchains -P forward DENY # ---------------------------------------------------------------------------- # LOOPBACK # Unlimited traffic on the loopback interface. ipchains -A input -i $LOOPBACK_INTERFACE -j ACCEPT ipchains -A output -i $LOOPBACK_INTERFACE -j ACCEPT # ---------------------------------------------------------------------------- # Network Ghouls # Deny access to jerks # /etc/rc.d/rc.firewall.blocked contains a list of # ipchains -A input -i $EXTERNAL_INTERFACE -s address -j DENY # rules to block from any access. # Refuse any connection from problem sites #if [ -f /etc/rc.d/rc.firewall.blocked ]; then # . /etc/rc.d/rc.firewall.blocked #fi # ---------------------------------------------------------------------------- # SPOOFING & BAD ADDRESSES # Refuse spoofed packets. # Ignore blatantly illegal source addresses. # Protect yourself from sending to bad addresses. # Refuse spoofed packets pretending to be from the external address. ipchains -A input -i $EXTERNAL_INTERFACE -s $IPADDR -j DENY -l # Refuse packets claiming to be to or from a Class A private network ipchains -A input -i $EXTERNAL_INTERFACE -s $CLASS_A -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -d $CLASS_A -j DENY -l ipchains -A output -i $EXTERNAL_INTERFACE -s $CLASS_A -j REJECT -l ipchains -A output -i $EXTERNAL_INTERFACE -d $CLASS_A -j REJECT -l # Refuse packets claiming to be to or from a Class B private network ipchains -A input -i $EXTERNAL_INTERFACE -s $CLASS_B -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -d $CLASS_B -j DENY -l ipchains -A output -i $EXTERNAL_INTERFACE -s $CLASS_B -j REJECT -l ipchains -A output -i $EXTERNAL_INTERFACE -d $CLASS_B -j REJECT -l # Refuse packets claiming to be to or from a Class C private network # ipchains -A input -i $EXTERNAL_INTERFACE -s $CLASS_C -j DENY -l # ipchains -A input -i $EXTERNAL_INTERFACE -d $CLASS_C -j DENY -l # ipchains -A output -i $EXTERNAL_INTERFACE -s $CLASS_C -j REJECT -l # ipchains -A output -i $EXTERNAL_INTERFACE -d $CLASS_C -j REJECT -l # Refuse packets claiming to be from the loopback interface ipchains -A input -i $EXTERNAL_INTERFACE -s $LOOPBACK -j DENY -l ipchains -A output -i $EXTERNAL_INTERFACE -s $LOOPBACK -j REJECT -l # Refuse broadcast address SOURCE packets ipchains -A input -i $EXTERNAL_INTERFACE -s $BROADCAST_DEST -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -d $BROADCAST_SRC -j DENY -l # Refuse Class D multicast addresses (in.h) (NET-3-HOWTO) # Multicast is illegal as a source address. # Multicast uses UDP. ipchains -A input -i $EXTERNAL_INTERFACE -s $CLASS_D_MULTICAST -j DENY -l # Refuse Class E reserved IP addresses ipchains -A input -i $EXTERNAL_INTERFACE -s $CLASS_E_RESERVED_NET -j DENY -l # refuse addresses defined as reserved by the IANA # 0.*.*.*, 1.*.*.*, 2.*.*.*, 5.*.*.*, 7.*.*.*, 23.*.*.*, 27.*.*.* # 31.*.*.*, 37.*.*.*, 39.*.*.*, 41.*.*.*, 42.*.*.*, 58-60.*.*.* # 65-95.*.*.*, 96-126.*.*.*, 197.*.*.*, 201.*.*.* (?), 217-223.*.*.* ipchains -A input -i $EXTERNAL_INTERFACE -s 1.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 2.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 5.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 7.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 23.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 27.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 31.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 37.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 39.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 41.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 42.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 58.0.0.0/7 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 60.0.0.0/8 -j DENY -l #65: 01000001 - /3 includes 64 - need 65-79 spelled out ipchains -A input -i $EXTERNAL_INTERFACE -s 65.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 66.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 67.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 68.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 69.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 70.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 71.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 72.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 73.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 74.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 75.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 76.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 77.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 78.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 79.0.0.0/8 -j DENY -l #80: 01010000 - /4 masks 80-95 ipchains -A input -i $EXTERNAL_INTERFACE -s 80.0.0.0/4 -j DENY -l # 96: 01100000 - /4 makses 96-111 ipchains -A input -i $EXTERNAL_INTERFACE -s 96.0.0.0/4 -j DENY -l #126: 01111110 - /3 includes 127 - need 112-126 spelled out ipchains -A input -i $EXTERNAL_INTERFACE -s 112.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 113.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 114.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 115.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 116.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 117.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 118.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 119.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 120.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 121.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 122.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 123.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 124.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 125.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 126.0.0.0/8 -j DENY -l #217: 11011001 - /5 includes 216 - need 217-219 spelled out ipchains -A input -i $EXTERNAL_INTERFACE -s 217.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 218.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 219.0.0.0/8 -j DENY -l #223: 11011111 - /6 masks 220-223 ipchains -A input -i $EXTERNAL_INTERFACE -s 220.0.0.0/6 -j DENY -l # ---------------------------------------------------------------------------- # ICMP # To prevent denial of service attacks based on ICMP bombs, filter # incoming Redirect (5) and outgoing Destination Unreachable (3). # Note, however, disabling Destination Unreachable (3) is not # advisable, as it is used to negotiate packet fragment size. # For bi-directional ping. # Message Types: Echo_Reply (0), Echo_Request (8) # To prevent attacks, limit the src addresses to your ISP range. # # For outgoing traceroute. # Message Types: INCOMING Dest_Unreachable (3), Time_Exceeded (11) # default UDP base: 33434 to base+nhops-1 # # For incoming traceroute. # Message Types: OUTGOING Dest_Unreachable (3), Time_Exceeded (11) # To block this, deny OUTGOING 3 and 11 # 0: echo-reply (pong) # 3: destination-unreachable, port-unreachable, fragmentation-needed, etc. # 4: source-quench # 5: redirect # 8: echo-request (ping) # 11: time-exceeded # 12: parameter-problem ipchains -A input -i $EXTERNAL_INTERFACE -p icmp \ -s $ANYWHERE 0 -d $IPADDR -j ACCEPT ipchains -A input -i $EXTERNAL_INTERFACE -p icmp \ -s $ANYWHERE 3 -d $IPADDR -j ACCEPT ipchains -A input -i $EXTERNAL_INTERFACE -p icmp \ -s $ANYWHERE 4 -d $IPADDR -j ACCEPT ipchains -A input -i $EXTERNAL_INTERFACE -p icmp \ -s $ANYWHERE 11 -d $IPADDR -j ACCEPT ipchains -A input -i $EXTERNAL_INTERFACE -p icmp \ -s $ANYWHERE 12 -d $IPADDR -j ACCEPT ipchains -A input -i $EXTERNAL_INTERFACE -p icmp \ -s $MY_ISP 8 -d $IPADDR -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p icmp \ -s $IPADDR 0 -d $MY_ISP -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p icmp \ -s $IPADDR 3 -d $MY_ISP -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p icmp \ -s $IPADDR 4 -d $ANYWHERE -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p icmp \ -s $IPADDR 8 -d $ANYWHERE -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p icmp \ -s $IPADDR 12 -d $ANYWHERE -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p icmp \ -s $IPADDR 11 -d $MY_ISP -j ACCEPT # ---------------------------------------------------------------------------- # UDP INCOMING TRACEROUTE # traceroute usually uses -S 32769:65535 -D 33434:33523 ipchains -A input -i $EXTERNAL_INTERFACE -p udp \ -s $MY_ISP $TRACEROUTE_SRC_PORTS \ -d $IPADDR $TRACEROUTE_DEST_PORTS -j ACCEPT -l ipchains -A input -i $EXTERNAL_INTERFACE -p udp \ -s $ANYWHERE $TRACEROUTE_SRC_PORTS \ -d $IPADDR $TRACEROUTE_DEST_PORTS -j DENY -l # ---------------------------------------------------------------------------- # DNS forwarding, caching only nameserver (53) # -------------------------------------------- # server to server query or response # Caching only name server only requires UDP, not TCP ipchains -A input -i $EXTERNAL_INTERFACE -p udp \ -s $NAMESERVER_1 53 \ -d $IPADDR 53 -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p udp \ -s $IPADDR 53 \ -d $NAMESERVER_1 53 -j ACCEPT ipchains -A input -i $EXTERNAL_INTERFACE -p udp \ -s $NAMESERVER_2 53 \ -d $IPADDR 53 -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p udp \ -s $IPADDR 53 \ -d $NAMESERVER_2 53 -j ACCEPT # DNS client (53) # --------------- ipchains -A input -i $EXTERNAL_INTERFACE -p udp \ -s $NAMESERVER_1 53 \ -d $IPADDR $UNPRIVPORTS -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p udp \ -s $IPADDR $UNPRIVPORTS \ -d $NAMESERVER_1 53 -j ACCEPT ipchains -A input -i $EXTERNAL_INTERFACE -p udp \ -s $NAMESERVER_2 53 \ -d $IPADDR $UNPRIVPORTS -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p udp \ -s $IPADDR $UNPRIVPORTS \ -d $NAMESERVER_2 53 -j ACCEPT # TCP client to server requests are allowed by the protocol # if UDP requests fail. This is rarely seen. Usually, clients # use TCP as a secondary nameserver for zone transfers from # their primary nameservers, and as hackers. ipchains -A input -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $NAMESERVER_1 53 \ -d $IPADDR $UNPRIVPORTS -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp \ -s $IPADDR $UNPRIVPORTS \ -d $NAMESERVER_1 53 -j ACCEPT ipchains -A input -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $NAMESERVER_2 53 \ -d $IPADDR $UNPRIVPORTS -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp \ -s $IPADDR $UNPRIVPORTS \ -d $NAMESERVER_2 53 -j ACCEPT # ---------------------------------------------------------------------------- # TCP accept only on selected ports # --------------------------------- # ------------------------------------------------------------------ # SSH server (22) # --------------- ipchains -A input -i $EXTERNAL_INTERFACE -p tcp \ -s $ANYWHERE $UNPRIVPORTS \ -d $IPADDR 22 -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $IPADDR 22 \ -d $ANYWHERE $UNPRIVPORTS -j ACCEPT ipchains -A input -i $EXTERNAL_INTERFACE -p tcp \ -s $ANYWHERE $SSH_PORTS \ -d $IPADDR 22 -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $IPADDR 22 \ -d $ANYWHERE $SSH_PORTS -j ACCEPT # ------------------------------------------------------------------ # HTTP server (80) # ---------------- ipchains -A input -i $EXTERNAL_INTERFACE -p tcp \ -s $ANYWHERE $UNPRIVPORTS \ -d $IPADDR 80 -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $IPADDR 80 \ -d $ANYWHERE $UNPRIVPORTS -j ACCEPT # ------------------------------------------------------------------ # HTTPS server (443) # ------------------ ipchains -A input -i $EXTERNAL_INTERFACE -p tcp \ -s $ANYWHERE $UNPRIVPORTS \ -d $IPADDR 443 -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $IPADDR 443 \ -d $ANYWHERE $UNPRIVPORTS -j ACCEPT # ------------------------------------------------------------------ # SYSLOG server (514) # ----------------- # Provides full remote logging. Using this feature you're able to # control all syslog messages on one host. # ipchains -A input -i $EXTERNAL_INTERFACE -p udp \ # -s $SYSLOG_CLIENT \ # -d $IPADDR 514 -j ACCEPT # SYSLOG client (514) # ----------------- # ipchains -A output -i $EXTERNAL_INTERFACE -p udp \ # -s $IPADDR 514 \ # -d $SYSLOG_SERVER 514 -j ACCEPT # ------------------------------------------------------------------ # AUTH server (113) # ----------------- # Reject, rather than deny, the incoming auth port. (NET-3-HOWTO) ipchains -A input -i $EXTERNAL_INTERFACE -p tcp \ -s $ANYWHERE \ -d $IPADDR 113 -j REJECT # ------------------------------------------------------------------ # SMTP client (25) # ---------------- ipchains -A input -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $SMTP_SERVER 25 \ -d $IPADDR $UNPRIVPORTS -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp \ -s $IPADDR $UNPRIVPORTS \ -d $SMTP_SERVER 25 -j ACCEPT # ------------------------------------------------------------------ # FTP server (20, 21) # ------------------- # incoming request ipchains -A input -i $EXTERNAL_INTERFACE -p tcp \ -s $ANYWHERE $UNPRIVPORTS \ -d $IPADDR 21 -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $IPADDR 21 \ -d $ANYWHERE $UNPRIVPORTS -j ACCEPT # PORT MODE data channel responses # ipchains -A input -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $ANYWHERE $UNPRIVPORTS \ -d $IPADDR 20 -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp \ -s $IPADDR 20 \ -d $ANYWHERE $UNPRIVPORTS -j ACCEPT # PASSIVE MODE data channel responses ipchains -A input -i $EXTERNAL_INTERFACE -p tcp \ -s $ANYWHERE $UNPRIVPORTS \ -d $IPADDR $UNPRIVPORTS -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $IPADDR $UNPRIVPORTS \ -d $ANYWHERE $UNPRIVPORTS -j ACCEPT # ------------------------------------------------------------------ # OUTGOING TRACEROUTE # ------------------- ipchains -A output -i $EXTERNAL_INTERFACE -p udp \ -s $IPADDR $TRACEROUTE_SRC_PORTS \ -d $ANYWHERE $TRACEROUTE_DEST_PORTS -j ACCEPT # ---------------------------------------------------------------------------- # Enable logging for selected denied packets ipchains -A input -i $EXTERNAL_INTERFACE -p tcp \ -d $IPADDR -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -p udp \ -d $IPADDR $PRIVPORTS -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -p udp \ -d $IPADDR $UNPRIVPORTS -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -p icmp \ -s $ANYWHERE 5 -d $IPADDR -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -p icmp \ -s $ANYWHERE 13:255 -d $IPADDR -j DENY -l # ---------------------------------------------------------------------------- ;; stop) echo -n "Shutting Firewalling Services: " # Remove all existing rules belonging to this filter ipchains -F # Delete all user-defined chain to this filter ipchains -X # Reset the default policy of the filter to accept. ipchains -P input ACCEPT ipchains -P output ACCEPT ipchains -P forward ACCEPT ;; status) status firewall ;; restart|reload) $0 stop $0 start ;; *) echo "Usage: firewall {start|stop|status|restart|reload}" exit 1 esac exit 0 Now, make this script executable and change its default permissions: [root@deep] /# chmod 700 /etc/rc.d/init.d/firewall [root@deep] /# chown 0.0 /etc/rc.d/init.d/firewall Create the symbolic rc.d links for your Firewall with the following command: [root@deep] /# chkconfig --add firewall [root@deep] /# chkconfig --level 345 firewall on Now, your firewall rules are configured to use System V init (System V init is in charge of starting all the normal processes that need to run at boot time) and it will be automatically started each time your server reboots. To manually stop the firewall on your system, use the following command: [root@deep] /# /etc/rc.d/init.d/firewall stop Shutting Firewalling Services: [ OK ] To manually start the firewall on your system, use the following command: [root@deep] /# /etc/rc.d/init.d/firewall start Starting Firewalling Services: [ OK ] ----------------------------------------------------------------------------- 11.2. Config /etc/rc.d/init.d/firewall script file - Mail Server This is the configuration script file for our Mail Server. This is configured to allows unlimited traffic on the Loopback interface, ICMP, DNS Server and Client (53), SSH Server (22), SMTP Server and Client (25), IMAP server (143), and OUTGOING TRACEROUTE requests by default. If you don't want some services listed in the firewall rules files for the Mail Server that I make ON by default, comment them out with a "#" at the beginning of the line. If you want some other services that I commented out with a "#", then remove the "#" at the beginning of their lines. Create the firewall script file, touch /etc/rc.d/init.d/firewall on your Mail Server and add: #!/bin/sh # # ---------------------------------------------------------------------------- # Last modified by Gerhard Mourani: 04-25-2000 # ---------------------------------------------------------------------------- # Copyright (C) 1997, 1998, 1999 Robert L. Ziegler # # Permission to use, copy, modify, and distribute this software and its # documentation for educational, research, private and non-profit purposes, # without fee, and without a written agreement is hereby granted. # This software is provided as an example and basis for individual firewall # development. This software is provided without warranty. # # Any material furnished by Robert L. Ziegler is furnished on an # "as is" basis. He makes no warranties of any kind, either expressed # or implied as to any matter including, but not limited to, warranty # of fitness for a particular purpose, exclusivity or results obtained # from use of the material. # ---------------------------------------------------------------------------- # # Invoked from /etc/rc.d/init.d/firewall. # chkconfig: - 60 95 # description: Starts and stops the IPCHAINS Firewall \ # used to provide Firewall network services. # Source function library. . /etc/rc.d/init.d/functions # Source networking configuration. . /etc/sysconfig/network # Check that networking is up. if [ ${NETWORKING} = "no" ] then exit 0 fi if [ ! -x /sbin/ipchains ]; then exit 0 fi # See how we were called. case "$1" in start) echo -n "Starting Firewalling Services: " # Some definitions for easy maintenance. # ---------------------------------------------------------------------------- # EDIT THESE TO SUIT YOUR SYSTEM AND ISP. EXTERNAL_INTERFACE="eth0" # Internet connected interface LOOPBACK_INTERFACE="lo" # Your local naming convention IPADDR="my.ip.address" # Your IP address ANYWHERE="any/0" # Match any IP address NAMESERVER_1="my.name.server.1" # Everyone must have at least one NAMESERVER_2="my.name.server.2" # Your secondary name server MY_ISP="my.isp.address.range/24" # ISP & NOC address range SMTP_SERVER="my.smtp.server" # Your Mail Hub Server. SYSLOG_SERVER="syslog.internal.server" # Your syslog internal server SYSLOG_CLIENT="sys.int.client.range/24" # Your syslog internal client range LOOPBACK="127.0.0.0/8" # Reserved loopback address range CLASS_A="10.0.0.0/8" # Class A private networks CLASS_B="172.16.0.0/12" # Class B private networks CLASS_C="192.168.0.0/16" # Class C private networks CLASS_D_MULTICAST="224.0.0.0/4" # Class D multicast addresses CLASS_E_RESERVED_NET="240.0.0.0/5" # Class E reserved addresses BROADCAST_SRC="0.0.0.0" # Broadcast source address BROADCAST_DEST="255.255.255.255" # Broadcast destination address PRIVPORTS="0:1023" # Well known, privileged port range UNPRIVPORTS="1024:65535" # Unprivileged port range # ---------------------------------------------------------------------------- # SSH starts at 1023 and works down to 513 for # each additional simultaneous incoming connection. SSH_PORTS="1022:1023" # range for SSH privileged ports # traceroute usually uses -S 32769:65535 -D 33434:33523 TRACEROUTE_SRC_PORTS="32769:65535" TRACEROUTE_DEST_PORTS="33434:33523" # ---------------------------------------------------------------------------- # Default policy is DENY # Explicitly accept desired INCOMING & OUTGOING connections # Remove all existing rules belonging to this filter ipchains -F # Clearing all current rules and user defined chains ipchains -X # Set the default policy of the filter to deny. # Don't even bother sending an error message back. ipchains -P input DENY ipchains -P output DENY ipchains -P forward DENY # ---------------------------------------------------------------------------- # LOOPBACK # Unlimited traffic on the loopback interface. ipchains -A input -i $LOOPBACK_INTERFACE -j ACCEPT ipchains -A output -i $LOOPBACK_INTERFACE -j ACCEPT # ---------------------------------------------------------------------------- # Network Ghouls # Deny access to jerks # /etc/rc.d/rc.firewall.blocked contains a list of # ipchains -A input -i $EXTERNAL_INTERFACE -s address -j DENY # rules to block from any access. # Refuse any connection from problem sites #if [ -f /etc/rc.d/rc.firewall.blocked ]; then # . /etc/rc.d/rc.firewall.blocked #fi # ---------------------------------------------------------------------------- # SPOOFING & BAD ADDRESSES # Refuse spoofed packets. # Ignore blatantly illegal source addresses. # Protect yourself from sending to bad addresses. # Refuse spoofed packets pretending to be from the external address. ipchains -A input -i $EXTERNAL_INTERFACE -s $IPADDR -j DENY -l # Refuse packets claiming to be to or from a Class A private network ipchains -A input -i $EXTERNAL_INTERFACE -s $CLASS_A -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -d $CLASS_A -j DENY -l ipchains -A output -i $EXTERNAL_INTERFACE -s $CLASS_A -j REJECT -l ipchains -A output -i $EXTERNAL_INTERFACE -d $CLASS_A -j REJECT -l # Refuse packets claiming to be to or from a Class B private network ipchains -A input -i $EXTERNAL_INTERFACE -s $CLASS_B -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -d $CLASS_B -j DENY -l ipchains -A output -i $EXTERNAL_INTERFACE -s $CLASS_B -j REJECT -l ipchains -A output -i $EXTERNAL_INTERFACE -d $CLASS_B -j REJECT -l # Refuse packets claiming to be to or from a Class C private network # ipchains -A input -i $EXTERNAL_INTERFACE -s $CLASS_C -j DENY -l # ipchains -A input -i $EXTERNAL_INTERFACE -d $CLASS_C -j DENY -l # ipchains -A output -i $EXTERNAL_INTERFACE -s $CLASS_C -j REJECT -l # ipchains -A output -i $EXTERNAL_INTERFACE -d $CLASS_C -j REJECT -l # Refuse packets claiming to be from the loopback interface ipchains -A input -i $EXTERNAL_INTERFACE -s $LOOPBACK -j DENY -l ipchains -A output -i $EXTERNAL_INTERFACE -s $LOOPBACK -j REJECT -l # Refuse broadcast address SOURCE packets ipchains -A input -i $EXTERNAL_INTERFACE -s $BROADCAST_DEST -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -d $BROADCAST_SRC -j DENY -l # Refuse Class D multicast addresses (in.h) (NET-3-HOWTO) # Multicast is illegal as a source address. # Multicast uses UDP. ipchains -A input -i $EXTERNAL_INTERFACE -s $CLASS_D_MULTICAST -j DENY -l # Refuse Class E reserved IP addresses ipchains -A input -i $EXTERNAL_INTERFACE -s $CLASS_E_RESERVED_NET -j DENY -l # refuse addresses defined as reserved by the IANA # 0.*.*.*, 1.*.*.*, 2.*.*.*, 5.*.*.*, 7.*.*.*, 23.*.*.*, 27.*.*.* # 31.*.*.*, 37.*.*.*, 39.*.*.*, 41.*.*.*, 42.*.*.*, 58-60.*.*.* # 65-95.*.*.*, 96-126.*.*.*, 197.*.*.*, 201.*.*.* (?), 217-223.*.*.* ipchains -A input -i $EXTERNAL_INTERFACE -s 1.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 2.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 5.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 7.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 23.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 27.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 31.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 37.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 39.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 41.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 42.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 58.0.0.0/7 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 60.0.0.0/8 -j DENY -l #65: 01000001 - /3 includes 64 - need 65-79 spelled out ipchains -A input -i $EXTERNAL_INTERFACE -s 65.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 66.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 67.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 68.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 69.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 70.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 71.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 72.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 73.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 74.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 75.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 76.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 77.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 78.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 79.0.0.0/8 -j DENY -l #80: 01010000 - /4 masks 80-95 ipchains -A input -i $EXTERNAL_INTERFACE -s 80.0.0.0/4 -j DENY -l # 96: 01100000 - /4 makses 96-111 ipchains -A input -i $EXTERNAL_INTERFACE -s 96.0.0.0/4 -j DENY -l #126: 01111110 - /3 includes 127 - need 112-126 spelled out ipchains -A input -i $EXTERNAL_INTERFACE -s 112.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 113.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 114.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 115.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 116.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 117.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 118.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 119.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 120.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 121.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 122.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 123.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 124.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 125.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 126.0.0.0/8 -j DENY -l #217: 11011001 - /5 includes 216 - need 217-219 spelled out ipchains -A input -i $EXTERNAL_INTERFACE -s 217.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 218.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 219.0.0.0/8 -j DENY -l #223: 11011111 - /6 masks 220-223 ipchains -A input -i $EXTERNAL_INTERFACE -s 220.0.0.0/6 -j DENY -l # ---------------------------------------------------------------------------- # ICMP # To prevent denial of service attacks based on ICMP bombs, filter # incoming Redirect (5) and outgoing Destination Unreachable (3). # Note, however, disabling Destination Unreachable (3) is not # advisable, as it is used to negotiate packet fragment size. # For bi-directional ping. # Message Types: Echo_Reply (0), Echo_Request (8) # To prevent attacks, limit the src addresses to your ISP range. # # For outgoing traceroute. # Message Types: INCOMING Dest_Unreachable (3), Time_Exceeded (11) # default UDP base: 33434 to base+nhops-1 # # For incoming traceroute. # Message Types: OUTGOING Dest_Unreachable (3), Time_Exceeded (11) # To block this, deny OUTGOING 3 and 11 # 0: echo-reply (pong) # 3: destination-unreachable, port-unreachable, fragmentation-needed, etc. # 4: source-quench # 5: redirect # 8: echo-request (ping) # 11: time-exceeded # 12: parameter-problem ipchains -A input -i $EXTERNAL_INTERFACE -p icmp \ -s $ANYWHERE 0 -d $IPADDR -j ACCEPT ipchains -A input -i $EXTERNAL_INTERFACE -p icmp \ -s $ANYWHERE 3 -d $IPADDR -j ACCEPT ipchains -A input -i $EXTERNAL_INTERFACE -p icmp \ -s $ANYWHERE 4 -d $IPADDR -j ACCEPT ipchains -A input -i $EXTERNAL_INTERFACE -p icmp \ -s $ANYWHERE 11 -d $IPADDR -j ACCEPT ipchains -A input -i $EXTERNAL_INTERFACE -p icmp \ -s $ANYWHERE 12 -d $IPADDR -j ACCEPT ipchains -A input -i $EXTERNAL_INTERFACE -p icmp \ -s $MY_ISP 8 -d $IPADDR -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p icmp \ -s $IPADDR 0 -d $MY_ISP -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p icmp \ -s $IPADDR 3 -d $MY_ISP -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p icmp \ -s $IPADDR 4 -d $ANYWHERE -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p icmp \ -s $IPADDR 8 -d $ANYWHERE -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p icmp \ -s $IPADDR 12 -d $ANYWHERE -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p icmp \ -s $IPADDR 11 -d $MY_ISP -j ACCEPT # ---------------------------------------------------------------------------- # UDP INCOMING TRACEROUTE # traceroute usually uses -S 32769:65535 -D 33434:33523 ipchains -A input -i $EXTERNAL_INTERFACE -p udp \ -s $MY_ISP $TRACEROUTE_SRC_PORTS \ -d $IPADDR $TRACEROUTE_DEST_PORTS -j ACCEPT -l ipchains -A input -i $EXTERNAL_INTERFACE -p udp \ -s $ANYWHERE $TRACEROUTE_SRC_PORTS \ -d $IPADDR $TRACEROUTE_DEST_PORTS -j DENY -l # ---------------------------------------------------------------------------- # DNS server # ---------- # DNS: full server # server/client to server query or response ipchains -A input -i $EXTERNAL_INTERFACE -p udp \ -s $ANYWHERE $UNPRIVPORTS \ -d $IPADDR 53 -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p udp \ -s $IPADDR 53 \ -d $ANYWHERE $UNPRIVPORTS -j ACCEPT # DNS client & Zone Transfers (53) # --------------- ipchains -A input -i $EXTERNAL_INTERFACE -p udp \ -s $NAMESERVER_1 53 \ -d $IPADDR $UNPRIVPORTS -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p udp \ -s $IPADDR $UNPRIVPORTS \ -d $NAMESERVER_1 53 -j ACCEPT ipchains -A input -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $NAMESERVER_1 53 \ -d $IPADDR $UNPRIVPORTS -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp \ -s $IPADDR $UNPRIVPORTS \ -d $NAMESERVER_1 53 -j ACCEPT # ---------------------------------------------------------------------------- # TCP accept only on selected ports # --------------------------------- # ------------------------------------------------------------------ # SSH server (22) # --------------- ipchains -A input -i $EXTERNAL_INTERFACE -p tcp \ -s $ANYWHERE $UNPRIVPORTS \ -d $IPADDR 22 -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $IPADDR 22 \ -d $ANYWHERE $UNPRIVPORTS -j ACCEPT ipchains -A input -i $EXTERNAL_INTERFACE -p tcp \ -s $ANYWHERE $SSH_PORTS \ -d $IPADDR 22 -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $IPADDR 22 \ -d $ANYWHERE $SSH_PORTS -j ACCEPT # ------------------------------------------------------------------ # AUTH server (113) # ----------------- # Reject, rather than deny, the incoming auth port. (NET-3-HOWTO) ipchains -A input -i $EXTERNAL_INTERFACE -p tcp \ -s $ANYWHERE \ -d $IPADDR 113 -j REJECT # ------------------------------------------------------------------ # SYSLOG server (514) # ----------------- # Provides full remote logging. Using this feature you're able to # control all syslog messages on one host. # ipchains -A input -i $EXTERNAL_INTERFACE -p udp \ # -s $SYSLOG_CLIENT \ # -d $IPADDR 514 -j ACCEPT # SYSLOG client (514) # ----------------- # ipchains -A output -i $EXTERNAL_INTERFACE -p udp \ # -s $IPADDR 514 \ # -d $SYSLOG_SERVER 514 -j ACCEPT # ------------------------------------------------------------------ # SMTP server (25) # ---------------- ipchains -A input -i $EXTERNAL_INTERFACE -p tcp \ -s $ANYWHERE $UNPRIVPORTS \ -d $IPADDR 25 -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $IPADDR 25 \ -d $ANYWHERE $UNPRIVPORTS -j ACCEPT # SMTP client (25) # ---------------- ipchains -A input -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $ANYWHERE 25 \ -d $IPADDR $UNPRIVPORTS -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp \ -s $IPADDR $UNPRIVPORTS \ -d $ANYWHERE 25 -j ACCEPT # ------------------------------------------------------------------ # IMAP server (143) # ----------------- ipchains -A input -i $EXTERNAL_INTERFACE -p tcp \ -s $ANYWHERE $UNPRIVPORTS \ -d $IPADDR 143 -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $IPADDR 143 \ -d $ANYWHERE $UNPRIVPORTS -j ACCEPT # POP server (110) # ----------------- # ipchains -A input -i $EXTERNAL_INTERFACE -p tcp \ # -s $ANYWHERE $UNPRIVPORTS \ # -d $IPADDR 110 -j ACCEPT # ipchains -A output -i $EXTERNAL_INTERFACE -p tcp ! -y \ # -s $IPADDR 110 \ # -d $ANYWHERE $UNPRIVPORTS -j ACCEPT # ------------------------------------------------------------------ # OUTGOING TRACEROUTE # ------------------- ipchains -A output -i $EXTERNAL_INTERFACE -p udp \ -s $IPADDR $TRACEROUTE_SRC_PORTS \ -d $ANYWHERE $TRACEROUTE_DEST_PORTS -j ACCEPT # ---------------------------------------------------------------------------- # Enable logging for selected denied packets ipchains -A input -i $EXTERNAL_INTERFACE -p tcp \ -d $IPADDR -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -p udp \ -d $IPADDR $PRIVPORTS -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -p udp \ -d $IPADDR $UNPRIVPORTS -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -p icmp \ -s $ANYWHERE 5 -d $IPADDR -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -p icmp \ -s $ANYWHERE 13:255 -d $IPADDR -j DENY -l # ---------------------------------------------------------------------------- ;; stop) echo -n "Shutting Firewalling Services: " # Remove all existing rules belonging to this filter ipchains -F # Delete all user-defined chain to this filter ipchains -X # Reset the default policy of the filter to accept. ipchains -P input ACCEPT ipchains -P output ACCEPT ipchains -P forward ACCEPT ;; status) status firewall ;; restart|reload) $0 stop $0 start ;; *) echo "Usage: firewall {start|stop|status|restart|reload}" exit 1 esac exit 0 Now, make this script executable and change its default permissions: [root@deep] /#chmod 700 /etc/rc.d/init.d/firewall [root@deep] /#chown 0.0 /etc/rc.d/init.d/firewall Create the symbolic rc.d links for your Firewall with the command: [root@deep] /#chkconfig --add firewall [root@deep] /#chkconfig --level 345 firewall on Now, your firewall rules are configured to use System V init (System V init is in charge of starting all the normal processes that need to run at boot time) and it will be automatically started each time if your server reboot. To manually stop the firewall on your system, use the following command: [root@deep] /# /etc/rc.d/init.d/firewall stop Shutting Firewalling Services: [ OK ] To manually start the firewall on your system, use the following command: [root@deep] /# /etc/rc.d/init.d/firewall start Starting Firewalling Services: [ OK ] ----------------------------------------------------------------------------- Chapter 12. Networking Firewall -Masquerading and Forwarding Unlike the example configurations in The firewall scripts files, configuring a Linux Server to masquerade and forward traffic generally from the inside private network that has unregistered IP addresses i.e. 192.168.1.0/24 to the outside network i.e. the Internet require a special setup of your kernel and of your firewall configuration scripts file. This kind of setting is also known as a Gateway Server, a machine that serves as a gateway for internal traffic to external traffic. This configuration must only be set if you have the intentions and the needs for this kind of service and it's for this reason that the configuration of the script file for the Gateway Server is in its own chapter. ----------------------------------------------------------------------------- 12.1. Build a kernel with Firewall Masquerading and Forwarding support Once again, the first thing you need to do is ensuring that your kernel has been built with Network Firewall support enabled and Firewalling. In the 2.2.14 kernel version you need to ensure that you have answered Y to the following questions: Networking options: Network firewalls (CONFIG_FIREFALL) [N] Y IP:Firewalling (CONFIG_IP_FIREWALL) [N] Y IP:TCP syncookie support (CONFIG_SYN_COOKIES) [N] Y Note : If you followed the Linux Kernel section and have recompiled your kernel, the options Network firewalls, IP:Firewalling, and IP:TCP syncookies supports shown above are already set. IP Masquerading and IP ICMP Masquerading are requiring only for a Gateway Server. IP:Masquerading (CONFIG_IP_MASQUERADE) [N] Y IP:ICMP Masquerading (CONFIG_IP_MASQUERADE_ICMP) [N] Y Important : Only your Gateway Server needs to have IP:Masquerading and IP :ICMP Masquerading kernel options enabled. This is required to masquerade your Internal Network to the outside. Masquerade means that if one of the computers on your local network for which your Linux box (or gateway) acts as a firewall wants to send something to the outside, your box can masquerade as that computer. In other words it forwards the traffic to the intended outside destination, but makes it look like it came from the firewall box itself. It works both ways: if the outside host replies, the Linux firewall will silently forward the traffic to the corresponding local computer. This way, the computers on your local net are completely invisible to the outside world, even though they can reach the outside and can receive replies. This makes it possible to have the computers on the local network participate on the Internet even if they don't have officially registered IP addresses. The IP masquerading code will only work if IP forwarding is enabled on your system. This feature is by default disabled and you can enable it with the following command: Under Version 6.1 only To enable IP forwarding feature on your server, execute the following command: [root@deep] /#echo 1 > /proc/sys/net/ipv4/ip_forward You can add the above line in your /etc/rc.d/rc.local script file so IP forwarding is enabled automatically for you even if your server is rebooted. In Red Hat Linux 6.1 this can also be accomplished by changing the line in / etc/sysconfig/network file from: FORWARD_IPV4="false" To read: FORWARD_IPV4="yes" You must restart your network for the change to take effect: [root@deep] /# /etc/rc.d/init.d/network restart Bringing up interface lo [ OK ] Bringing up interface eth0 [ OK ] Bringing up interface eth1 [ OK ] So you can either add the echo 1 > /proc/sys/net/ipv4/ip_forward command line to your rc.local script file or you change the value of the line FORWARD_IPV4 =false to yes in the network file to set this feature to ON. Personally I prefer the second choice. Under Version 6.2 only To enable IPv4 forwarding on your RH 6.2 system, Edit the /etc/sysctl.conf file and add the following line: # Enable packet forwarding net.ipv4.ip_forward = 1 You must restart your network for the change to take effect. The command to restart the network is the following: To restart all network devices manually on your system, use the following command: [root@deep] /# /etc/rc.d/init.d/network restart Setting network parameters [ OK ] Bringing up interface lo [ OK ] Bringing up interface eth0 [ OK ] Bringing up interface eth1 [ OK ] Important : The IP forwarding line above is only required if you answered Yes to the kernel option IP:Masquerading (CONFIG_IP_MASQUERADE) and choose to have a server act as a Gateway and masquerade for your inside network. If you enabled IP Masquerading, then the modules ip_masq_ftp.o for ftp file transfers, ip_masq_irc.o for irc chats, ip_masq_quake.o you guessed it!, ip_masq_vdolive.o for VDOLive video connections, ip_masq_cuseeme.o for CU-SeeMe broadcasts and ip_masq_raudio.o for RealAudio downloads will automatically be compiled. They are needed to make masquerading for these protocols work. Also, don't forget that you'll need to build a modularized kernel and answer Yes to the Enable loadable module support (CONFIG_MODULES) option instead of a monolithic kernel to be able to use masquerading functions and modules like ip_masq_ftp.o on your Gateway server see the Linux Kernel section above in this book for more information. The basic masquerade code described for IP: masquerading above only handles TCP or UDP packets and ICMP errors for existing connections. The IP:ICMP Masquerading option adds additional support for masquerading ICMP packets, such as ping or the probes used by the Windows 95™ tracer program. Remember that other servers like the Web Server and Mail Server examples don't need to have these options enabled since they either have a real IP address assigned or don't act as a Gateway for the inside network. ----------------------------------------------------------------------------- 12.2. Config /etc/rc.d/init.d/firewall script file -Gateway Server +---------------------------------------------------------------------------+ | Some Points to Consider | | | | You can safely assume that you are potentially at risk if you connect | | your system to the Internet. Your gateway to the Internet is your | | greatest exposure, so we recommend the following: | | | |   * The gateway should not run any more applications than are absolutely | | necessary. | | | |   * The gateway should strictly limit the type and number of protocols | | allowed to flow through it (protocols potentially provide security | | holes, such as FTP and telnet). | | | |   * Any system containing confidential or sensitive information should | | not be directly accessible from the Internet. | | | | | +---------------------------------------------------------------------------+ ----------------------------------------------------------------------------- 12.3. Configure script for Example Gateway Server This is the configuration script file for our Gateway Server. This configuration allows unlimited traffic on the Loopback interface, ICMP, DNS Server and Client (53), SSH Server and Client (22), HTTP Server and Client (80), HTTPS Server and Client (443), POP Client (110), NNTP NEWS Client (119), SMTP Server and Client (25), IMAP Server (143), IRC Client (6667), ICQ Client (4000), FTP Client (20, 21), RealAudio / QuickTime Client, and OUTGOING TRACEROUTE requests by default. If you don't want some services listed in the firewall rules files for the Gateway Server that I make ON by default, comment them out with a "#" at the beginning of the line. If you want some other services that I commented out with a "#", then remove the "#" at the beginning of their lines. If you have configured Masquerading on your server, don't forget to uncomment the modules necessary to masquerade their respective services that you need like ip_masq_irc.o, ip_masq_raudio.o, etc under the MODULES MASQUERADING section of the firewall script file. Create the firewall script file touch /etc/rc.d/init.d/firewall, on your Gateway Server and add: #!/bin/sh # # ---------------------------------------------------------------------------- # Last modified by Gerhard Mourani: 04-25-2000 # ---------------------------------------------------------------------------- # Copyright (C) 1997, 1998, 1999 Robert L. Ziegler # # Permission to use, copy, modify, and distribute this software and its # documentation for educational, research, private and non-profit purposes, # without fee, and without a written agreement is hereby granted. # This software is provided as an example and basis for individual firewall # development. This software is provided without warranty. # # Any material furnished by Robert L. Ziegler is furnished on an # "as is" basis. He makes no warranties of any kind, either expressed # or implied as to any matter including, but not limited to, warranty # of fitness for a particular purpose, exclusivity or results obtained # from use of the material. # ---------------------------------------------------------------------------- # # Invoked from /etc/rc.d/init.d/firewall. # chkconfig: - 60 95 # description: Starts and stops the IPCHAINS Firewall \ # used to provide Firewall network services. # Source function library. . /etc/rc.d/init.d/functions # Source networking configuration. . /etc/sysconfig/network # Check that networking is up. if [ ${NETWORKING} = "no" ] then exit 0 fi if [ ! -x /sbin/ipchains ]; then exit 0 fi # See how we were called. case "$1" in start) echo -n "Starting Firewalling Services: " # Some definitions for easy maintenance. # ---------------------------------------------------------------------------- # EDIT THESE TO SUIT YOUR SYSTEM AND ISP. EXTERNAL_INTERFACE="eth0" # Internet connected interface LOCAL_INTERFACE_1="eth1" # Internal LAN interface LOOPBACK_INTERFACE="lo" # Your local naming convention IPADDR="my.ip.address" # Your IP address LOCALNET_1="192.168.1.0/24" # Whatever private range you use IPSECSG="my.ipsecsg.address" # Space separated list of remote VPN gateways FREESWANVI="ipsec0" # Space separated list of virtual interfaces ANYWHERE="any/0" # Match any IP address NAMESERVER_1="my.name.server.1" # Everyone must have at least one NAMESERVER_2="my.name.server.2" # Your secondary name server MY_ISP="my.isp.address.range/24" # ISP & NOC address range SMTP_SERVER="my.smtp.server" # Your Mail Hub Server. POP_SERVER="my.pop.server" # External pop server, if any NEWS_SERVER="my.news.server" # External news server, if any SYSLOG_SERVER="syslog.internal.server" # Your syslog internal server LOOPBACK="127.0.0.0/8" # Reserved loopback address range CLASS_A="10.0.0.0/8" # Class A private networks CLASS_B="172.16.0.0/12" # Class B private networks CLASS_C="192.168.0.0/16" # Class C private networks CLASS_D_MULTICAST="224.0.0.0/4" # Class D multicast addresses CLASS_E_RESERVED_NET="240.0.0.0/5" # Class E reserved addresses BROADCAST_SRC="0.0.0.0" # Broadcast source address BROADCAST_DEST="255.255.255.255" # Broadcast destination address PRIVPORTS="0:1023" # Well known, privileged port range UNPRIVPORTS="1024:65535" # Unprivileged port range # ---------------------------------------------------------------------------- # SSH starts at 1023 and works down to 513 for # each additional simultaneous incoming connection. SSH_PORTS="1022:1023" # range for SSH privileged ports # traceroute usually uses -S 32769:65535 -D 33434:33523 TRACEROUTE_SRC_PORTS="32769:65535" TRACEROUTE_DEST_PORTS="33434:33523" # ---------------------------------------------------------------------------- # Default policy is DENY # Explicitly accept desired INCOMING & OUTGOING connections # Remove all existing rules belonging to this filter ipchains -F # Clearing all current rules and user defined chains ipchains -X # Set the default policy of the filter to deny. # Don't even bother sending an error message back. ipchains -P input DENY ipchains -P output DENY ipchains -P forward DENY # set masquerade timeout to 10 hours for tcp connections ipchains -M -S 36000 0 0 # Don't forward fragments. Assemble before forwarding. ipchains -A output -f -i $LOCAL_INTERFACE_1 -j DENY # ---------------------------------------------------------------------------- # MODULES MASQUERADING # Uncomment bellow all modules lines that you need # These modules are necessary to masquerade their respective services. /sbin/modprobe ip_masq_ftp /sbin/modprobe ip_masq_raudio ports=554,7070,7071,6970,6971 /sbin/modprobe ip_masq_irc #/sbin/modprobe ip_masq_vdolive #/sbin/modprobe ip_masq_cuseeme #/sbin/modprobe ip_masq_quake # ---------------------------------------------------------------------------- # LOOPBACK # Unlimited traffic on the loopback interface. ipchains -A input -i $LOOPBACK_INTERFACE -j ACCEPT ipchains -A output -i $LOOPBACK_INTERFACE -j ACCEPT # ---------------------------------------------------------------------------- # Network Ghouls # Deny access to jerks # /etc/rc.d/rc.firewall.blocked contains a list of # ipchains -A input -i $EXTERNAL_INTERFACE -s address -j DENY # rules to block from any access. # Refuse any connection from problem sites #if [ -f /etc/rc.d/rc.firewall.blocked ]; then # . /etc/rc.d/rc.firewall.blocked #fi # ---------------------------------------------------------------------------- # SPOOFING & BAD ADDRESSES # Refuse spoofed packets. # Ignore blatantly illegal source addresses. # Protect yourself from sending to bad addresses. # Refuse spoofed packets pretending to be from the external address. ipchains -A input -i $EXTERNAL_INTERFACE -s $IPADDR -j DENY -l # Refuse packets claiming to be to or from a Class A private network ipchains -A input -i $EXTERNAL_INTERFACE -s $CLASS_A -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -d $CLASS_A -j DENY -l ipchains -A output -i $EXTERNAL_INTERFACE -s $CLASS_A -j REJECT -l ipchains -A output -i $EXTERNAL_INTERFACE -d $CLASS_A -j REJECT -l # Refuse packets claiming to be to or from a Class B private network ipchains -A input -i $EXTERNAL_INTERFACE -s $CLASS_B -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -d $CLASS_B -j DENY -l ipchains -A output -i $EXTERNAL_INTERFACE -s $CLASS_B -j REJECT -l ipchains -A output -i $EXTERNAL_INTERFACE -d $CLASS_B -j REJECT -l # Refuse packets claiming to be to or from a Class C private network # ipchains -A input -i $EXTERNAL_INTERFACE -s $CLASS_C -j DENY -l # ipchains -A input -i $EXTERNAL_INTERFACE -d $CLASS_C -j DENY -l # ipchains -A output -i $EXTERNAL_INTERFACE -s $CLASS_C -j REJECT -l # ipchains -A output -i $EXTERNAL_INTERFACE -d $CLASS_C -j REJECT -l # Refuse packets claiming to be from the loopback interface ipchains -A input -i $EXTERNAL_INTERFACE -s $LOOPBACK -j DENY -l ipchains -A output -i $EXTERNAL_INTERFACE -s $LOOPBACK -j REJECT -l # Refuse broadcast address SOURCE packets ipchains -A input -i $EXTERNAL_INTERFACE -s $BROADCAST_DEST -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -d $BROADCAST_SRC -j DENY -l # Refuse Class D multicast addresses (in.h) (NET-3-HOWTO) # Multicast is illegal as a source address. # Multicast uses UDP. ipchains -A input -i $EXTERNAL_INTERFACE -s $CLASS_D_MULTICAST -j DENY -l # Refuse Class E reserved IP addresses ipchains -A input -i $EXTERNAL_INTERFACE -s $CLASS_E_RESERVED_NET -j DENY -l # refuse addresses defined as reserved by the IANA # 0.*.*.*, 1.*.*.*, 2.*.*.*, 5.*.*.*, 7.*.*.*, 23.*.*.*, 27.*.*.* # 31.*.*.*, 37.*.*.*, 39.*.*.*, 41.*.*.*, 42.*.*.*, 58-60.*.*.* # 65-95.*.*.*, 96-126.*.*.*, 197.*.*.*, 201.*.*.* (?), 217-223.*.*.* ipchains -A input -i $EXTERNAL_INTERFACE -s 1.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 2.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 5.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 7.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 23.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 27.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 31.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 37.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 39.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 41.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 42.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 58.0.0.0/7 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 60.0.0.0/8 -j DENY -l #65: 01000001 - /3 includes 64 - need 65-79 spelled out ipchains -A input -i $EXTERNAL_INTERFACE -s 65.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 66.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 67.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 68.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 69.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 70.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 71.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 72.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 73.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 74.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 75.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 76.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 77.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 78.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 79.0.0.0/8 -j DENY -l #80: 01010000 - /4 masks 80-95 ipchains -A input -i $EXTERNAL_INTERFACE -s 80.0.0.0/4 -j DENY -l # 96: 01100000 - /4 makses 96-111 ipchains -A input -i $EXTERNAL_INTERFACE -s 96.0.0.0/4 -j DENY -l #126: 01111110 - /3 includes 127 - need 112-126 spelled out ipchains -A input -i $EXTERNAL_INTERFACE -s 112.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 113.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 114.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 115.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 116.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 117.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 118.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 119.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 120.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 121.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 122.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 123.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 124.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 125.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 126.0.0.0/8 -j DENY -l #217: 11011001 - /5 includes 216 - need 217-219 spelled out ipchains -A input -i $EXTERNAL_INTERFACE -s 217.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 218.0.0.0/8 -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -s 219.0.0.0/8 -j DENY -l #223: 11011111 - /6 masks 220-223 ipchains -A input -i $EXTERNAL_INTERFACE -s 220.0.0.0/6 -j DENY -l # ---------------------------------------------------------------------------- # ICMP # To prevent denial of service attacks based on ICMP bombs, filter # incoming Redirect (5) and outgoing Destination Unreachable (3). # Note, however, disabling Destination Unreachable (3) is not # advisable, as it is used to negotiate packet fragment size. # For bi-directional ping. # Message Types: Echo_Reply (0), Echo_Request (8) # To prevent attacks, limit the src addresses to your ISP range. # # For outgoing traceroute. # Message Types: INCOMING Dest_Unreachable (3), Time_Exceeded (11) # default UDP base: 33434 to base+nhops-1 # # For incoming traceroute. # Message Types: OUTGOING Dest_Unreachable (3), Time_Exceeded (11) # To block this, deny OUTGOING 3 and 11 # 0: echo-reply (pong) # 3: destination-unreachable, port-unreachable, fragmentation-needed, etc. # 4: source-quench # 5: redirect # 8: echo-request (ping) # 11: time-exceeded # 12: parameter-problem ipchains -A input -i $EXTERNAL_INTERFACE -p icmp \ -s $ANYWHERE 0 -d $IPADDR -j ACCEPT ipchains -A input -i $EXTERNAL_INTERFACE -p icmp \ -s $ANYWHERE 3 -d $IPADDR -j ACCEPT ipchains -A input -i $EXTERNAL_INTERFACE -p icmp \ -s $ANYWHERE 4 -d $IPADDR -j ACCEPT ipchains -A input -i $EXTERNAL_INTERFACE -p icmp \ -s $ANYWHERE 11 -d $IPADDR -j ACCEPT ipchains -A input -i $EXTERNAL_INTERFACE -p icmp \ -s $ANYWHERE 12 -d $IPADDR -j ACCEPT ipchains -A input -i $EXTERNAL_INTERFACE -p icmp \ -s $MY_ISP 8 -d $IPADDR -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p icmp \ -s $IPADDR 0 -d $MY_ISP -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p icmp \ -s $IPADDR 3 -d $MY_ISP -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p icmp \ -s $IPADDR 4 -d $ANYWHERE -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p icmp \ -s $IPADDR 8 -d $ANYWHERE -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p icmp \ -s $IPADDR 12 -d $ANYWHERE -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p icmp \ -s $IPADDR 11 -d $MY_ISP -j ACCEPT # ---------------------------------------------------------------------------- # UDP INCOMING TRACEROUTE # traceroute usually uses -S 32769:65535 -D 33434:33523 ipchains -A input -i $EXTERNAL_INTERFACE -p udp \ -s $MY_ISP $TRACEROUTE_SRC_PORTS \ -d $IPADDR $TRACEROUTE_DEST_PORTS -j ACCEPT -l ipchains -A input -i $EXTERNAL_INTERFACE -p udp \ -s $ANYWHERE $TRACEROUTE_SRC_PORTS \ -d $IPADDR $TRACEROUTE_DEST_PORTS -j DENY -l # ---------------------------------------------------------------------------- # DNS server # ---------- # DNS: full server # server/client to server query or response ipchains -A input -i $EXTERNAL_INTERFACE -p udp \ -s $ANYWHERE $UNPRIVPORTS \ -d $IPADDR 53 -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p udp \ -s $IPADDR 53 \ -d $ANYWHERE $UNPRIVPORTS -j ACCEPT # DNS client (53) # --------------- ipchains -A input -i $EXTERNAL_INTERFACE -p udp \ -s $NAMESERVER_1 53 \ -d $IPADDR $UNPRIVPORTS -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p udp \ -s $IPADDR $UNPRIVPORTS \ -d $NAMESERVER_1 53 -j ACCEPT ipchains -A input -i $EXTERNAL_INTERFACE -p udp \ -s $NAMESERVER_2 53 \ -d $IPADDR $UNPRIVPORTS -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p udp \ -s $IPADDR $UNPRIVPORTS \ -d $NAMESERVER_2 53 -j ACCEPT # TCP client to server requests are allowed by the protocol # if UDP requests fail. This is rarely seen. Usually, clients # use TCP as a secondary nameserver for zone transfers from # their primary nameservers, and as hackers. ipchains -A input -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $NAMESERVER_1 53 \ -d $IPADDR $UNPRIVPORTS -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp \ -s $IPADDR $UNPRIVPORTS \ -d $NAMESERVER_1 53 -j ACCEPT ipchains -A input -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $NAMESERVER_2 53 \ -d $IPADDR $UNPRIVPORTS -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp \ -s $IPADDR $UNPRIVPORTS \ -d $NAMESERVER_2 53 -j ACCEPT # ---------------------------------------------------------------------------- # TCP accept only on selected ports # --------------------------------- # ------------------------------------------------------------------ # SSH server (22) # --------------- ipchains -A input -i $EXTERNAL_INTERFACE -p tcp \ -s $ANYWHERE $UNPRIVPORTS \ -d $IPADDR 22 -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $IPADDR 22 \ -d $ANYWHERE $UNPRIVPORTS -j ACCEPT ipchains -A input -i $EXTERNAL_INTERFACE -p tcp \ -s $ANYWHERE $SSH_PORTS \ -d $IPADDR 22 -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $IPADDR 22 \ -d $ANYWHERE $SSH_PORTS -j ACCEPT # SSH client (22) # --------------- ipchains -A input -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $ANYWHERE 22 \ -d $IPADDR $UNPRIVPORTS -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp \ -s $IPADDR $UNPRIVPORTS \ -d $ANYWHERE 22 -j ACCEPT ipchains -A input -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $ANYWHERE 22 \ -d $IPADDR $SSH_PORTS -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp \ -s $IPADDR $SSH_PORTS \ -d $ANYWHERE 22 -j ACCEPT # ------------------------------------------------------------------ # HTTP client (80) # ---------------- ipchains -A input -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $ANYWHERE 80 \ -d $IPADDR $UNPRIVPORTS -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp \ -s $IPADDR $UNPRIVPORTS \ -d $ANYWHERE 80 -j ACCEPT # ------------------------------------------------------------------ # HTTPS client (443) # ------------------ ipchains -A input -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $ANYWHERE 443 \ -d $IPADDR $UNPRIVPORTS -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp \ -s $IPADDR $UNPRIVPORTS \ -d $ANYWHERE 443 -j ACCEPT # ------------------------------------------------------------------ # POP client (110) # ---------------- ipchains -A input -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $POP_SERVER 110 \ -d $IPADDR $UNPRIVPORTS -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp \ -s $IPADDR $UNPRIVPORTS \ -d $POP_SERVER 110 -j ACCEPT # ------------------------------------------------------------------ # NNTP NEWS client (119) # ---------------------- ipchains -A input -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $NEWS_SERVER 119 \ -d $IPADDR $UNPRIVPORTS -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp \ -s $IPADDR $UNPRIVPORTS \ -d $NEWS_SERVER 119 -j ACCEPT # ------------------------------------------------------------------ # FINGER client (79) # ------------------ # ipchains -A input -i $EXTERNAL_INTERFACE -p tcp ! -y \ # -s $ANYWHERE 79 \ # -d $IPADDR $UNPRIVPORTS -j ACCEPT # ipchains -A output -i $EXTERNAL_INTERFACE -p tcp \ # -s $IPADDR $UNPRIVPORTS \ # -d $ANYWHERE 79 -j ACCEPT # ------------------------------------------------------------------ # SYSLOG client (514) # ----------------- # ipchains -A output -i $LOCAL_INTERFACE_1 -p udp \ # -s $IPADDR 514 \ # -d $SYSLOG_SERVER 514 -j ACCEPT # ------------------------------------------------------------------ # AUTH server (113) # ----------------- # Reject, rather than deny, the incoming auth port. (NET-3-HOWTO) ipchains -A input -i $EXTERNAL_INTERFACE -p tcp \ -s $ANYWHERE \ -d $IPADDR 113 -j REJECT # AUTH client (113) # ----------------- # ipchains -A input -i $EXTERNAL_INTERFACE -p tcp ! -y \ # -s $ANYWHERE 113 \ # -d $IPADDR $UNPRIVPORTS -j ACCEPT # ipchains -A output -i $EXTERNAL_INTERFACE -p tcp \ # -s $IPADDR $UNPRIVPORTS \ # -d $ANYWHERE 113 -j ACCEPT # ------------------------------------------------------------------ # SMTP client (25) # ---------------- ipchains -A input -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $ANYWHERE 25 \ -d $IPADDR $UNPRIVPORTS -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp \ -s $IPADDR $UNPRIVPORTS \ -d $ANYWHERE 25 -j ACCEPT # ------------------------------------------------------------------ # IRC client (6667) # ----------------- ipchains -A input -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $ANYWHERE 6667 \ -d $IPADDR $UNPRIVPORTS -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp \ -s $IPADDR $UNPRIVPORTS \ -d $ANYWHERE 6667 -j ACCEPT # ------------------------------------------------------------------ # ICQ client (4000) # ----------------- ipchains -A input -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $ANYWHERE 2000:4000 \ -d $IPADDR $UNPRIVPORTS -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp \ -s $IPADDR $UNPRIVPORTS \ -d $ANYWHERE 2000:4000 -j ACCEPT ipchains -A input -i $EXTERNAL_INTERFACE -p udp \ -s $ANYWHERE 4000 \ -d $IPADDR $UNPRIVPORTS -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p udp \ -s $IPADDR $UNPRIVPORTS \ -d $ANYWHERE 4000 -j ACCEPT # ------------------------------------------------------------------ # FTP client (20, 21) # ------------------- # outgoing request ipchains -A input -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $ANYWHERE 21 \ -d $IPADDR $UNPRIVPORTS -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp \ -s $IPADDR $UNPRIVPORTS \ -d $ANYWHERE 21 -j ACCEPT # NORMAL mode data channel ipchains -A input -i $EXTERNAL_INTERFACE -p tcp \ -s $ANYWHERE 20 \ -d $IPADDR $UNPRIVPORTS -j ACCEPT # NORMAL mode data channel responses ipchains -A output -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $IPADDR $UNPRIVPORTS \ -d $ANYWHERE 20 -j ACCEPT # PASSIVE mode data channel creation ipchains -A output -i $EXTERNAL_INTERFACE -p tcp \ -s $IPADDR $UNPRIVPORTS \ -d $ANYWHERE $UNPRIVPORTS -j ACCEPT # PASSIVE mode data channel responses ipchains -A input -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $ANYWHERE $UNPRIVPORTS \ -d $IPADDR $UNPRIVPORTS -j ACCEPT # ------------------------------------------------------------------ # RealAudio / QuickTime client # ---------------------------- ipchains -A input -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $ANYWHERE 554 \ -d $IPADDR $UNPRIVPORTS -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp \ -s $IPADDR $UNPRIVPORTS \ -d $ANYWHERE 554 -j ACCEPT # TCP is a more secure method: 7070:7071 ipchains -A input -i $EXTERNAL_INTERFACE -p tcp ! -y \ -s $ANYWHERE 7070:7071 \ -d $IPADDR $UNPRIVPORTS -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p tcp \ -s $IPADDR $UNPRIVPORTS \ -d $ANYWHERE 7070:7071 -j ACCEPT # UDP is the preferred method: 6970:6999 # For LAN machines, UDP requires the RealAudio masquerading module and # the ipmasqadm third-party software. ipchains -A input -i $EXTERNAL_INTERFACE -p udp \ -s $ANYWHERE $UNPRIVPORTS \ -d $IPADDR 6970:6999 -j ACCEPT ipchains -A output -i $EXTERNAL_INTERFACE -p udp \ -s $IPADDR $UNPRIVPORTS \ -d $ANYWHERE $UNPRIVPORTS -j ACCEPT # ------------------------------------------------------------------ # WHOIS client (43) # ----------------- # ipchains -A input -i $EXTERNAL_INTERFACE -p tcp ! -y \ # -s $ANYWHERE 43 \ # -d $IPADDR $UNPRIVPORTS -j ACCEPT # ipchains -A output -i $EXTERNAL_INTERFACE -p tcp \ # -s $IPADDR $UNPRIVPORTS \ # -d $ANYWHERE 43 -j ACCEPT # ------------------------------------------------------------------ # OUTGOING TRACEROUTE # ------------------- ipchains -A output -i $EXTERNAL_INTERFACE -p udp \ -s $IPADDR $TRACEROUTE_SRC_PORTS \ -d $ANYWHERE $TRACEROUTE_DEST_PORTS -j ACCEPT # ---------------------------------------------------------------------------- # Unlimited traffic within the local network. # All internal machines have access to the firewall machine. ipchains -A input -i $LOCAL_INTERFACE_1 -s $LOCALNET_1 -j ACCEPT ipchains -A output -i $LOCAL_INTERFACE_1 -d $LOCALNET_1 -j ACCEPT # ---------------------------------------------------------------------------- # FreeS/WAN IPSec VPN # ------------------- # If you are using the FreeSWAN IPSec VPN, you will need to fill in the # addresses of the gateways in the IPSECSG and the virtual interfaces for # FreeS/Wan IPSEC in the FREESWANVI parameters. Look at the beginning of # this firewall script rules file to set the parameters. # IPSECSG is a Space separated list of remote gateways. FREESWANVI is a # Space separated list of virtual interfaces for FreeS/Wan IPSEC # implementation. Only include those that are actually used. # Allow IPSEC protocol from remote gateways on external interface # IPSEC uses three main types of packet: # IKE uses the UDP protocol and port 500, # ESP use the protocol number 50, and # AH use the protocol number 51 # ipchains -A input -i $EXTERNAL_INTERFACE -p udp \ # -s $IPSECSG -j ACCEPT # ipchains -A output -i $EXTERNAL_INTERFACE -p udp \ # -d $IPSECSG -j ACCEPT # ipchains -A input -i $EXTERNAL_INTERFACE -p 50 \ # -s $IPSECSG -j ACCEPT # ipchains -A output -i $EXTERNAL_INTERFACE -p 50 \ # -d $IPSECSG -j ACCEPT # ipchains -A input -i $EXTERNAL_INTERFACE -p 51 \ # -s $IPSECSG -j ACCEPT # ipchains -A output -i $EXTERNAL_INTERFACE -p 51 \ # -d $IPSECSG -j ACCEPT # Allow all traffic to FreeS/WAN Virtual Interface # ipchains -A input -i $FREESWANVI \ # -s $ANYWHERE \ # -d $ANYWHERE -j ACCEPT # ipchains -A output -i $FREESWANVI \ # -s $ANYWHERE \ # -d $ANYWHERE -j ACCEPT # Forward anything from the FreeS/WAN virtual interface IPSEC tunnel # ipchains -A forward -i $FREESWANVI \ # -s $ANYWHERE \ # -d $ANYWHERE -j ACCEPT # Disable IP spoofing protection to allow IPSEC to work properly # echo 0 > /proc/sys/net/ipv4/conf/ipsec0/rp_filter # echo 0 > /proc/sys/net/ipv4/conf/eth0/rp_filter # ---------------------------------------------------------------------------- # Masquerade internal traffic. # All internal traffic is masqueraded externally. ipchains -A forward -i $EXTERNAL_INTERFACE -s $LOCALNET_1 -j MASQ # ---------------------------------------------------------------------------- # Enable logging for selected denied packets ipchains -A input -i $EXTERNAL_INTERFACE -p tcp \ -d $IPADDR -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -p udp \ -d $IPADDR $PRIVPORTS -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -p udp \ -d $IPADDR $UNPRIVPORTS -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -p icmp \ -s $ANYWHERE 5 -d $IPADDR -j DENY -l ipchains -A input -i $EXTERNAL_INTERFACE -p icmp \ -s $ANYWHERE 13:255 -d $IPADDR -j DENY -l # ---------------------------------------------------------------------------- ;; stop) echo -n "Shutting Firewalling Services: " # Remove all existing rules belonging to this filter ipchains -F # Delete all user-defined chain to this filter ipchains -X # Reset the default policy of the filter to accept. ipchains -P input ACCEPT ipchains -P output ACCEPT ipchains -P forward ACCEPT ;; status) status firewall ;; restart|reload) $0 stop $0 start ;; *) echo "Usage: firewall {start|stop|status|restart|reload}" exit 1 esac exit 0 Now, make this script executable and change its default permissions: [root@deep] /#chmod 700 /etc/rc.d/init.d/firewall [root@deep] /#chown 0.0 /etc/rc.d/init.d/firewall Create the symbolic rc.d links for your Firewall with the command: [root@deep] /#chkconfig --add firewall [root@deep] /#chkconfig --level 345 firewall on Now, your firewall rules are configured to use System V init -System V init is in charge of starting all the normal processes that need to run at boot time and it will be automatically started each time your server reboots. To manually stop the firewall on your system, use the following command: [root@deep] /# /etc/rc.d/init.d/firewall stop Shutting Firewalling Services: [ OK ] To manually start the firewall on your system, use the following command: [root@deep] /# /etc/rc.d/init.d/firewall start Starting Firewalling Services: [ OK ] ----------------------------------------------------------------------------- 12.4. Deny access to some address Sometimes you'll know an address that you would like to block from having any access at all to your server. You can do that by creating the rc.firewall.blocked file under /etc/rc.d/ directory and uncomment the following lines in your firewall rules scripts file: Edit your firewall scripts file vi /etc/rc.d/init.d/firewall and uncomment the following lines: if [ -f /etc/rc.d/rc.firewall.blocked ]; then . /etc/rc.d/rc.firewall.blocked fi Create the rc.firewall.blocked file touch /etc/rc.d/rc.firewall.blocked and add inside this file all the IP addresses that you want to block from having any access to your server at all: For example, I put the following IP addresses in this file: Example 12-1. rc.firewall.blocked 204.254.45.9 187.231.11.5 Further documentation, more details, there are several man pages you can read:   *  ipchains(8) - IP firewall administration   *  ipchains-restore(8) - restore IP firewall chains from stdin   *  ipchains-save(8) - save IP firewall chains to stdout ----------------------------------------------------------------------------- 12.5. IPCHAINS Administrative Tools The commands listed below are some tools that we use often, but many more exist, and you should check the man page and documentation for more details and information. The ipchains tool is used for the firewall administration of the Linux system. We can use it to set up a firewall rules file, as we are doing in this book. Once firewall rules have been created we can play with its many commands to maintain, and inspect its rules in the Linux kernel. To list all rules in the selected chain, use the command: [root@deep] /# ipchains -L This command will list all rules in the selected chain. If no chain is selected, all chains are listed. To list all input rules in the selected chain, use the command: [root@deep] /# ipchains -L input This command will list all input rules we have configured in the selected chain. To list all output rules in the selected chain, use the command: [root@deep] /# ipchains -L output This command will list all output rules we have configured in the selected chain. To list all forward rules in the selected chain, use the command: [root@deep] /# ipchains -L forward This command will list all forward rules in the selected chain. This of course works only if you have configured Masquerading on your server. for gateway servers in general. To list all masquerades rules in the selected chain, use the command: [root@deep] /# ipchains -ML This option allows viewing of the currently masqueraded connections. You must have configured Masquerading on your server for this command to work, once again, only for gateway servers. To list all rules in numeric output in the selected chain, use the command: [root@deep] /# ipchains -nL This command will list all rules in numeric output. All the IP addresses and port numbers will be printed in numeric format. 5. Software -Security Spoonbill The next Two parts will exclusively deal with the Software other than the one's which the Linux distribution, in our case Redhat Linux, may or may not provide as a part of its core distribution. In some cases it may be provided as an extra but may come as pre-compiled binary which may not exactly suit your purpose. Hence we have in most cases used source packages usually packed as tar gzipped -*.tar.gz or in some recent case in tar bzipped -*.tar.bz2 format. This gives us the maximum available choices to tweak, choose and delete the options within these Softwares. Just a word about the *.tar.gz and *.tar.bz2, the contents are same except that the compression used is different and the bz2 extention is smaller in size as compressed format. Table of Contents 13. Linux -The Compiler functionality 13.1. The necessary packages 13.2. Why choose tarballs? 13.3. Build, Install software on your system 14. Software -Security/Monitoring 14.1. sXid 14.2. Configure and Optimize sXid 14.3. Logcheck 14.4. Configure and Optimize Logcheck 14.5. PortSentry 14.6. Configure and Optimise Portsentry 14.7. Test fire your PortSentry ----------------------------------------------------------------------------- Chapter 13. Linux -The Compiler functionality We are, now at one of the most interesting point, here we will compile and install all the services that we wish to offer in our Linux server. Before we begin to explain how to compile and install server software with all the necessary securities and optimizations that we will need on our server, it is important to know the commands and programs we'll use often to do the job. First of all, we must ensure that we have the necessary packages needed to make compilations on our system. These packages must be installed on your server or you'll not be able to compile programs. ----------------------------------------------------------------------------- 13.1. The necessary packages The following are the necessary packages needed to be able to compile the other software programs on your system after recompilation of your kernel. This software is on your Red Hat Linux 6.1 or 6.2 Part 1 CD-ROM under RedHat/ RPMS directory if they are not already installed. [root@deep] /#mount /dev/cdrom /mnt/cdrom/ [root@deep] /#cd /mnt/cdrom/RedHat/RPMS/ Version 6.1 only autoconf-2.13-5.noarch.rpm ctags-3.2-1.i386.rpm m4-1.4-12.i386.rpm egcs-1.1.2-24.i386.rpm automake-1.4-5.noarch.rpm ElectricFence-2.1-1.i386.rpm dev86-0.14.9-1.i386.rpm flex-2.5.4a-7.i386.rpm bison-1.28-1.i386.rpm gdb-4.18-4.i386.rpm byacc-1.9-11.i386.rpm kernel-headers-2.2.12-20.i386.rpm cdecl-2.5-9.i386.rpm glibc-devel-2.1.2-11.i386.rpm cpp-1.1.2-24.i386.rpm make-3.77-6.i386.rpm cproto-4.6-2.i386.rpm patch-2.5-9.i386.rpm Version 6.2 only autoconf-2.13-5.noarch.rpm ctags-3.4-1.i386.rpm m4-1.4-12.i386.rpm egcs-1.1.2-30.i386.rpm automake-1.4-6.noarch.rpm ElectricFence-2.1-3.i386.rpm dev86-0.15.0-2.i386.rpm flex-2.5.4a-9.i386.rpm bison-1.28-2.i386.rpm gdb-4.18-11.i386.rpm byacc-1.9-12.i386.rpm kernel-headers-2.2.14-5.0.i386.rpm cdecl-2.5-10.i386.rpm glibc-devel-2.1.3-15.i386.rpm cpp-1.1.2-30.i386.rpm make-3.78.1-4.i386.rpm cproto-4.6-3.i386.rpm patch-2.5-10.i386.rpm Important : It is better to install the software described above all together if you don't want to receive dependency error messages during RPM install. If you have followed all the steps in Installation of your Linux Server, then all of these packages are already installed on your system and you don't need to reinstall them again. The RPM command to install a RPM package on your system is: [root@deep] /#rpm -Uvh foo-1.0-2.i386.rpm The RPM command to verify that a package is or is not installed on your system is: [root@deep] /#rpm -q foo Once again, after installation and compilation of all programs that you need on your server, its important to uninstall all sharp objects compilers, etc. describe above. This will protect your system from unauthorized users trying to compile programs on your server without authorization. Another thing to do is to move the rpm binary program to a safe place like a floppy disk for the same reasons listed above. Imagine somebody with dark intentions trying to compile programs on your server and realizing that compilers are not available. They will switch to import programs RPM on the server and install it with the RPM commands. Whoops, Heh! Heh! surprised! RPM commands are not available either. Of course, in future if you need to install new software on your server, all you have to do is to replace it from the floppy disk. To move the RPM binary in the floppy disk, use the command: [root@deep] /#mount /dev/fd0 /mnt/floppy/ [root@deep] /#mv /bin/rpm /mnt/floppy [root@deep] /#umount /mnt/floppy/ To put the RPM binary to its original directory, use the command: [root@deep] /#mount /dev/fd0 /mnt/floppy/ [root@deep] /#cp /mnt/floppy/rpm /bin/ [root@deep] /#umount /mnt/floppy/ +---------------------------------------------------------------------------+ | Warning | +---------------------------------------------------------------------------+ |Never uninstall the RPM program completely from your system or you will be | |unable to reinstall it again later since to install RPM or other software | |you need to have RPM commands available. | +---------------------------------------------------------------------------+ ----------------------------------------------------------------------------- 13.2. Why choose tarballs? All the programs in Red Hat distributions of Linux are provided as RPM files. An RPM file, also known, as a package, is a way of distributing software so that it can be easily installed, upgraded, queried, and deleted. However, in Unix world, the defacto-standard for package distribution continues to be by way of so-called tarballs. Tarballs are simply compressed files that can be readable and uncompressed with the tar utility. Installing from tar is usually significantly more tedious than using RPM. So why would we choose to do so? 1. Unfortunately, it takes a few weeks for developers and coders to get the latest version of a package converted to RPMs because many developers first release them as tarballs. 2. When developers and vendors release a new RPM, they include a lot of options that often are not necessary. Those organization and companies don't know what options you will need and what you will not, so they include the most used to fit the needs of everyone. 3. Often RPMs are not optimized for your specific processors; companies like Red Hat Linux build RPMs based on a standard PC. This permit their RPM packages to be installed on all sorts of computers since compiling programs for an i386 machine can fit on all systems. 4. Sometimes you download and install RPM, which other people around the world are building and make available for your purposes. This can pose conflicts in certain cases depending how this individual built the package, such as errors, security and all the other problems described above. ----------------------------------------------------------------------------- 13.2.1. Compiling software on your system A program is something a computer can execute. Originally, somebody wrote the source code in a programming language he/she could understand e.g., C, C++. The program source code also makes sense to a compiler that converts the instructions into a binary file suited to whatever processor is wanted e.g. a 386 or similar. A modern file format for these executable programs is Elf. The programmer compiles his source using the compiler and gets a result of some sort. It's not at all uncommon that early attempts fail to compile, or having compiled, fail to act as expected. Half of programming is tracking down and fixing these problems debugging. For the beginners there are more aspect and new words relating to compilation of a source code that you must know, these includes but are not limited to: The Multiple Files One-file programs are quite rare. Usually there are a number of files say *.c, *.cpp, etc. that are each compiled into object files *.o and then linked into an executable. The compiler is usually used to perform the linking and calls the ld program behind the scenes. The Makefiles The Makefiles are intended to aid you in building your program the same way each time. They also often help with speed. The make program uses dependencies in the Makefile to decide what parts of the program need to be recompiled. If you change one source file out of fifty you hope to get away with one compile and one link step, instead of starting from scratch. The Libraries Programs can be linked not only to object files *.o but also to libraries that are collections of object files. There are two forms of linking to libraries: static, where the code goes in the executable file, and dynamic, where the code is collected when the program starts to run. The Patches It was common before for executable files to be given corrections without recompiling them. Now this practice has died out; in modern days, people changes a small proportion of the whole source code, putting a change into a file called a patch. Where different versions of a program are required, small changes to code can be released this way, saving the trouble of having two large distributions. The Errors in Compilation and Linking Errors in compilation and linking are often typos, omissions, and misuse of the language. Check that the right includes files are used for the functions you are calling. Unreferenced symbols are the sign of an incomplete link step. Also checks if the necessary development libraries GLIBC or tools GCC, DEV86, AUTOMAKE, etc. are installed on your system. The Debugging Debugging is a large topic. It usually helps to have statements in the code that inform you of what is happening. To avoid drowning in output you might sometimes get them to print out only the first 3 passes in a loop. Checking that variables have passed correctly between modules often helps. Get familiar with your debugging tools. ----------------------------------------------------------------------------- 13.3. Build, Install software on your system You will see from the next chapter right through Part 6 that we use many different compile commands to build and install programs on the server. These commands are UNIX compatible and are used on all variant off *nix machines to compile and install software. The procedures to compile and install software tarballs on your server follow: 1. First of all, you must download the tarball from your trusted software archive site. Usually from the main site of the software you hope to install. 2. After downloading the tarball change to the /var/tmp/ directory, note that other paths are possible, as personal discretion and untar the archive by typing the commands as root as in the following example: Example 13-1. Using tar [root@deep] /#tar xzpf foo.tar.gz The above command will extract all files from the example foo.tar.gz compressed archive and will create a new directory for them with the name of this software from the path where you are executing the command. The x option tells tar to extract all files from the archive. The z option tells tar that the archive is compressed with gzip. The p option maintains the original and permissions the files had as the archive was created. The f option tells tar that the very next argument is the file name. Once the tarball has been decompressed into the appropriate directory, you will almost certainly find a README and/or an INSTALL file included with the newly decompressed files, with further instructions on how to build and compile the software package for use. You will need to enter commands similar to the following example: ./configure make make install The above commands; ./configure will configure the software to ensure your system has the necessary functionality and libraries to successfully compile the package make will compile all the source files into executable binaries. Finally, make install will install the binaries and any supporting files into the appropriate locations. Other specifics commands that you'll see in our book for compilation and installation procedure will be: make depend strip chown make depend command will build and make the necessary dependencies for different files. strip command will discard all symbols from the object files. This means that our binary file will be smaller in size, will improve a bit the performance hit to the program since there will be fewer lines to read by the system when it executes the binary. chown command will set the correct files owner and group permission for the binaries. Note : More commands when necessary will be explained in the concerned installation procedure. ----------------------------------------------------------------------------- 13.3.1. Edit files with the vi editor The vi program is a text editor that you can use to edit any text and particularly programs. During installation of software, the user will often have to edit text files like Makefiles or configuration files to make and fit they changes. The following are some of the most important keystroke commands to get around in vi. i To insert text before the cursor. a To append text after the cursor. dd To delete the current line. x To delete the current character. Esc To end the insert or append mode. u To undo the last command. Ctrl+f Scroll up one page. Ctrl+b Scroll down one page. /string Search forward for string. :f Display filename and current line nmber. :q Quit editor. :q! Quit editor without saving changes. :wq Save changes and exit editor. +---------------------------------------------------------------------------+ | Warning | +---------------------------------------------------------------------------+ |Before proceeding to read the rest of this book, it should be noted that | |the text assumes that certain files are placed in certain directories. | |Where they have been specified, the conventions we adopt here for locating | |these files are those of the Red Hat Linux distribution. If you are using a| |distribution of Linux or some other operating system that chooses to | |distribute these files in a different way, you should be careful when | |copying examples directly from the text. | +---------------------------------------------------------------------------+ ----------------------------------------------------------------------------- Chapter 14. Software -Security/Monitoring At this part of our book, all software-listed on chapter 14 through chapter 32 are optional and depends on what you want to install or do on your server. e.g., What kind of tasks will your server do, and for which part of your network Intranet/Internet? In other parts it may be important for you to replace the Telnet program with SSH for secure remote administration. Another interesting program is Tripwire that aids system administrators and users in monitoring a designated set of files for any changes. ----------------------------------------------------------------------------- 14.1. sXid SUID/SGID files can be a security hazard. To reduce the risks, we have previously already removed the s bits from root-owned programs that won't absolutely require such privilege, but future and existing files may be set with these s bits enabled without your notification. sXid is an all in one suid/sgid monitoring program designed to be run from cron on a regular basis. Basically it tracks any changes in your s[ug]id files and folders. If there are any new ones, ones that aren't set any more, or they have changed bits or other modes then it reports the changes in an easy to read format via email or on the command line. sXid will automate the task to find all SUID/SGID on your server and report them to you. Once installed you can forget it and it will do the job for you. These installation instructions assume the following:   *  Commands are Unix-compatible.   *  The source path is /var/tmp other paths are possible.   *  Installations were tested on Red Hat Linux 6.1 and 6.2.   *  All steps in the installation will happen in super-user account root.   *  sXid version number as of this writing is 4.0.1 Packages can be dowloaded from the sXid FTP Site:ftp://marcus.seva.net/pub/ sxid/ and You must be sure to download: sxid_4.0.1.tar.gz or whatever the latest version is. +---------------------------------------------------------------------------+ | Warning | +---------------------------------------------------------------------------+ |The instructions explained here in this book are applicable to the version | |number mentioned and you need to consult the README and/or INSTALL with in | |the tarball of the version you have downloaded for any changes, additions | |and deletions etc.. | +---------------------------------------------------------------------------+ Important : It is a good idea to make a list of files on the system before you install sXid, and one afterwards, and then compare them using diff to find out what file it placed where. Simply run find /* > sXid1 before and find /* > sXid2 after you install the software, and use diff sXid1 sXid2 > sXid-Installed to get a list of what changed. Decompress the tarball tar.gz. [root@deep] /#cp sxid_version.tar.gz /var/tmp/ [root@deep] /#cd /var/tmp [root@deep ] /tmp#tar xzpf sxid_version.tar.gz To Compile and Optimize move into the new sXid directory and type the following commands on your terminal: [root@deep tmp]#cd sxid-4.0.1 [root@deep ] /sxid-4.0.1#make install The above commands will configure the software to ensure your system has the necessary functionality and libraries to successfully compile the package, compile all source files into executable binaries, and then install the binaries and any supporting files into the appropriate locations. Please do a cleanup later: [root@deep] /#cd /var/tmp [root@deep ] /tmp#rm -rf sxid-version/ sxid_version_tar.gz The rm command as used above will remove all the source files we have used to compile and install sXid. It will also remove the sXid compressed archive from the /var/tmp directory. ----------------------------------------------------------------------------- 14.2. Configure and Optimize sXid Note : All the configuration files required for each software described in this book has been provided by us as a gzipped file, floppy.tgz for your convenience. This can be downloaded from this web address: http:// www.openna.com/books/floppy.tgz You can unpack this to any location on your local machine, say for example /tmp, assuming you have done this your directory structure will be /tmp/floppy. Within this floppy directory each configuration file has its own directory for respective software. For example sXid configuration file are organised like this: total 4 -rw-r--r-- 1 harrypotter harrypotter 1586 Jun 8 13:00 sxid.conf You can either cut and paste this directly if you are faithfully following our instructions from the begining or manually edit these to modify to your needs. This facility is there though as a convenience but please don't forget ultimately it will be your responsibility to check, verify, etc. before you use them whether modified or as it is. Tip : To run sXid, the following file from the floppy.tgz archive is required and must be created or copied to the appropriate directory on your server. Copy the sxid.conf file to the /etc/ directory. or alternatively you can copy and paste directly from this book to the concerned file. ----------------------------------------------------------------------------- 14.2.1. Configure the /etc/sxid.conf file The configuration file for sXid /etc/sxid.conf allows you to set options that modify the operation of the program. It is well commented and very basic. 1. Edit the sxid.conf file vi /etc/sxid.conf and set your needs: # Configuration file for sXid # Note that all directories must be absolute with no trailing /'s # Where to begin our file search SEARCH = "/" # Which subdirectories to exclude from searching EXCLUDE = "/proc /mnt /cdrom /floppy" # Who to send reports to EMAIL = "root" # Always send reports, even when there are no changes? ALWAYS_NOTIFY = "no" # Where to keep interim logs. This will rotate 'x' number of # times based on KEEP_LOGS below LOG_FILE = "/var/log/sxid.log" # How many logs to keep KEEP_LOGS = "5" # Rotate the logs even when there are no changes? ALWAYS_ROTATE = "no" # Directories where +s is forbidden (these are searched # even if not explicitly in SEARCH), EXCLUDE rules apply FORBIDDEN = "/home /tmp" # Remove (-s) files found in forbidden directories? ENFORCE = "yes" # This implies ALWAYS_NOTIFY. It will send a full list of # entries along with the changes LISTALL = "no" # Ignore entries for directories in these paths # (this means that only files will be recorded, you # can effectively ignore all directory entries by # setting this to "/"). The default is /home since # some systems have /home g+s. IGNORE_DIRS = "/home" # File that contains a list of (each on it's own line) # of other files that sxid should monitor. This is useful # for files that aren't +s, but relate to system # integrity (tcpd, inetd, apache...). # EXTRA_LIST = "/etc/sxid.list" # Mail program. This changes the default compiled in # mailer for reports. You only need this if you have changed # it's location and don't want to recompile sxid. # MAIL_PROG = "/usr/bin/mail" 2. Place an entry into root's crontabs to make sXid run as a cronjob. sXid will run from crond; basically it tracks any changes in your s[ug]id files and folders. If there are any new ones, ones that aren't set any more, or they have changed bits or other modes then it reports the changes. To add sxid in your cronjob you must edit the crontab and add the following line: To edit the crontab, use the command as root: [root@deep] /#crontab -e # Sample crontab entry to run every day at 4am 0 4 * * * /usr/bin/sxid Further documentation for more details, there are some man pages you can read sxid.conf(5) -configuration settings for sxid and sxid(1) - check for changes in s[ug]id files and directories sXid as administrative tool is meant to run as a cronjob. It must run once a day, but busy shell boxes may want to run it twice a day. You can also run this manually for spot-checking. To run sxid manually, use the command: [root@deep] /#sxid -k sXid Vers : 4.0.1 Check run : Wed Dec 29 12:40:32 1999 This host : mail.openna.com Spotcheck : /home/admin Excluding : /proc /mnt /cdrom /floppy Ignore Dirs: /home Forbidden : /home /tmp No changes found! This checks for changes by recursing the current working directory. Log files will not be rotated and no email sent. All output will go to stdout. These are the Installed files on your system by the program sXid. /etc/sxid.conf /usr/bin/sxid /usr/man/man1/sxid.1 /usr/man/man5/sxid.conf.5 ----------------------------------------------------------------------------- 14.3. Logcheck One important task in the security world is to regularly check the log files. Often the daily activities of an administrator don't allow him the time to do this task and this can bring about problems. +---------------------------------------------------------------------------+ | Extracted from [Logcheck abstract]: | | | | Auditing and logging system events is important! What is more important | | is that system administrators be aware of these events so they can | | prevent problems that will inevitably occur if you have a system | | connected to the Internet. Unfortunately for most Unices it doesn't | | matter how much you log activity if nobody ever checks the logs, which is | | often the case. This is where logcheck will help. Logcheck automates the | | auditing process and weeds out normal log information to give you a | | condensed look at problems and potential troublemakers mailed to wherever | | you please. Logcheck is a software package that is designed to | | automatically run and check system log files for security violations and | | unusual activity. Logcheck utilizes a program called logtail that | | remembers the last position it read from in a log file and uses this | | position on subsequent runs to process new information. | +---------------------------------------------------------------------------+ These installation instructions assume   *  Commands are Unix-compatible.   *  The source path is /var/tmp other paths are possible.   *  Installations were tested on Red Hat Linux 6.1 and 6.2.   *  All steps in the installation will happen in super-user account root.   *  Logcheck version number is 1.1.1 These are the packages available at Logcheck Homepage Site: http:// www.psionic.com/abacus/logcheck/, and you must be sure to download: logcheck-1.1.1.tar.gz available as of this writing. Important : Please do not forget to read the README and/or INSTALL with in the tarball you have downloaded if the version number is not the same as we have suggested and follow the instructions since there are chances of some changes either bythe way of additions or deletions are likely to be there. Before you uncompress and install from the tarballs it is a good idea to make a list of files on the system before you install Logcheck, and one afterwards, and then compare them using diff to find out what files were placed where. Simply run find /* > Logcheck1 before and find /* > Logcheck2 after you install the software, and use diff Logcheck1 Logcheck2 > Logcheck-Installed to get a list of what changed. To compile, you need to decompress the tarball (tar.gz). [root@deep] /#cp logcheck-version.tar.gz /var/tmp/ [root@deep] /#cd /var/tmp [root@deep ]/tmp#tar xzpf logcheck-version.tar.gz To Compile and Optimize you must modify the Makefile file of Logcheck to specify installation paths, compilation flags, and optimizations for your system. We must modify this file to be compliant with Red Hat's file system structure and install Logcheck script files under our PATH Environment variable. 1. Move into the new Logcheck directory and edit the Makefile, vi Makefile and change the following lines by type the following commands on your terminal: a. CC = cc To read: CC = egcs b. CFLAGS = -O To read: CFLAGS = -O9 -funroll-loops -ffast-math -malign-double -mcpu=pentiumpro -march=pentiumpro -fomit-frame-pointer -fno-exceptions c. INSTALLDIR = /usr/local/etc To read: INSTALLDIR = /etc/logcheck d. INSTALLDIR_BIN = /usr/local/bin To read: INSTALLDIR_BIN = /usr/bin e. INSTALLDIR_SH = /usr/local/etc To read: INSTALLDIR_SH = /usr/bin f. TMPDIR = /usr/local/etc/tmp To read: TMPDIR = /etc/logcheck/tmp g. The above changes will configure the software to use egcs compiler, optimization flags specific to our system, and locate all files related to Logcheck software to the destination target directories we have chosen to be compliant with the Red Hat file system structure. 2. Edit the Makefile file vi +67 Makefile and change the following line: @if [ ! -d $(TMPDIR) ]; then /bin/mkdir $(TMPDIR); fi To read: @if [ ! -d $(TMPDIR) ]; then /bin/mkdir -p $(TMPDIR); fi The above change -p will allow the installation program to create parent directories as needed. 3. Install Logcheck on your system. [root@deep ]/logcheck-1.1.1#make linux The above command will configure the software for the Linux operating system, compile all source files into executable binaries, and then install the binaries and any supporting files into the appropriate locations. Please don't forget to cleanup later: [root@deep] /#cd /var/tmp [root@deep ]/tmp#rm -rf logcheck-version/ logcheck-version_tar.gz The rm command as used above will remove all the source files we have used to compile and install Logcheck. It will also remove the Logcheck compressed archive from the /var/tmp directory. ----------------------------------------------------------------------------- 14.4. Configure and Optimize Logcheck You need to configure the /usr/bin/logcheck.sh script file, Since we are using an alternate path for the files i.e. not /usr/local/etc, we need to change the path entries for logcheck.hacking, logcheck.violations, logcheck.ignore, logcheck.violations.ignore, and logtail in the main logcheck.sh script. The script file for Logcheck /usr/bin/logcheck.sh allows you to set these options that modify the path entries and operation of the program. It is well commented and very basic. 1. Edit the logcheck.sh file vi /usr/bin/logcheck.sh and change the following: a. LOGTAIL=/usr/local/bin/logtail To read: LOGTAIL=/usr/bin/logtail b. TMPDIR=/usr/local/etc/tmp To read: TMPDIR=/etc/logcheck/tmp c. HACKING_FILE=/usr/local/etc/logcheck.hacking To read: HACKING_FILE=/etc/logcheck/logcheck.hacking d. VIOLATIONS_FILE=/usr/local/etc/logcheck.violations To read: VIOLATIONS_FILE=/etc/logcheck/logcheck.violations e. VIOLATIONS_IGNORE_FILE=/usr/local/etc/logcheck.violations.ignore To read: VIOLATIONS_IGNORE_FILE=/etc/logcheck/logcheck.violations.ignore f. IGNORE_FILE=/usr/local/etc/logcheck.ignore To read: IGNORE_FILE=/etc/logcheck/logcheck.ignore 2. After installing Logcheck, place an entry into root's crontabs to make Logcheck run as a cronjob, you should edit your local crontab file for root and set Logcheck to run once per hour recommended, although you can do it more frequently, or less frequently. To add Logcheck in your cronjob you must edit the crontab and add the following line as root: [root@deep] /#crontab -e # Hourly check Log files for security violations and unusual activity. 00 * * * * /usr/bin/logcheck.sh Note : Remember, Logcheck does not report anything via email if it has nothing useful to say. These are the files Installed by the program Logcheck on your sytem, for your future referance. /etc/logcheck /usr/bin/logcheck.sh /etc/logcheck/tmp /usr/bin/logtail /etc/logcheck/logcheck.hacking /var/log/messages.offset /etc/logcheck/logcheck.violations /var/log/secure.offset /etc/logcheck/logcheck.violations.ignore /var/log/maillog.offset /etc/logcheck/logcheck.ignore   ----------------------------------------------------------------------------- 14.5. PortSentry Firewalls help us to protect our network from unsolicited intrusions. Using them we can choose which ports we want to be open and which one's we dont. Information is kept private by your organization and responsibility of individuals asociated. Nobody from the outside implicitly knows this information, but attackers know as well as spammers, that for some kind of attacks you can use a special program to scan all the ports on a server to glean this valuable information i.e. what is open and what is not. +---------------------------------------------------------------------------+ | From the [PortSentry introduction]: | | | | A port scan is a symptom of a larger problem coming your way. It is often | | the pre-cursor for an attack and is a critical piece of information for | | properly defending your information resources. PortSentry is a program | | designed to detect and respond to port scans against a target host in | | real-time and has a number of options to detect port scans. When it finds | | one it can react in the following ways: | | | | A log indicating the incident is made via syslog(). | | The target host is automatically dropped into /etc/hosts.deny for TCP | | Wrappers. | | The local host is automatically re-configured to route all traffic to the | | target to a dead host to make the target system disappear. | | The local host is automatically re-configured to drop all packets from | | the target via a local packet filter. | | The purpose of this is to give an admin a heads up that their host is | | being probed. | +---------------------------------------------------------------------------+ These installation instructions assume:   *  Commands are Unix-compatible.   *  The source path is /var/tmp other paths are possible.   *  Installations were tested on Red Hat Linux 6.1 and 6.2.   *  All steps in the installation will happen in super-user account root.   *  Portsentry version number is 1.0 These are the Package(s) you have to download and Portsentry Homepage:http: //www.psionic.com/abacus/portsentry/ You must be sure to download: portsentry-1.0.tar.gz Important : Please do not forget to read the README and/or INSTALL with in the tarball you have downloaded if the version number is not the same as we have suggested and follow the instructions since there are chances of some changes either by the way of additions or deletions are likely to be there. When you install from Tarball(s), it is always better to make a list of files on the system before you install Portsentry, and one afterwards, and then compare them using diff to find out what file is placed where.A Simple step find /* > Portsentry1 before and find /* > Portsentry2 after you install the software, and use diff Portsentry1 Portsentry2 > PortSentry-Installed to get a list of what changed. You need to Compile so Decompress the tarball *.tar.gz. [root@deep] /#cp portsentry-version.tar.gz /var/tmp/ [root@deep] /#cd /var/tmp [root@deep ]/tmp#tar xzpf portsentry-version.tar.gz Optimize to compile 1. You must modify the Makefile file for Portsentry to specify installation paths, compilation flags, and optimizations for your system. We must also modify this file to be compliant with Red Hat file's system structure. Move into the new Portsentry directory and with the following commands on your terminal edit the Makefile file vi Makefile and change the following lines: a. CC = cc To read: CC = egcs b. CFLAGS = -O -Wall To read: CFLAGS = -O9 -funroll-loops -ffast-math -malign-double -mcpu=pentiumpro -march=pentiumpro -fomit-frame-pointer -fno-exceptions -Wall c. INSTALLDIR = /usr/local/psionic To read: INSTALLDIR = /usr/psionic d. The above changes will configure the software to use egcs compiler, optimization flags specific to our system, and locate all files related to Portsentry software to the target directories we have chosen. 2. Since we are using an alternate path for the files i.e. not /usr/local/ psionic, we need to change the path to the PortSentry configuration file in the main portsentry_config.h header file. Move into the new PortSentry directory and edit the portsentry_config.h file vi portsentry_config.h and change the following line: #define CONFIG_FILE "/usr/local/psionic/portsentry/portsentry.conf" To read: #define CONFIG_FILE "/usr/psionic/portsentry/portsentry.conf" 3. Step 3 Install Portsentry on your system. [root@deep ]/portsentry-1.0#make linux [root@deep ]/portsentry-1.0#make install The above commands will configure the software to the Linux operating system, compile, build, and then finally install files into the appropriate locations. Please do a cleanup later: [root@deep] /# cd /var/tmp [root@deep ]/tmp#rm -rf portsentry-version/ portsentry-version_tar.gz The rm command will remove all the source files we have used to compile and install PortSentry. It will also remove the PortSentry compressed archive from the /var/tmp directory. ----------------------------------------------------------------------------- 14.6. Configure and Optimise Portsentry You have to configure the the /usr/psionic/portsentry/portsentry.conf file which is the main configuration file for the PortSentry Software; you can specify which ports you want to listen to, which IP addresses are denied, monitor, ignore, disable automatic responses, and so on. For more information read the README.install file under the PortSentry source directory. Edit the portsentry.conf file, vi /usr/psionic/portsentry.conf and check/change the following options to fit your needs: # PortSentry Configuration # # $Id: portsentry.conf,v 1.13 1999/11/09 02:45:42 crowland Exp crowland $ # # IMPORTANT NOTE: You CAN NOT put spaces between your port arguments. # # The default ports will catch a large number of common probes # # All entries must be in quotes. ####################### # Port Configurations # ####################### # # # Some example port configs for classic and basic Stealth modes # # I like to always keep some ports at the "low" end of the spectrum. # This will detect a sequential port sweep really quickly and usually # these ports are not in use (i.e. tcpmux port 1) # # ** X-Windows Users **: If you are running X on your box, you need to be sure # you are not binding PortSentry to port 6000 (or port 2000 for OpenWindows users). # Doing so will prevent the X-client from starting properly. # # These port bindings are *ignored* for Advanced Stealth Scan Detection Mode. # # Un-comment these if you are really anal: #TCP_PORTS="1,7,9,11,15,70,79,80,109,110,111,119,138,139,143,512,513,514,515,540,635,1080,1524,2000,2001,4000,4001,5742,6000,6001,6667,12345,12346,20034,30303,32771,32772,32773,32774,31337,40421,40425,49724,54320" #UDP_PORTS="1,7,9,66,67,68,69,111,137,138,161,162,474,513,517,518,635,640,641,666,700,2049,32770,32771,32772,32773,32774,31337,54321" # # Use these if you just want to be aware: TCP_PORTS="1,11,15,79,111,119,143,540,635,1080,1524,2000,5742,6667,12345,12346,20034,31337,32771,32772,32773,32774,40421,49724,54320" UDP_PORTS="1,7,9,69,161,162,513,635,640,641,700,32770,32771,32772,32773,32774,31337,54321" # # Use these for just bare-bones #TCP_PORTS="1,11,15,110,111,143,540,635,1080,524,2000,12345,12346,20034,32771,32772,32773,32774,49724,54320" #UDP_PORTS="1,7,9,69,161,162,513,640,700,32770,32771,32772,32773,32774,31337,54321" ########################################### # Advanced Stealth Scan Detection Options # ########################################### # # This is the number of ports you want PortSentry to monitor in Advanced mode. # Any port *below* this number will be monitored. Right now it watches # everything below 1023. # # On many Linux systems you cannot bind above port 61000. This is because # these ports are used as part of IP masquerading. I don't recommend you # bind over this number of ports. Realistically: I DON'T RECOMMEND YOU MONITOR # OVER 1023 PORTS AS YOUR FALSE ALARM RATE WILL ALMOST CERTAINLY RISE. You've been # warned! Don't write me if you have have a problem because I'll only tell # you to RTFM and don't run above the first 1023 ports. # # ADVANCED_PORTS_TCP="1023" ADVANCED_PORTS_UDP="1023" # # This field tells PortSentry what ports (besides listening daemons) to # ignore. This is helpful for services like ident that services such # as FTP, SMTP, and wrappers look for but you may not run (and probably # *shouldn't* IMHO). # # By specifying ports here PortSentry will simply not respond to # incoming requests, in effect PortSentry treats them as if they are # actual bound daemons. The default ports are ones reported as # problematic false alarms and should probably be left alone for # all but the most isolated systems/networks. # # Default TCP ident and NetBIOS service ADVANCED_EXCLUDE_TCP="113,139" # Default UDP route (RIP), NetBIOS, bootp broadcasts. ADVANCED_EXCLUDE_UDP="520,138,137,67" ###################### # Configuration Files# ###################### # # Hosts to ignore IGNORE_FILE="/usr/psionic/portsentry/portsentry.ignore" # Hosts that have been denied (running history) HISTORY_FILE="/usr/psionic/portsentry/portsentry.history" # Hosts that have been denied this session only (temporary until next restart) BLOCKED_FILE="/usr/psionic/portsentry/portsentry.blocked" ################### # Response Options# ################### # Options to dispose of attacker. Each is an action that will # be run if an attack is detected. If you don't want a particular # option then comment it out and it will be skipped. # # The variable $TARGET$ will be substituted with the target attacking # host when an attack is detected. The variable $PORT$ will be substituted # with the port that was scanned. # ################## # Ignore Options # ################## # These options allow you to enable automatic response # options for UDP/TCP. This is useful if you just want # warnings for connections, but don't want to react for # a particular protocol (i.e. you want to block TCP, but # not UDP). To prevent a possible Denial of service attack # against UDP and stealth scan detection for TCP, you may # want to disable blocking, but leave the warning enabled. # I personally would wait for this to become a problem before # doing though as most attackers really aren't doing this. # The third option allows you to run just the external command # in case of a scan to have a pager script or such execute # but not drop the route. This may be useful for some admins # who want to block TCP, but only want pager/e-mail warnings # on UDP, etc. # # # 0 = Do not block UDP/TCP scans. # 1 = Block UDP/TCP scans. # 2 = Run external command only (KILL_RUN_CMD) BLOCK_UDP="1" BLOCK_TCP="1" ################### # Dropping Routes:# ################### # This command is used to drop the route or add the host into # a local filter table. # # The gateway (333.444.555.666) should ideally be a dead host on # the *local* subnet. On some hosts you can also point this at # localhost (127.0.0.1) and get the same effect. NOTE THAT # 333.444.555.66 WILL *NOT* WORK. YOU NEED TO CHANGE IT!! # # All KILL ROUTE OPTIONS ARE COMMENTED OUT INITIALLY. Make sure you # uncomment the correct line for your OS. If you OS is not listed # here and you have a route drop command that works then please # mail it to me so I can include it. ONLY ONE KILL_ROUTE OPTION # CAN BE USED AT A TIME SO DON'T UNCOMMENT MULTIPLE LINES. # # NOTE: The route commands are the least optimal way of blocking # and do not provide complete protection against UDP attacks and # will still generate alarms for both UDP and stealth scans. I # always recommend you use a packet filter because they are made # for this purpose. # # Generic #KILL_ROUTE="/sbin/route add $TARGET$ 333.444.555.666" # Generic Linux #KILL_ROUTE="/sbin/route add -host $TARGET$ gw 333.444.555.666" # Newer versions of Linux support the reject flag now. This # is cleaner than the above option. KILL_ROUTE="/sbin/route add -host $TARGET$ reject" # Generic BSD (BSDI, OpenBSD, NetBSD, FreeBSD) #KILL_ROUTE="/sbin/route add $TARGET$ 333.444.555.666" # Generic Sun #KILL_ROUTE="/usr/sbin/route add $TARGET$ 333.444.555.666 1" # NEXTSTEP #KILL_ROUTE="/usr/etc/route add $TARGET$ 127.0.0.1 1" # FreeBSD (Not well tested.) #KILL_ROUTE="route add -net $TARGET$ -netmask 255.255.255.255 127.0.0.1 -blackhole" # Digital UNIX 4.0D (OSF/1 / Compaq Tru64 UNIX) #KILL_ROUTE="/sbin/route add -host -blackhole $TARGET$ 127.0.0.1" # Generic HP-UX #KILL_ROUTE="/usr/sbin/route add net $TARGET$ netmask 255.255.255.0 127.0.0.1" ## # Using a packet filter is the preferred method. The below lines # work well on many OS's. Remember, you can only uncomment *one* # KILL_ROUTE option. ## ############### # TCP Wrappers# ############### # This text will be dropped into the hosts.deny file for wrappers # to use. There are two formats for TCP wrappers: # # Format One: Old Style - The default when extended host processing # options are not enabled. # KILL_HOSTS_DENY="ALL: $TARGET$" # # Format Two: New Style - The format used when extended option # processing is enabled. You can drop in extended processing # options, but be sure you escape all '%' symbols with a backslash # to prevent problems writing out (i.e. \%c \%h ) # #KILL_HOSTS_DENY="ALL: $TARGET$ : DENY" ################### # External Command# ################### # This is a command that is run when a host connects, it can be whatever # you want it to be (pager, etc.). This command is executed before the # route is dropped. I NEVER RECOMMEND YOU PUT IN RETALIATORY ACTIONS # AGAINST THE HOST SCANNING YOU. TCP/IP is an *unauthenticated protocol* # and people can make scans appear out of thin air. The only time it # is reasonably safe (and I *never* think it is reasonable) to run # reverse probe scripts is when using the "classic" -tcp mode. This # mode requires a full connect and is very hard to spoof. # #KILL_RUN_CMD="/some/path/here/script $TARGET$ $PORT$" ##################### # Scan trigger value# ##################### # Enter in the number of port connects you will allow before an # alarm is given. The default is 0 which will react immediately. # A value of 1 or 2 will reduce false alarms. Anything higher is # probably not necessary. This value must always be specified, but # generally can be left at 0. # # NOTE: If you are using the advanced detection option you need to # be careful that you don't make a hair trigger situation. Because # Advanced mode will react for *any* host connecting to a non-used # below your specified range, you have the opportunity to really # break things. (i.e someone innocently tries to connect to you via # SSL [TCP port 443] and you immediately block them). Some of you # may even want this though. Just be careful. # SCAN_TRIGGER="0" ###################### # Port Banner Section# ###################### # # Enter text in here you want displayed to a person tripping the PortSentry. # I *don't* recommend taunting the person as this will aggravate them. # Leave this commented out to disable the feature # # Stealth scan detection modes don't use this feature # PORT_BANNER="** UNAUTHORIZED ACCESS PROHIBITED *** YOUR CONNECTION ATTEMPT HAS BEEN LOGGED. GO AWAY." # EOF Now, we must check/change its default permission for security reasons: [root@deep] /#chmod 600 /usr/psionic/portsentry/portsentry.conf You need to configure the /usr/psionic/portsentry/portsentry.ignore file, where you add in any host you want to have ignored if it connects to a tripwired port. This should always contain at least the localhost 127.0.0.1 and the IP's of the local interfaces lo. It is not recommend that you put in every IP on your network. Edit the portsentry.ignore file, vi /usr/psionic/ portsentry.ignore and add in any host you want to have ignored if it connects to a tripwired port: # Put hosts in here you never want blocked. This includes the IP addresses # of all local interfaces on the protected host (i.e virtual host, mult-home) # Keep 127.0.0.1 and 0.0.0.0 to keep people from playing games. 127.0.0.1 0.0.0.0 Now, we must check/change its default permission for security reasons: [root@deep] /#chmod 600 /usr/psionic/portsentry/portsentry.ignore ----------------------------------------------------------------------------- 14.7. Test fire your PortSentry The PortSentry program can be configured in six different modes of operation, but be aware that only one protocol mode type can be started at a time. To be more accurate, you can start one TCP mode and one UDP mode, so two TCP modes and one UDP modes, for example, doesn't work. The available modes are: portsentry -tcp basic port-bound TCP mode portsentry -udp basic port-bound UDP mode portsentry -stcp Stealth TCP scan detection portsentry -atcp Advanced TCP stealth scan detection portsentry -sudp Stealth UDP scan detection portsentry -audp Advanced Stealth UDP scan detection In my case I prefer to start TCP in Advanced TCP stealth scan detection protocol mode and UDP in Stealth UDP scan detection protocol mode. For information about the other protocol modes, please refer to the README.install and README.stealth file under the PortSentry source directory. For TCP mode I choose: -atcp Advanced TCP stealth scan detection mode With the Advanced TCP stealth scan detection mode -atcp protocol mode type, PortSentry will first check to see what ports you have running on your server, then remove these ports from monitoring and will begin watching the remaining ports. This is very powerful and reacts exceedingly quickly for port scanners. It also uses very little CPU time. For UDP mode I choose: -sudp Stealth UDP scan detection mode With the Stealth UDP scan detection mode -sudp protocol mode type, the UDP ports will be listed and then monitored. To start PortSentry in the two modes selected above, use the commands: [root@deep] /# /usr/psionic/portsentry/portsentry -atcp [root@deep] /# /usr/psionic/portsentry/portsentry -sudp Tip : You can add the above lines to your /etc/rc.d/rc.local script file and PortSentry software will be automatically started if you reboot your system. These are the files Installed by Portsentry on your system: /usr/psionic /usr/psionic/portsentry /usr/psionic/portsentry/portsentry.conf /usr/psionic/portsentry/portsentry.ignore /usr/psionic/portsentry/portsentry 6. Software -Networking Two ducks! Linux being a product of the net revolution is a natural choice for a web server, mail server, a file and print server; if it is a part of your intranet environement, among various other roles it can perform superbly well. In this part we take a look at various avatars it can assume and serve your organisation for a long time to come. All distributions of linux whether be it RedHat or SuSe do provide in binary format tools/ software for your linux to act as a Web server or a Mail server to mention a few, but the amount of advancements which happen in linux world are beyond the grasp of these companies for it to catch up. The situation is if something can be achieved, it will be done in shortest possible time hence we have used always source tarballs downloaded from the respective websites of the software(s) used as example in this book. This affords us the capability to configure, choose and optimise according to our needs. This part attempts to highlight the capablities of linux to act as a full fledged Web server, Mail server, a file and print server, as a B2B e-commerce point where the need of the hour is secure environement, etc. Enjoy! Table of Contents 15. Software -Securities 15.1. OpenSSH 15.2. Configure and optimise Openssh 15.3. Configure the /etc/ssh/ssh_config file 15.4. Configure the /etc/ssh/sshd_config file 15.5. Configure OpenSSH to use TCP-Wrappers/inetd super server 15.6. OpenSSH Per-User Configuration 15.7. OpenSSH Users Tools 15.8. Installed files 16. Software -Securties(commercial) 16.1. Linux SSH2 Client/Server 16.2. Configure and Optimise SSH2 16.3. Configure the /etc/ssh2/ssh2_config file 16.4. Configure the /etc/ssh2/sshd2_config file 16.5. Configure sshd2 to use tcp-wrappers/inetd super server 16.6. Configuration of the /etc/pam.d/ssh file 16.7. Ssh2 Per-User Configuration 16.8. SSH2 Users Tools 16.9. Installed files 17. Software -Securities/System Integrity 17.1. Linux Tripwire 2.2.1 17.2. Configure the /var/tmp/install.cfg file 17.3. Configuration files 17.4. Configure the /usr/TSS/policy/twpol.txt file 17.5. Securing Tripwire for Linux 17.6. Integrity or Interactive Check Mode 17.7. Installed files 18. Linux Tripwire ASR 1.3.1 18.1. Install, Compile and Optimize 18.2. Configurations 18.3. Configure the /etc/tw.config file 18.4. Configure the /etc/cron.daily/tripwire.verify script 18.5. Tripwire in Interactive Checking Mode 18.6. Run Tripwire in Database Update Mode 19. Software -Securities/Management & Limitation 19.1. Linux GnuPG 19.2. Often used Commands 19.3. Importing keys 19.4. Encrypt and decrypt 20. Set Limits using Qouta 20.1. Qouta 20.2. Create of the quota.user and quota.group 20.3. edquota 20.4. Assign quota for a particular group 20.5. Often used Commands 21. Software -Networking 21.1. Linux DNS and BIND Server 21.2. Configure 21.3. Caching-only name Server 21.4. Primary master name Server 21.5. Secondary slave name Server 21.6. Run ISC BIND/DNS in a chroot jail 21.7. The syslog daemon 21.8. Clean-up and Test the new chrooted jail 21.9. DNS Administrative Tools 21.10. DNS Users Tools 21.11. Installed files 22. Software -Server/Mail Network 22.1. Linux Sendmail Server 22.2. Compile and optimize 22.3. Configurations 22.4. The /etc/sendmail.mc file /Central Mail Hub 22.5. Build and Tweak Sendmail 22.6. The /etc/mail/access and access.db files 22.7. The /etc/mail/aliases and aliases.db files 22.8. The /etc/mail/local-host-names file 22.9. The /etc/rc.d/init.d/sendmail script file 22.10. Secure Sendmail using smrsh 22.11. The /etc/mail/aliases file 22.12. Limit queue processing to root 22.13. Sendmail Administrative Tools 22.14. Installed files: Sendmail -Central Mail Hub 22.15. Installed files: Sendmail -Local server/client 23. Linux IMAP & POP Server 23.1. Configure and Compile 23.2. Configure to tweak 23.3. Enable IMAP or POP via the tcp-wrappers inetd super server 23.4. Installed files 24. Software -Networking/Encryption 24.1. Linux OPENSSL Server 24.2. Compile and Optimize 24.3. Configure OpenSSL to optimise 24.4. The /etc/ssl/openssl.cnf file 24.5. Create the /usr/bin/sign.sh program file 24.6. Commands -often used 24.7. Securing OpenSSL 24.8. Installed files 25. Linux FreeS/WAN VPN 25.1. IPSEC/VPN -FreeS/WAN 25.2. Compile, insert FreeS/WAN into the kernel 25.3. Reconfigure and install the kernel with FreeS/WAN VPN support 25.4. Configure to optimise 25.5. Automatic or Manual Key connections 25.6. The /etc/ipsec.conf file 25.7. The /etc/ipsec.secrets file 25.8. Configure RSA private keys secrets 25.9. Required network setup for IPSec 25.10. Testing the installation 25.11. Further documentation 25.12. Installed files 26. Linux OpenLDAP Server 26.1. Compile ans Install 26.2. Compile and Optimize 26.3. Configurations 26.4. Configure the /etc/ldap/slapd.conf file 26.5. Configure the /etc/rc.d/init.d/ldap script file 26.6. Securing OpenLDAP 26.7. OpenLDAP Creation and Maintenance Tools 26.8. Create the LDMB backend database on-line 26.9. OpenLDAP Users Tools 26.10. Installed files 27. Linux PostgreSQL Database Server 27.1. Install PostgreSQL 27.2. Compile and Optimize 27.3. Database installation using superuser account 27.4. Configuration files 27.5. Configure the /etc/rc.d/init.d/postgresql script file 27.6. Commands often used 27.7. Installed files 28. Software -Server/Proxy Network 28.1. Linux Squid Proxy Server 28.2. Configure and Optimize 28.3. Improve performance Using GNU malloc library 28.4. Compile and Optimize 28.5. Configurations 28.6. Configure the /etc/squid/squid.conf file -in httpd-accelerator mode 28.7. Configure of the /etc/squid/squid.conf file -/proxy-caching mode 28.8. Configure the /etc/rc.d/init.d/squid script file -/all configurations 28.9. Configure the /etc/logrotate.d/squid file 28.10. Optimizing Squid 28.11. Netscape Proxies Configuration 28.12. Installed files 29. Software -Network Server, web/Apache 29.1. Linux MM Shared Memory Library 29.2. Compile 29.3. Linux Apache Web Server 29.4. Compile and Optimize 29.5. Configure and apply PHP4 to Apache source 29.6. Apply mod_perl to Apache source tree 29.7. Install Apache 29.8. Post install Configuration 29.9. Configure the /etc/httpd/conf/httpd.conf file 29.10. Configure the /etc/logrotate.d/apache file 29.11. Configure the /etc/rc.d/init.d/httpd script file 29.12. PHP4 server-side scripting 29.13. Perl module Devel::Symdump 29.14. CGI.pm Perl library 29.15. Securing Apache 29.16. users authentication with .dbmpasswd password file 29.17. Apache in a chroot jail 29.18. Apache to use shared libraries 29.19. The /chroot/etc directory 29.20. Test the new chrooted jail 29.21. Configure the new /etc/logrotate.d/apache file 29.22. Optimizing Apache 29.23. Installed files for Apache Web Server 29.24. Installed files /PHP4 29.25. Installed files by mod_perl 30. Optional component to install with Apache 30.1. Linux Webalizer 30.2. Compile 30.3. Configure the /etc/webalizer.conf file 30.4. Make Apache aware of Webalizer output directory 30.5. Run Webalizer automatically with a cron job 30.6. Linux FAQ-O-Matic 30.7. Compile and install FAQ-O-Matic 30.8. Make Apache aware Faq-O-Matic file's location 30.9. Configure your FAQ-O-Matic 30.10. Installed files 30.11. Linux Webmail IMP 30.12. Set up PHPLib 30.13. Compile to install Webmail IMP 30.14. Configure and create Webmail IMP SQL database 30.15. Configure your php.ini from PHP4 30.16. Configure Webmail IMP via your web browser 31. Software -Server/File Sharing-Network 31.1. Linux Samba Server 31.2. Configure Samba 31.3. Compile and optimize 31.4. Configurations 31.5. Configuration of the /etc/smb.conf file 31.6. Configure the /etc/lmhosts file 31.7. Encrypted Samba password file for clients 31.8. Optimizing Samba 31.9. Tuning the buffermem 31.10. Further documentation 31.11. Samba Administrative Tools 31.12. The /etc/rc.d/init.d/smb script file 31.13. Installed files 32. Linux FTP Server 32.1. chroot'd Guest FTP access 32.2. Setup an FTP user account minus shells 32.3. Setup a chroot user environment 32.4. Configurations 32.5. Configure the /etc/ftphosts file 32.6. Configure the /etc/ftpconversions file 32.7. Configure the /etc/logrotate.d/ftpd file 32.8. FTP Administrative Tools 32.9. Securing FTP 32.10. The special file .notar 32.11. Installed files ----------------------------------------------------------------------------- Chapter 15. Software -Securities As illustrated in Installation of your Linux Server, many network services including, but not limited, to telnet, rsh, rlogin, or rexec are vulnerable to electronic eavesdropping. As a consequence, anyone who has access to any machine connected to the network can listen in on their communication and get your password, as well as any other private information that goes over the network in plain text. Currently the Telnet program is indispensable for daily administration task, but is insecure since it transmits your password in plain text over the network and allows any listener to thereby use your account to do anything he likes. To solve this problem we must find another way, or program, to replace it. Fortunately OpenSSH is a truly seamless and secure replacement of old, insecure and obsolete remote login programs such as telnet, rlogin, rsh, rdist, or rcp. ----------------------------------------------------------------------------- 15.1. OpenSSH +---------------------------------------------------------------------------+ | The official [OpenSSH README] file says: | | | | Ssh Secure Shell is a program to log into another computer over a | | network, to execute commands in a remote machine, and to move files from | | one machine to another. It provides strong authentication and secure | | communications over insecure channels. It is intended as a replacement | | for rlogin, rsh, rcp, and rdist. | +---------------------------------------------------------------------------+ In our configuration we have configured OpenSSH to support tcp-wrappers; the inetd super server, to improve the security of this already secure program and to avoid always running its daemon in the background of the server. This way, the program will run only when client connections arrive and will redirect them through the TCP-WRAPPERS daemon for authentication and authorization before allowing the connection in the server. OpenSSH is a free replacement and improvement of SSH1 with all patent-encumbered algorithms removed to external libraries, all known security bugs fixed, new features reintroduced and many other clean-ups. It is recommended that you use OpenSSH free and security bug fixed instead of SSH1 free, buggy, and old or SSH2 that was originally free but now under a commercial license. For peoples that use SSH2 from Datafellows Company, we'll provide in this book both versions, beginning with OpenSSH, since it is the new SSH program which everyone, we suggest, must move to in the future. These installation instructions assume:   *  Commands are Unix-compatible.   *  The source path is /var/tmp -other paths are possible.   *  Installations were tested on Red Hat Linux 6.1 and 6.2.   *  All steps in the installation will happen in super-user account root.   *  OpenSSH version number is 1.2.3 These are the Packages you can download from OpenSSH Homepage:http:// www.openssh.com and be sure to download: openssh-1.2.3.tar.gz as of this writing There are some Prerequisites you need to take care of before installing OpenSSH since it requires that the zlib-devel package, which contains the header files and libraries needed to develop programs that use the zlib compression and decompression library, be already installed on your system. If this is not the case, you must install it from your Red Hat Linux 6.1 or 6.2 CD-ROM. To verify that the zlib-devel package is installed on your Linux system, use the following command: [root@deep] /#rpm -qi zlib-devel package zlib-devel is not installed To install the zlib-devel package on your Linux system, use the following command: [root@deep] /#mount /dev/cdrom /mnt/cdrom/ [root@deep] /#cd /mnt/cdrom/RedHat/RPMS/ [root@deep ]/RPMS#rpm -Uvh zlib-devel-version.i386.rpm gd ################################################## [root@deep ]/RPMS#rpm -Uvh gd-devel-version.i386.rpm zlib-devel ################################################## [root@deep ]/RPMS# cd /; umount /mnt/cdrom/ Important : OpenSSL, which enables support for SSL functionality, must already be installed on your system to be able to use the OpenSSH software.For more information on OpenSSL server, see its related chapter in this book. Even if you don't need to use OpenSSL software to create or hold encrypted key files, it's important to note that OpenSSH program require its libraries files to be able to work properly on your system. you need to decompress and unpack the Tarballs but it is a good idea to make a list of files on the system before you install OpenSSH, and one afterwards, and then compare them using diff to find out what files it placed where. Simply run find/* > OpenSSH1 before and find/* > OpenSSH2 after you install the software, and use diff OpenSSH1 OpenSSH2 > OpenSSH-Installed to get a list of what changed. To Compile,Decompress the tarball tar.gz and: [root@deep] /#cp openssh-version.tar.gz /var/tmp [root@deep] /#cd /var/tmp [root@deep ]/tmp#tar xzpf openssh-version.tar.gz You need to Compile and Optimize: 1. Move into the new OpenSSH directory and type the following commands on your terminal: CC="egcs" \ CFLAGS="-O9 -funroll-loops -ffast-math -malign-double -mcpu=pentiumpro -march=pentiumpro -fomit-frame-pointer -fno-exceptions" \ ./configure \ --prefix=/usr \ --sysconfdir=/etc/ssh \ --with-tcp-wrappers \ --with-ipv4-default \ --with-ssl-dir=/usr/include/openssl This tells OpenSSH to set itself up for this particular hardware setup with: - Compiled-in libwrap and enabled TCP Wrappers /etc/hosts.allow|deny support. - Disabled long delays in name resolution under Linux/glibc-2.1.2 to improve connection time. - Specified locations of OpenSSL libraries required by OpenSSH program to work. 2. Now, we must compile and install OpenSSH on the Server: [root@deep ]/openssh-1.2.3#make [root@deep ]/openssh-1.2.3#make install [root@deep ]/openssh-1.2.3#make host-key [root@deep ]/openssh-1.2.3#install -m644 contrib/redhat/sshd.pam /etc/pam.d/sshd make command will compile all source files into executable binaries, make install will install the binaries and any supporting files into the appropriate locations. make host-key command will generate a host key. install command will install the PAM support for Red Hat Linux, which is now more functional than the popular packages of commercial ssh-1.2.x. 3. please do a Cleanup later: [root@deep] /#cd /var/tmp [root@deep ]/tmp#rm -rf openssh-version/ openssh-version.tar.gz The rm command as used above will remove all the source files we have used to compile and install OpenSSH. It will also remove the OpenSSH compressed archive from the /var/tmp directory. ----------------------------------------------------------------------------- 15.2. Configure and optimise Openssh Note : All the configuration files required for each software described in this book has been provided by us as a gzipped file, floppy.tgz for your convenience. This can be downloaded from this web address: http:// www.openna.com/books/floppy.tgz You can unpack this to any location on your local machine, say for example /tmp, assuming you have done this your directory structure will be /tmp/floppy. Within this floppy directory each configuration file has its own directory for respective software. For example Openssh configuration file are organised like this: total 16 -rw-r--r-- 1 harrypotter harrypotter 275 Jun 8 13:00 Compile-OpenSSH drwxr-xr-x 2 harrypotter harrypotter 4096 Jun 8 13:00 pam.d/ -rw-r--r-- 1 harrypotter harrypotter 372 Jun 8 13:00 ssh_config -rw-r--r-- 1 harrypotter harrypotter 467 Jun 8 13:00 sshd_config You can either cut and paste this directly if you are faithfully following our instructions from the begining or manually edit these to modify to your needs. This facility is there though as a convenience but please don't forget ultimately it will be your responsibility to check, verify, etc. before you use them whether modified or as it is. To run OpenSSH Client/Server, the following files are required and must be created or copied to the appropriate directories on your server.   *  Copy the ssh_config file to the /etc/ssh/ directory.   *  Copy the sshd_config file to the /etc/ssh/ directory.   *  Copy the sshd file to the /etc/pam.d/ directory. Tip : You can obtain the configuration files listed in the next sections on our floppy.tgz archive. Copy the following files from the decompressed floppy.tgz archive to the appropriate places, or copy them directly from this book to the concerned file. ----------------------------------------------------------------------------- 15.3. Configure the /etc/ssh/ssh_config file The /etc/ssh/ssh_config file is the system-wide configuration file for OpenSSH which allows you to set options that modify the operation of the client programs. The file contains keyword-value pairs, one per line, with keywords being case insensitive. Here are the most important keywords to configure your ssh for top security; a complete listing and/or special requirements are available in the man page for ssh(1). Edit the ssh_config file, vi /etc/ssh/ssh_config and add/or change, if necessary the following parameters: # Site-wide defaults for various options Host * ForwardAgent no ForwardX11 no RhostsAuthentication no RhostsRSAAuthentication no RSAAuthentication yes PasswordAuthentication yes FallBackToRsh no UseRsh no BatchMode no CheckHostIP yes StrictHostKeyChecking no IdentityFile ~/.ssh/identity Port 22 Cipher blowfish EscapeChar ~ This tells ssh_config file to set itself up for this particular configuration setup with: Host * The option Host restricts all forwarded declarations and options in the configuration file to be only for those hosts that match one of the patterns given after the keyword. The pattern * means for all hosts up to the next Host keyword. With this option you can set different declarations for different hosts in the same ssh_config file. ForwardAgent no The option ForwardAgent specifies which connection authentication agent if any should be forwarded to the remote machine. ForwardX11 no The option ForwardX11 is for people that use the Xwindow GUI and want to automatically redirect X11 sessions to the remote machine. Since we setup a server and don't have GUI installed on it, we can safely turn this option off. RhostsAuthentication no The option RhostsAuthentication specifies whether we can try to use rhosts based authentication. Because rhosts authentication is insecure you shouldn't use this option. RhostsRSAAuthentication no The option RhostsRSAAuthentication specifies whether or not to try rhosts authentication in concert with RSA host authentication. RSAAuthentication yes The option RSAAuthentication specifies whether to try RSA authentication. This option must be set to yes for better security on your sessions. RSA uses public and private keys pair created with the ssh-keygen1utility for authentication purposes. PasswordAuthentication yes The option PasswordAuthentication specifies whether we should use password-based authentication. For strong security, this option must always be set to yes. FallBackToRsh no The option FallBackToRsh specifies that if a connection with ssh daemon fails rsh should automatically be used instead. Recalling that rsh service is insecure, this option must always be set to no. UseRsh no The option UseRsh specifies that rlogin/rsh services should be used on this host. As with the FallBackToRsh option, it must be set to no for obvious reasons. BatchMode no The option BatchMode specifies whether a username and password querying on connect will be disabled. This option is useful when you create scripts and dont want to supply the password. e.g. Scripts that use the scp command to make backups over the network. CheckHostIP yes The option CheckHostIP specifies whether or not ssh will additionally check the host IP address that connect to the server to detect DNS spoofing. It's recommended that you set this option to yes. StrictHostKeyChecking no The option StrictHostKeyChecking specifies whether or not ssh will automatically add new host keys to the $HOME/.ssh/known_hosts file, or never automatically add new host keys to the host file. This option, when set to yes, provides maximum protection against Trojan horse attacks. One interesting procedure with this option is to set it to no at the beginning, allow ssh to add automatically all common hosts to the host file as they are connected to, and then return to set it to yes to take advantage of this feature. IdentityFile ~/.ssh/identity The option IdentityFile specifies an alternate RSA authentication identity file to read. Also, multiple identity files may be specified in the configuration file ssh_config. Port 22 The option Port specifies on which port number ssh connects to on the remote host. The default port is 22. Cipher blowfish The option Cipher specifies what cipher should be used for encrypting sessios. The blowfish use 64-bit blocks and keys of up to 448 bits. EscapeChar ~ The option EscapeChar specifies the session escape character for suspension. ----------------------------------------------------------------------------- 15.4. Configure the /etc/ssh/sshd_config file The /etc/ssh/sshd_config file is the system-wide configuration file for OpenSSH which allows you to set options that modify the operation of the daemon. This file contains keyword-value pairs, one per line, with keywords being case insensitive. Here are the most important keywords to configure your sshd for top security; a complete listing and/or special requirements are available in the man page for sshd(8). Edit the sshd_config file, vi /etc/ssh/sshd_config and add/or change, if necessary, the following parameters: # This is ssh server systemwide configuration file. Port 22 ListenAddress 192.168.1.1 HostKey /etc/ssh/ssh_host_key ServerKeyBits 1024 LoginGraceTime 600 KeyRegenerationInterval 3600 PermitRootLogin no IgnoreRhosts yes IgnoreUserKnownHosts yes StrictModes yes X11Forwarding no PrintMotd yes SyslogFacility AUTH LogLevel INFO RhostsAuthentication no RhostsRSAAuthentication no RSAAuthentication yes PasswordAuthentication yes PermitEmptyPasswords no AllowUsers admin This tells sshd_config file to set itself up for this particular configuration setup with: Port 22 The option Port specifies on which port number ssh daemon listens for incoming connections. The default port is 22. ListenAddress 192.168.1.1 The option ListenAddress specifies the IP address of the interface network on which the ssh daemon server socket is bind. The default is 0.0.0.0; to improve security you may specify only the required ones to limit possible addresses. HostKey /etc/ssh/ssh_host_key The option HostKey specifies the location containing the private host key. ServerKeyBits 1024 The option ServerKeyBits specifies how many bits to use in the server key. These bits are used when the daemon starts to generate its RSA key. LoginGraceTime 600 The option LoginGraceTime specifies how long in seconds after a connection request the server will wait before disconnecting if the user has not successfully logged in. KeyRegenerationInterval 3600 The option KeyRegenerationInterval specifies how long in seconds the server should wait before automatically regenerated its key. This is a security feature to prevent decrypting captured sessions. PermitRootLogin no The option PermitRootLogin specifies whether root can log in using ssh. Never say yes to this option. IgnoreRhosts yes The option IgnoreRhosts specifies whether rhosts or shosts files should not be used in authentication. For security reasons it is recommended to no use rhosts or shosts files for authentication. IgnoreUserKnownHosts yes The option IgnoreUserKnownHosts specifies whether the ssh daemon should ignore the user's $HOME/.ssh/known_hosts during RhostsRSAAuthentication. StrictModes yes The option StrictModes specifies whether ssh should check user's permissions in their home directory and rhosts files before accepting login. This option must always be set to yes because sometimes users may accidentally leave their directory or files world-writable. X11Forwarding no The option X11Forwarding specifies whether X11 forwarding should be enabled or not on this server. Since we setup a server without GUI installed on it, we can safely turn this option off. PrintMotd yes The option PrintMotd specifies whether the ssh daemon should print the contents of the /etc/motd file when a user logs in interactively. The / etc/motd file is also known as the message of the day. SyslogFacility AUTH The option SyslogFacility specifies the facility code used when logging messages from sshd. The facility specifies the subsystem that produced the message--in our case, AUTH. LogLevel INFO The option LogLevel specifies the level that is used when logging messages from sshd. INFO is a good choice. See the man page for sshd for more information on other possibilities. RhostsAuthentication no The option RhostsAuthentication specifies whether sshd can try to use rhosts based authentication. Because rhosts authentication is insecure you shouldn't use this option. RhostsRSAAuthentication no The option RhostsRSAAuthentication specifies whether to try rhosts authentication in concert with RSA host authentication. RSAAuthentication yes The option RSAAuthentication specifies whether to try RSA authentication. This option must be set to yes for better security in your sessions. RSA use public and private key pairs created with the ssh-keygen1utility for authentication purposes. PasswordAuthentication yes The option PasswordAuthentication specifies whether we should use password-based authentication. For strong security, this option must always be set to yes. PermitEmptyPasswords no The option PermitEmptyPasswords specifies whether the server allows logging in to accounts with a null password. If you intend to use the scp utility to make automatic backups over the network, you must set this option to yes. AllowUsers admin The option AllowUsers specifies and controls which users can access ssh services. Multiple users can be specified, separated by spaces. ----------------------------------------------------------------------------- 15.5. Configure OpenSSH to use TCP-Wrappers/inetd super server Tcp-Wrappers should be enabled to start and stop our OpenSSH server. Upon execution, inetd reads its configuration information from a configuration file which, by default, is /etc/inetd.conf. There must be an entry for each field of the configuration file, with entries for each field separated by a tab or a space. 1. Edit the inetd.conf file vi /etc/inetd.conf and add the line: ssh stream tcp nowait root /usr/sbin/tcpd sshd -i Important : The -i parameter is important since it's specifies that sshd is being run from inetd. Also, update your inetd.conf file by sending a SIGHUP signal killall-HUP inetd after adding the above line to the file. To update your inetd.conf file, use the following command: [root@deep] /#killall -HUP inetd 2. Edit the hosts.allow file, vi /etc/hosts.allow and add the line: sshd: 192.168.1.4 win.openna.com Which mean client IP 192.168.1.4 with host name win.openna.com is allowed to ssh in to the server. These daemon strings for tcp-wrappers are in use by sshd: sshdfwd-X11 if you want to allow/deny X11-forwarding sshdfwd- for tcp-forwarding sshdfwd- port-name defined in /etc/services. Used in tcp-forwarding Tip : If you do decide to switch to using ssh, make sure you install and use it on all your servers. Having ten secure servers and one insecure is a waste of time. For more details, there are several man pages you can read: ssh(1) OpenSSH secure shell client remote login program ssh [slogin](1) OpenSSH secure shell client remote login program ssh-add(1) adds identities for the authentication agent ssh-agent(1) authentication agent ssh-keygen(1) authentication key generation sshd(8) secure shell daemon ----------------------------------------------------------------------------- 15.6. OpenSSH Per-User Configuration 1. Create your private & public keys of local, by executing: [root@deep] /#su admin [admin@deep /]$ssh-keygen The result should look like the following example: Initializing random number generator... Generating p: ............................++ (distance 430) Generating q: ......................++ (distance 456) Computing the keys... Testing the keys... Key generation complete. Enter file in which to save the key (/home/admin/.ssh/identity): [Press Enter] Enter passphrase: Enter the same passphrase again: Your identification has been saved in /home/admin/.ssh/identity. Your public key is: 1024 37 14937757511251955533691120318477293862290049394715136511145806108870001764378494676831297577843158532 2723612061006231460440536487184367748423324091941848098890786099717524446977589647127757030728779973708569993 017043141563536333068888944038178461608592483844590202154102756903055846534063365635584899765402181 admin@deep.openna.com Your public key has been saved in /home/admin/.ssh/identity.pub Note : If you have multiple accounts you might want to create a separate key on each of them. You may want to have separate keys for:   o  Your Mail server   o  Your Web server   o  Your GW server This allows you to limit access between these servers, e.g. not allowing the Mail account to access your Web account or the machines in the GW. This enhances the overall security in the case any of your authentication keys are compromised for any reason. 2. Copy your local public keys identity.pub to the /home/admin/.ssh directory remotely under the name, say, authorized_keys. Tip : One way to copy the file is to use the ftp command or you might need to send your public key in electronic mail to the administrator of the system. Just include the contents of the ~/.ssh/identity.pub file in the message. You might feel the need to Change your pass-phrase for various reason and can do so at any time by using the -p option of ssh-keygen. To change the pass-phrase, use the command: [root@deep] /#su admin [admin@deep /]$ssh-keygen -p Enter file key is in /home/admin/.ssh/identity: [Press ENTER] Enter old passphrase: Key has comment 'admin@deep.openna.com' Enter new passphrase: Enter the same passphrase again: Your identification has been saved with the new passphrase. ----------------------------------------------------------------------------- 15.7. OpenSSH Users Tools The commands listed belows are some that we use often in our regular use, but many more exist, and you should check the man page and documentation for more details. The ssh Secure Shell command provides secure encrypted communications between two untrusted hosts over an insecure network. It is a program for logging securely into a remote machine and executing commands from there. It is a suitable replacement for insecure programs like telnet, rlogin, rcp, rdist, and rsh. To login to a remote machine, use the command: [root@deep] /#ssh -l Example 15-1. Remote login using ssh [root@deep] /#ssh -l admin www.openna.com admin@deep.openna.coms password: Last login: Tue Oct 19 1999 18:13:00 -0400 from deep.openna.com No mail. [admin@www ]/admin$ Where is the name you use to connect to the ssh server and < hostname> is the remote address of your ssh server. ----------------------------------------------------------------------------- 15.7.1. scp The scp Secure Copy utility copies files from the local system to a remote system or vice versa, or even between two remote systems using the scp command. To copy files from remote to local system, use the following command: [root@deep] /#su admin [admin@deep /]$scp -p :/dir/for/file localdir/to/filelocation Example 15-2. scp Secure Copy utility [admin@deep /]$ scp1 -p admin@mail:/etc/test1 /tmp Enter passphrase for RSA key 'admin@mail.openna.com': test1 | 2 KB | 2.0 kB /s | ETA: 00:00:00 | 100% To copy files from local to remote system, use the following command: [root@deep] /#su admin [admin@deep /]$scp -p localdir/to/filelocation :/dir/for/file Example 15-3. local to remote [admin@deep /]$scp1 -p /usr/bin/test2 admin@mail:/var/tmp admin@mail's password: test2 | 7 KB | 7.9 kB/s | ETA: 00:00:00 | 100% Tip : The -p option indicates that the modification and access times, as well as modes of the source file, should be preserved on the copy. This is usually desirable. Some possible uses of OpenSSH softwareare: 1. Replace telnet, rlogin, rsh, rdist, and rcp. 2. Make secure backups over the network. 3. Execute remote commands. 4. Access to corporate resources over the Internet. ----------------------------------------------------------------------------- 15.8. Installed files These are files Installed by the software program Openssh: /etc/ssh /usr/bin/slogin /etc/ssh/ssh_config /usr/man/man1/ssh.1 /etc/ssh/sshd_config /usr/man/man1/scp.1 /etc/ssh_host_key /usr/man/man1/ssh-add.1 /etc/ssh_host_key.pub /usr/man/man1/ssh-agent.1 /usr/bin/ssh /usr/man/man1/ssh-keygen.1 /usr/bin/scp /usr/man/man1/slogin.1 /usr/bin/ssh-add /usr/man/man8/sshd.8 /usr/bin/ssh-agent /usr/sbin/sshd /usr/bin/ssh-keygen   ----------------------------------------------------------------------------- 15.8.1. Free SSH clients for Windows Check out this free SSH clients for windows; so that you can provide the same services on your windows machine, if your networked environement is likely to have windows indtalled machines. Putty. And this is Putty Homepage:http://www.chiark.greenend.org.uk/ ~sgtatham/putty.html Tera Term Pro and TTSSH. The Tera Term Pro can be found here on its Homepage: http://hp.vector.co.jp/authors/VA002416/teraterm.html, and TTSSH Homepage is: http://www.zip.com.au/~roca/download.html. ----------------------------------------------------------------------------- Chapter 16. Software -Securties(commercial) Its now clear that all Linux users must use OpenSSH instead of SSH2 from Datafellows Company. However, for the users or organizations that want to use the non-free version of this software, we provide here steps to follow. This is the SSH2 commercial version of SSH software. In our configuration we have also configured sshd2 to support tcp-wrappers the inetd super server for security reason. ----------------------------------------------------------------------------- 16.1. Linux SSH2 Client/Server Since Linux is all about choices we have provided as an alternative the commercial verion of OpenSSH, The SSH2 and these installation instructions assume   *  Commands are Unix-compatible.   *  The source path is /var/tmp, other paths are possible.   *  Installations were tested on Red Hat Linux 6.1 and 6.2.   *  All steps in the installation will happen in super-user account root.   *  SSH2 version number is 2.0.13 Packages that you need can be downloaded from: SSH2 Homepage:http://www.ssh.org/ You must be sure to download: ssh-2.0.13.tar.gz once you have got the Tarballs, It is a good idea to make a list of files on the system before you install ssh2, and one afterwards, and then compare them using diff to find out what file it placed where. Simply run find /* > SSH1 before and find /* > SSH2 after you install the software, and use diff SSH1 SSH2 > SSH-Installed to get a list of what changed. Before you Compile, you need to decompress the tarball tar.gz. [root@deep] /#cp ssh-version.tar.gz /var/tmp [root@deep] /#cd /var/tmp [root@deep ]/tmp#tar xzpf ssh-version.tar.gz You need to Compile and Optimize so move into the new SSH2 directory and type the following commands on your terminal: CC="egcs" \ CFLAGS="-O9 -funroll-loops -ffast-math -malign-double -mcpu=pentiumpro -march=pentiumpro -fomit-frame-pointer -fno-exceptions" \ ./configure \ --prefix=/usr \ --without-ssh-agent1-compat \ --disable-suid-ssh-signer \ --disable-tcp-port-forwarding \ --disable-X11-forwarding \ --enable-tcp-nodelay \ --with-libwrap This tells SSH2 to set itself up for this particular hardware setup as follows:   *  Leave out ssh-agent1 compatibility.   *  Install ssh-signer without suid bit.   *  Disable port forwarding support.   *  Disable X11 forwarding support.   *  Enable TCP_NODELAY socket option.   *  Compile in libwrap tcp_wrappers support. [root@deep ]/ssh-2.0.13#make clean [root@deep ]/ssh-2.0.13# make [root@deep ]/ssh-2.0.13# make install [root@deep ]/ssh-2.0.13#rm -f /usr/bin/ssh-askpass The make clean, command erase all previous traces of a compilation so as to avoid any mistakes, The make command compiles all source files into executable binaries, The make install command installs the binaries and any supporting files into the appropriate locations. Please don't forget to cleanup after work: [root@deep] /#cd /var/tmp [root@deep ]/tmp#rm -rf ssh-version/ ssh-version.tar.gz The rm command as used above will remove all the source files we have used to compile and install SSH2. It will also remove the SSH2 compressed archive from the /var/tmp directory. ----------------------------------------------------------------------------- 16.2. Configure and Optimise SSH2 Note : All the configuration files required for each software described in this book has been provided by us as a gzipped file, floppy.tgz for your convenience. This can be downloaded from this web address: http:// www.openna.com/books/floppy.tgz You can unpack this to any location on your local machine, say for example /tmp, assuming you have done this your directory structure will be /tmp/floppy. Within this floppy directory each configuration file has its own directory for respective software. For example SSH2 configuration file are organised like this: total 16 -rw-r--r-- 1 harrypotter harrypotter 326 Jun 8 13:00 Compile-SSH2 drwxr-xr-x 2 harrypotter harrypotter 4096 Jun 8 13:00 pam.d/ -rw-r--r-- 1 harrypotter harrypotter 462 Jun 8 13:00 ssh2_config -rw-r--r-- 1 harrypotter harrypotter 799 Jun 8 13:00 sshd2_config You can either cut and paste this directly if you are faithfully following our instructions from the begining or manually edit these to modify to your needs. This facility is there though as a convenience but please don't forget ultimately it will be your responsibility to check, verify, etc. before you use them whether modified or as it is. To run the SSH2 Client/Server, the following files are required, and must be created or copied to the appropriate directories on your server.   *  Copy the sshd2_config file to the /etc/ssh2/ directory.   *  Copy the ssh2_config file to the /etc/ssh2/ directory.   *  Copy the ssh file to the /etc/pam.d/ directory. Tip : You can obtain the configuration files listed in the following section on our floppy.tgz archive. Copy the following files from the decompressed floppy.tgz archive to the appropriate places, or copy them directly from this book to the concerned file. ----------------------------------------------------------------------------- 16.3. Configure the /etc/ssh2/ssh2_config file The configuration file for ssh2 /etc/ssh2/ssh2_config allows you to set options that modify the operation of the client programs. The files contain keyword-value pairs, one per line, with keywords being case insensitive. Here are the more important keywords; a complete listing is available in the man page for ssh2(1). Edit the ssh2_config file, vi /etc/ssh2/ssh2_config and add or change, if necessary: # ssh2_config # SSH 2.0 Client Configuration File *:Port 22 Ciphers blowfish Compression yes IdentityFile identification AuthorizationFile authorization RandomSeedFile random_seed VerboseMode no ForwardAgent no ForwardX11 no PasswordPrompt "%U's password: " Ssh1Compatibility no Ssh1AgentCompatibility none NoDelay yes KeepAlive yes QuietMode no This tells ssh2_config file to set itself up for this particular configuration setup with: Port 22 The option Port specifies on which port number ssh connects to on the remote host. The default port is 22. Ciphers blowfish The option Ciphers specifies what cipher should be used for encrypting sessions. The blowfish uses 64-bit blocks and keys of up to 448 bits. Compression yes The option Compression specifies whether to use compression during sessions. Compression will improve communication speed and files transfers. IdentityFile identification The option IdentityFile specifies an alternate name for the user's identification file. AuthorizationFile authorization The option AuthorizationFile specifies an alternate name for the user's authorization file. RandomSeedFile random_seed The option RandomSeedFile specifies an alternate name for the user's random seed file. VerboseMode no The option VerboseMode instructs ssh2 to print debugging messages about its progress. This option is helpful in debugging connection, authentication, and configuration problems. ForwardAgent no The option ForwardAgent specifies which connection authentication agent if any should be forwarded to the remote machine. ForwardX11 no The option ForwardX11 is for people that use the Xwindow GUI and want to automatically redirect X11 sessions to the remote machine. Since we've set up a server and do not have a GUI installed on it, we can safely turn this option off. PasswordPrompt "%U's password: " The option PasswordPrompt specifies the password prompt that will be displayed for the user when connecting to a host. Variables %U and %H give the user's login name and host, respectively. Ssh1Compatibility no The option Ssh1Compatibility specifies whether or not to use SSH1 compatibility code with SSH2 for ssh1 users. Ssh1AgentCompatibility none The option Ssh1AgentCompatibility specifies whether or not to also forward SSH1 agent connections with SSH2 for ssh1 users. NoDelay yes The option NoDelay specifies if the socket option TCP_NODELAY should be enabled. It is recommended that you set this option to yes to improve network performance. KeepAlive yes The option KeepAlive specifies whether the system should send keep alive messages to the remote server. If set to yes then the death of the connection or crash of remote machines will be properly noticed. QuietMode no The option QuietMode specifies whether the system runs in quiet mode. This option must be set to no because in quiet mode, nothing is logged in the system log except for fatal errors. Since we want to have information about users sessions it is preferable to disable this option. ----------------------------------------------------------------------------- 16.4. Configure the /etc/ssh2/sshd2_config file The configuration file for sshd2 /etc/ssh2/sshd2_config allows you to set options that modify the operation of the daemon. The files contain keyword-value pairs, one per line, with keywords being case insensitive. Here are the more important keywords; a complete listing is available in the man page for sshd2(8). Edit the sshd2_config file (vi /etc/ssh2/sshs2_config and add or change, if necessary: # sshd2_config # SSH 2.0 Server Configuration File *:Port 22 ListenAddress 192.168.1.1 Ciphers blowfish IdentityFile identification AuthorizationFile authorization HostKeyFile hostkey PublicHostKeyFile hostkey.pub RandomSeedFile random_seed ForwardAgent no ForwardX11 no PasswordGuesses 3 MaxConnections 5 PermitRootLogin no AllowedAuthentications publickey,password RequiredAuthentications publickey,password VerboseMode no PrintMotd yes CheckMail yes UserConfigDirectory "%D/.ssh2" SyslogFacility DAEMON Ssh1Compatibility no NoDelay yes KeepAlive yes UserKnownHosts yes AllowHosts 192.168.1.4 DenyHosts * QuietMode no # subsystem definitions subsystem-sftp sftp-server This tells sshd2_config file to set itself up for this particular configuration setup with: Port 22 The option Port specifies which port number the ssh2 daemon listens to for ssh incoming connection. The default port is 22. ListenAddress 192.168.1.1 The option ListenAddress specifies the IP address of the interface network on which the ssh2 daemon server socket is bound. The default is 0.0.0.0; to improve security you may specify only the required ones to limit possible addresses. Ciphers blowfish The option Ciphers specifies what cipher should be used for encrypting sessions. The blowfish uses 64-bit blocks and keys of up to 448 bits. IdentityFile identification The option IdentityFile specifies an alternate name for the user's identification file. AuthorizationFile authorization The option AuthorizationFile specifies an alternate name for the user's authorization file. HostKeyFile hostkey The option HostKeyFile specifies an alternate file containing the private host key. The default is /etc/ssh2/hostkey. PublicHostKeyFile hostkey.pub The option PublicHostKeyFile specifies an alternate file containing the public host key. The default is /etc/ssh2/hostkey.pub. RandomSeedFile random_seed The option RandomSeedFile specifies an alternate name for the user's random seed file. ForwardAgent no The option ForwardAgent specifies which connection authentication agent if any should be forwarded to the remote machine. ForwardX11 no The option ForwardX11 is for people that use the Xwindow GUI and want to automatically redirect X11 sessions to the remote machine. Since we set up a server and don't have a GUI installed on it, we can safely turn this option off. PasswordGuesses 3 The option PasswordGuesses specifies how many tries the user has when using password authentication. MaxConnections 5 The option MaxConnections specifies what the maximum number of connections that ssh2 daemon will handle simultaneously is. PermitRootLogin no The option PermitRootLogin specifies whether root can log in using ssh. Never say, yes to this option. AllowedAuthentications publickey,password The option AllowedAuthentications specifies which authentication methods are allowed to be used. With this option the administrator can force users to complete several authentications before they are considered authenticated. RequiredAuthentications publickey,password The option RequiredAuthentications related to AllowedAuthentications, specifies which authentication methods the users must complete before continuing. This parameter must be the same as for the AllowedAuthentications option or the server will denies connection every time. VerboseMode no The option VerboseMode instructs the ssh2 daemon to print debugging messages about its progress. This option is helpful in debugging connection, authentication, and configuration problems. PrintMotd yes The option PrintMotd specifies whether the ssh2 daemon should print the content of the /etc/motd file when a user logs in interactively. The /etc /motd file is also know as the message of the day. CheckMail yes The option CheckMail specifies whether the ssh2 daemon should print information about new mail you may have. UserConfigDirectory "%D/.ssh2" The option UserConfigDirectory specifies the default location for user-specific configuration data. SyslogFacility DAEMON The option SyslogFacility specifies the facility code used when logging messages from the ssh2 daemon. The facility specifies the subsystem that produced the message, in our case DAEMON. Ssh1Compatibility no The option Ssh1Compatibility specifies whether or not to use SSH1 compatibility code with SSH2 for ssh1 users. NoDelay yes The option NoDelay specifies if the socket option TCP_NODELAY should be enabled. It is recommended that you set this option to yes to improve network performance. KeepAlive yes The option KeepAlive specifies whether the system should send keep alive messages to the remote server. If set to yes then the death of the connection or crash of remote machines will be properly noticed. UserKnownHosts yes The option UserKnownHosts specifies whether the default user's home directory $HOME/.ssh2/knownhosts/ can be used to get hosts public keys when using hostbased-authentication. AllowHosts 192.168.1.4 The option AllowHosts specifies and control which hosts can access ssh2 services. Multiple hosts can be specified separated by spaces. DenyHosts * The option DenyHosts specifies and controls which hosts cannot access ssh2 services. Multiple hosts can be specified separated by spaces. The default pattern * mean all hosts. QuietMode no The option QuietMode specifies whether the system runs in quiet mode. This option must be set to no, because in quiet mode nothing is logged in the system log except for fatal errors. Since we want to have information about user sessions it is preferable to disable this option. ----------------------------------------------------------------------------- 16.5. Configure sshd2 to use tcp-wrappers/inetd super server Tcp-wrappers shoud be enabled to start and stop the sshd2 server. Upon execution, inetd reads its configuration information from a configuration file which, by default, is /etc/inetd.conf. There must be an entry for each field of the configuration file, with entries for each field separated by a tab or a space. 1. Edit the inetd.conf file, vi /etc/inetd.conf and add the line: ssh stream tcp nowait root /usr/sbin/tcpd sshd -i Important : The -i parameter is important since it specifies that sshd is being run from inetd. Also, update your inetd.conf file by sending a SIGHUP signal, killall -HUP inetd after adding the above line into the file. To update your inetd.conf file, use the following command: [root@deep] /#killall -HUP inetd 2. Edit the hosts.allow file, vi /etc/hosts.allow and add the line: sshd: 192.168.1.4 win.openna.com Which means client 192.168.1.4 with host name win.openna.com is allowed to ssh on the server. Note: These daemon strings for tcp-wrappers are in use by sshd2: sshd, sshd2 The name sshd2 was called with usually sshd. sshdfwd-X11 if you want to allow/deny X11-forwarding. sshdfwd- for tcp-forwarding. sshdfwd- port-name defined in /etc/services. Used in tcp-forwarding. Tip : If you do decide to switch to using ssh, make sure you install and use it on all your servers. Having ten secure servers and one insecure is a waste of time. ----------------------------------------------------------------------------- 16.6. Configuration of the /etc/pam.d/ssh file For better security of your ssh2 server, you can configure it to use pam authentication. To do that, you must create the /etc/pam.d/ssh file. Create the ssh file touch /etc/pam.d/ssh and add or change, if necessary: #%PAM-1.0 auth required /lib/security/pam_pwdb.so shadow auth required /lib/security/pam_nologin.so account required /lib/security/pam_pwdb.so password required /lib/security/pam_cracklib.so password required /lib/security/pam_pwdb.so use_authtok nullok md5 shadow session required /lib/security/pam_pwdb.so For Further documentation and more details, there are several man pages you can read: ssh-add2(1) - adds identities for the authentication agent ssh-agent2(1) - authentication agent ssh-keygen2(1) - authentication key pair generation ssh2(1) - secure shell client remote login program sshd2(8) - secure shell daemon ----------------------------------------------------------------------------- 16.7. Ssh2 Per-User Configuration 1. Create your private & public keys of local, by executing: [root@deep] /#su admin [admin@deep /]$ ssh-keygen2 Generating 1024-bit dsa key pair 6 Oo..oOo.oOo. Key generated. 1024-bit dsa, admin@deep.openna.com, Sun Feb 13 2000 05:33:38 -0500 Passphrase : Again : Private key saved to /home/admin/.ssh2/id_dsa_1024_a Public key saved to /home/admin/.ssh2/id_dsa_1024_a.pub 2. Create an identification file in your ~/.ssh2 home directory on local: [admin@deep]$cd ~/.ssh2 [admin@deep ]/.ssh2$echo "IdKey id_dsa_1024_a" > identification Note : It's optional to create an identification file on Remote. The identification file contains the name of the private key that is to be used in authentication. 3. Copy your public key of Local id_dsa_1024_a.pub to ~/.ssh2 home directory of remote under the name, say, Local.pub. 4. Create an authorization file in your ~/.ssh2 home directory on remote: [admin@remote ]/.ssh2$touch authorization Note : The ~/ means the user home directory. 5. Add the following one line to the authorization file on the remote host: [admin@remote ]/.ssh2$vi authorization key Local.pub ----------------------------------------------------------------------------- 16.8. SSH2 Users Tools The commands listed below are some that we use often in our regular use, but many more exist, and you should check the man page and documentation for more details. ssh2. Ssh2, Secure Shell provides secure encrypted communications between two untrusted hosts over an insecure network. It is a program for logging securely into a remote machine and executing commands from there. It is a suitable replacement for insecure program like telnet, rlogin, rcp, rdist, and rsh. To login to a remote machine, use the command: [root@deep] /#ssh2 -l Example 16-1. login to a remote using ssh2 [root@deep] /#ssh2 -l admin www.openna.com Passphrase for key "/home/admin/.ssh2/id_dsa_1024_a" with comment "1024-bit dsa, admin@deep.openna.com, Tue Oct 19 1999 14:31:40 -0400": admin's password: Last login: Tue Oct 19 1999 18:13:00 -0400 from deep.openna.com No mail. [admin@www ]/admin$ Where is the name you use to connect to the ssh2 remote server and is the address of your ssh2 remote server. sftp2. The sftp2, Secure File Transfer utility is an ftp-like client that provides file transfers over the network. You must already be connected with ssh2 before using the sftp2 utility. To ftp over ssh2, use the following command: [admin@deep /]$sftp2 Example 16-2. sftp2, Secure File Transfer [admin@deep /]$sftp2 www.openna.com local path : /home/admin Passphrase for key "/home/admin/.ssh2/id_dsa_1024_a" with comment "1024-bit dsa, admin@deep.openna.com, Tue Oct 19 1999 14:31:40 -0400": admin's password: admin's password: remote path : /home/admin sftp> Where is the name of the remote server you want to sftp. ----------------------------------------------------------------------------- 16.9. Installed files These are the files Installed by Ssh2 software on your machine: /etc/pam.d/ssh /usr/man/man1/sftp2.1 /usr/bin/ssh-keygen2 /etc/ssh2 /usr/man/man1/ssh.1 /usr/bin/ssh-signer2 /etc/ssh2/hostkey /usr/man/man1/ssh-add.1 /usr/bin/ssh-add2 /etc/ssh2/hostkey.pub /usr/man/man1/ssh-agent.1 /usr/bin/ssh /etc/ssh2/sshd2_config /usr/man/man1/ssh-keygen.1 /usr/bin/ssh-agent /etc/ssh2/ssh2_config /usr/man/man1/scp.1 /usr/bin/ssh-add /root/.ssh2 /usr/man/man1/sftp.1 /usr/bin/ssh-askpass /root/.ssh2/random_seed /usr/man/man8/sshd2.8 /usr/bin/ssh-keygen /root/ssh2 /usr/man/man8/sshd.8 /usr/bin/scp /usr/man/man1/ssh2.1 /usr/bin/ssh2 /usr/bin/sftp /usr/man/man1/ssh-keygen2.1 /usr/bin/scp2 /usr/bin/sftp-server /usr/man/man1/ssh-add2.1 /usr/bin/sftp2 /usr/bin/ssh-signer /usr/man/man1/ssh-agent2.1 /usr/bin/sftp-server2 /usr/sbin/sshd2 /usr/man/man1/scp2.1 /usr/bin/ssh-agent2 /usr/sbin/sshd ----------------------------------------------------------------------------- Chapter 17. Software -Securities/System Integrity A typical Red Hat Linux server installation handles approximately 30,400 files. At their busiest times, administrators can't check the integrity of all system files, and if a cracker has accessed your server, he or she can install or modify files without your knowledge with some effort. Since such a possibility exists a few programs have been created to respond to this kind of activity. ----------------------------------------------------------------------------- 17.1. Linux Tripwire 2.2.1 +---------------------------------------------------------------------------+ | According to the official [Tripwire site]: | | | | Tripwire works at the most fundamental layer, protecting the servers and | | workstations that make up the corporate network. Tripwire works by first | | scanning a computer and creating a database of system files, a compact | | digital snapshot of the system in a known secure state. The user can | | configure Tripwire very precisely, specifying individual files and | | directories on each machine to monitor, or creating a standard template | | that can be used on all machines in an enterprisewide environement. | | | | Once this baseline database is created, a system administrator can use | | Tripwire to check the integrity of a system at any time. By scanning the | | current system and comparing that information with the data stored in the | | database, Tripwire detects and reports any additions, deletions, or | | changes to the system outside of the specified boundaries. If these | | changes are valid, the administrator can update the baseline database | | with the new information. If malicious changes are found, the system | | administrator will instantly know exactly which part, which component | | etc. of the network have been affected. | +---------------------------------------------------------------------------+ This version of Tripwire has significant product enhancements over previous versions of Tripwire. Some of the enhancements include:   *  Multiple levels of reporting allow you to choose different levels of report detail.   *  Syslog option sends information about database initialization, database update, policy update and integrity check to the syslog.   *  Database performance has been optimized to increase the efficiency of integrity checks.   *  Individual email recipients can be sent certain sections of a report.   *  SMTP email reporting support.   *  Email test mode enables you to verify that the email settings are correct.   *  Ability to create multiple sections within a policy file to be executed separately. These installation instructions assume:   *  Commands are Unix-compatible.   *  The source path is /var/tmp -other paths are possible.   *  Installations were tested on Red Hat Linux 6.1 and 6.2.   *  All steps in the installation will happen in super-user account root.   *  Tripwire version number is 2.2.1 These are the Package(s) you need to install: Tripwire Homepage: http://www.tripwiresecurity.com/ You must be sure to download: Tripwire_221_for_Linux_x86_tar.gz To Compile Tripwire-2.2.1, you do need to Decompress the tarball tar.gz.: [root@deep] /#cp Tripwire_version_for_Linux_x86_tar.gz /var/tmp [root@deep] /#cd /var/tmp [root@deep ]/tmp# tar xzpf Tripwire_version_for_Linux_x86_tar.gz Note : After the decompression of Tripwire you will see the following files in your /var/tmp directory related to Tripwire software: License.txt README Release_Notes install.cfg install.sh package directory Tripwire tar.gz file Tripwire_version_for_Linux_x86_tar.gz. ----------------------------------------------------------------------------- 17.2. Configure the /var/tmp/install.cfg file Recall that Tripwire version 2.2.1 is not open source, so you cannot compile and install it like other archives source files, instead you must modify the install.cfg file of tripwire that will install automatically Tripwire software for you to specify installation paths for your system. We must modify this file to be compliant with Red Hats file system structure and install Tripwire binaries under our PATH Environment Variable. 1. Edit the install.cfg file, vi install.cfg and change this file to look like: # # install.cfg # # default install.cfg for: # Tripwire(R) 2.2.1 for Unix # # NOTE: This is a Bourne shell script that stores installation # parameters for your installation. The installer will # execute this file to generate your config file and also to # locate any special configuration needs for your install. # Protect this file, because it is possible for # malicious code to be inserted here # # To set your Root directory for install, set TWROOT= to something # other than /usr/TSS as necessary. # #======================================================= # If CLOBBER is true, then existing files are overwritten. # If CLOBBER is false, existing files are not overwritten. CLOBBER=false # The root of the TSS directory tree. TWROOT="/usr" # Tripwire binaries are stored in TWBIN. TWBIN="${TWROOT}/bin" # Tripwire policy files are stored in TWPOLICY. TWPOLICY="${TWROOT}/TSS/policy" # Tripwire manual pages are stored in TWMAN. TWMAN="${TWROOT}/man" # Tripwire database files are stored in TWDB. TWDB="${TWROOT}/TSS/db" # The Tripwire site key files are stored in TWSITEKEYDIR. TWSITEKEYDIR="${TWROOT}/TSS/key" # The Tripwire local key files are stored in TWLOCALKEYDIR. TWLOCALKEYDIR="${TWROOT}/TSS/key" # Tripwire report files are stored in TWREPORT. TWREPORT="${TWROOT}/TSS/report" # This sets the default text editor for Tripwire. TWEDITOR="/bin/vi" # TWLATEPROMTING controls the point when tripwire asks for a password. TWLATEPROMPTING=false # TWLOOSEDIRCHK selects whether the directory should be monitored for # properties that change when files in the directory are monitored. TWLOOSEDIRCHK=false # TWMAILNOVIOLATIONS determines whether Tripwire sends a no violation # report when integrity check is run with --email-report but no rule # violations are found. This lets the admin know that the integrity # was run, as opposed to having failed for some reason. TWMAILNOVIOLATIONS=true # TWEMAILREPORTLEVEL determines the verbosity of e-mail reports. TWEMAILREPORTLEVEL=3 # TWREPORTLEVEL determines the verbosity of report printouts. TWREPORTLEVEL=3 # TWSYSLOG determines whether Tripwire will log events to the system log TWSYSLOG=false ##################################### # Mail Options - Choose the appropriate # method and comment the other section ##################################### ##################################### # SENDMAIL options - DEFAULT # # Either SENDMAIL or SMTP can be used to send reports via TWMAILMETHOD. # Specifies which sendmail program to use. ##################################### TWMAILMETHOD=SENDMAIL TWMAILPROGRAM="/usr/lib/sendmail -oi -t" ##################################### # SMTP options # # TWSMTPHOST selects the SMTP host to be used to send reports. # SMTPPORT selects the SMTP port for the SMTP mail program to use. ##################################### # TWMAILMETHOD=SMTP # TWSMTPHOST="mail.domain.com" # TWSMTPPORT=25 ################################################################################ # Copyright (C) 1998-2000 Tripwire (R) Security Systems, Inc. Tripwire (R) is a # registered trademark of the Purdue Research Foundation and is licensed # exclusively to Tripwire (R) Security Systems, Inc. ################################################################################ Note : The file install.cfg is a Bourne shell script used by the installer to set configuration variables. These variables specify the target directories where the installer will copy files and what the installer should do if the installation process would overwrite existing Tripwire software files. 2. Now we must run the installation script to install Tripwire binaries and related files on to our system according to whether you are using default or custom configuration values. To run the installation script and install Tripwire, use the following command: [root@deep ]/tmp#./install.sh Important : The install.sh file is the installation script which you run to begin installation of Tripwire. During the installation procedure, you will: 1. Answer some questions related to the installation. 2. Specify two pass phrases to be assigned for your site and local keys. 3. When Tripwire is installed in our system it will copy License.txt, README, and Release_Notes files under /usr directory. Of course after finishing reading those files you can safely remove them from your /usr directory with the following command: To remove these files from your system, use the following command: [root@deep ]/usr# rm -f /usr/License.txt README Release_Notes Dont forget to clean up later: [root@deep] /#cd /var/tmp [root@deep ]/tmp# rm -rf License.txt README Release-Notes install.cfg install.sh pkg/ Tripwire_version_for_Linux_x86_tar.gz The rm command as used above will remove all related files and directories we have used to install Tripwire for Linux. It will also remove the Tripwire for Linux compressed archive from the /var/tmp directory. ----------------------------------------------------------------------------- 17.3. Configuration files Note : All the configuration files required for each software described in this book has been provided by us as a gzipped file, floppy.tgz for your convenience. This can be downloaded from this web address: http:// www.openna.com/books/floppy.tgz You can unpack this to any location on your local machine, say for example /tmp, assuming you have done this your directory structure will be /tmp/floppy. Within this floppy directory each configuration file has its own directory for respective software. For example Tripwire-2.2.1 configuration file are organised like this: total 16 -rw-r--r-- 1 harrypotter harrypotter 3312 Jun 8 13:00 install.cfg -rw-r--r-- 1 harrypotter harrypotter 10152 Jun 8 13:00 twpol.txt You can either cut and paste this directly if you are faithfully following our instructions from the begining or manually edit these to modify to your needs. This facility is there though as a convenience but please don't forget ultimately it will be your responsibility to check, verify, etc. before you use them whether modified or as it is. To run Tripwire for Linux, the following file is required and must be created or copied to the appropriate directory on your server. Copy the twpol.txt file to the /usr/TSS/policy directory. Tip : You can obtain the configuration file listed below on our floppy.tgz archive. Copy the following file from the decompressed floppy.tgz archive to the appropriate place, or copy and paste it directly from this book to the concerned file. ----------------------------------------------------------------------------- 17.4. Configure the /usr/TSS/policy/twpol.txt file The /usr/TSS/policy/twpol.txt is the text policy file of Tripwire where you specify what files and directories, to check. Note that extensive testing and experience are necessary when editing this policy file before you get a working file report. The following is a working example from where you can start your own customization. 1. You must modify the default policy file, or create your own. The policyguide.txt file under /usr/TSS/policy directory can help you. Open the policy file twpol.txt with a text editor, vi /usr/TSS/policy/ twpol.txt and change it to fit your needs: @@section GLOBAL TWROOT="/usr"; TWBIN="/usr/bin"; TWPOL="/usr/TSS/policy"; TWDB="/usr/TSS/db"; TWSKEY="/usr/TSS/key"; TWLKEY="/usr/TSS/key"; TWREPORT="/usr/TSS/report"; HOSTNAME=deep.openna.com; @@section FS SEC_CRIT = $(IgnoreNone)-SHa; # Critical files - we can't afford to miss any changes. SEC_SUID = $(IgnoreNone)-SHa; # Binaries with the SUID or SGID flags set. SEC_TCB = $(ReadOnly); # Members of the Trusted Computing Base. SEC_BIN = $(ReadOnly); # Binaries that shouldn't change SEC_CONFIG = $(Dynamic); # Config files that are changed infrequently but accessed often. SEC_LOG = $(Growing); # Files that grow, but that should never change ownership. SEC_INVARIANT = +pug; # Directories that should never change permission or ownership. SIG_LOW = 33; # Non-critical files that are of minimal security impact SIG_MED = 66; # Non-critical files that are of significant security impact SIG_HI = 100; # Critical files that are significant points of vulnerability # Tripwire Binaries (emailto = admin@openna.com, rulename = "Tripwire Binaries", severity = $(SIG_HI)) { $(TWBIN)/siggen -> $(ReadOnly); $(TWBIN)/tripwire -> $(ReadOnly); $(TWBIN)/twadmin -> $(ReadOnly); $(TWBIN)/twprint -> $(ReadOnly); } # Tripwire Data Files - Configuration Files, Policy Files, Keys, Reports, Databases (emailto = admin@openna.com, rulename = "Tripwire Data Files", severity = $(SIG_HI)) { # NOTE: Removing the inode attribute because when Tripwire creates a backup # it does so by renaming the old file and creating a new one (which will # have a new inode number). Leaving inode turned on for keys, which shouldn't # ever change. # NOTE: this rule will trigger on the first integrity check after database # initialization, and each integrity check afterward until a database update # is run, since the database file will not exist before that point. $(TWDB) -> $(Dynamic) -i; $(TWPOL)/tw.pol -> $(SEC_BIN) -i; $(TWBIN)/tw.cfg -> $(SEC_BIN) -i; $(TWLKEY)/$(HOSTNAME)-local.key -> $(SEC_BIN) ; $(TWSKEY)/site.key -> $(SEC_BIN) ; #don't scan the individual reports $(TWREPORT) -> $(Dynamic) (recurse=0); } # These files are critical to a correct system boot. (emailto = admin@openna.com, rulename = "Critical system boot files", severity = 100) { /boot -> $(SEC_CRIT) ; !/boot/System.map ; !/boot/module-info ; } # These files change the behavior of the root account (emailto = admin@openna.com, rulename = "Root config files", severity = 100) { /root -> $(SEC_CRIT) ; /root/.bash_history -> $(SEC_LOG) ; } # Commonly accessed directories that should remain static with regards to owner and group (emailto = admin@openna.com, rulename = "Invariant Directories", severity = $(SIG_MED)) { / -> $(SEC_INVARIANT) (recurse = 0); /home -> $(SEC_INVARIANT) (recurse = 0); /etc -> $(SEC_INVARIANT) (recurse = 0); /chroot -> $(SEC_INVARIANT) (recurse = 0); /cache -> $(SEC_INVARIANT) (recurse = 0); } (emailto = admin@openna.com, rulename = "Shell Binaries") { /bin/bsh -> $(SEC_BIN); /bin/csh -> $(SEC_BIN); /bin/sh -> $(SEC_BIN); } # Rest of critical system binaries (emailto = admin@openna.com, rulename = "OS executables and libraries", severity = $(SIG_HI)) { /bin -> $(ReadOnly) ; /lib -> $(ReadOnly) ; } # Local files (emailto = admin@openna.com, rulename = "User binaries", severity = $(SIG_MED)) { /sbin -> $(SEC_BIN) (recurse = 1); /usr/sbin -> $(SEC_BIN) (recurse = 1); /usr/bin -> $(SEC_BIN) (recurse = 1); } # Temporary directories (emailto = admin@openna.com, rulename = "Temporary directories", recurse = false, severity = $(SIG_LOW)) { /usr/tmp -> $(SEC_INVARIANT); /var/tmp -> $(SEC_INVARIANT); /tmp -> $(SEC_INVARIANT); } # Libraries (emailto = admin@openna.com, rulename = "Libraries", severity = $(SIG_MED)) { /usr/lib -> $(SEC_BIN); } # Include (emailto = admin@openna.com, rulename = "OS Development Files", severity = $(SIG_MED)) { /usr/include -> $(SEC_BIN); } # Shared (emailto = admin@openna.com, rulename = "OS Shared Files", severity = $(SIG_MED)) { /usr/share -> $(SEC_BIN); } # Kernel headers files (emailto = admin@openna.com, rulename = "Kernel Headers Files", severity = $( SIG_HI)) { /usr/src/linux-2.2.14 -> $(SEC_BIN); } # setuid/setgid root programs (emailto = admin@openna.com, rulename = "setuid/setgid", severity = $(SIG_HI)) { /bin/su -> $(SEC_SUID); /sbin/pwdb_chkpwd -> $(SEC_SUID); /sbin/dump -> $(SEC_SUID); /sbin/restore -> $(SEC_SUID); /usr/bin/at -> $(SEC_SUID); /usr/bin/passwd -> $(SEC_SUID); /usr/bin/suidperl -> $(SEC_SUID); /usr/bin/crontab -> $(SEC_SUID); /usr/sbin/sendmail -> $(SEC_SUID); /usr/bin/man -> $(SEC_SUID); /usr/bin/sperl5.00503 -> $(SEC_SUID); /usr/bin/slocate -> $(SEC_SUID); /usr/sbin/utempter -> $(SEC_SUID); /sbin/netreport -> $(SEC_SUID); } (emailto = admin@openna.com, rulename = "Configuration Files") { /etc/hosts -> $(SEC_CONFIG); /etc/inetd.conf -> $(SEC_CONFIG); /etc/initlog.conf -> $(SEC_CONFIG); /etc/inittab -> $(SEC_CONFIG); /etc/resolv.conf -> $(SEC_CONFIG); /etc/syslog.conf -> $(SEC_CONFIG); } (emailto = admin@openna.com, rulename = "Security Control") { /etc/group -> $(SEC_CRIT); /etc/security/ -> $(SEC_CRIT); /lib/security/ -> $(SEC_CRIT); /var/spool/cron -> $(SEC_CRIT); } (emailto = admin@openna.com, rulename = "Login Scripts") { /etc/csh.login -> $(SEC_CONFIG); /etc/profile -> $(SEC_CONFIG); } # These files change every time the system boots (emailto = admin@openna.com, rulename = "System boot changes", severity = $(SIG_HI)) { /dev/log -> $(Dynamic) ; /dev/cua0 -> $(Dynamic) ; /dev/console -> $(Dynamic) ; /dev/tty2 -> $(Dynamic) ; # tty devices /dev/tty3 -> $(Dynamic) ; # are extremely /dev/tty4 -> $(Dynamic) ; # variable /dev/tty5 -> $(Dynamic) ; /dev/tty6 -> $(Dynamic) ; /dev/urandom -> $(Dynamic) ; /dev/initctl -> $(Dynamic) ; /var/lock/subsys -> $(Dynamic) ; /var/run -> $(Dynamic) ; # daemon PIDs /var/log -> $(Dynamic) ; /etc/ioctl.save -> $(Dynamic) ; /etc/.pwd.lock -> $(Dynamic) ; /etc/mtab -> $(Dynamic) ; /lib/modules -> $(Dynamic) ; } # Critical configuration files (emailto = admin@openna.com, rulename = "Critical configuration files", severity = $(SIG_HI)) { /etc/conf.modules -> $(ReadOnly) ; /etc/crontab -> $(ReadOnly) ; /etc/cron.hourly -> $(ReadOnly) ; /etc/cron.daily -> $(ReadOnly) ; /etc/cron.weekly -> $(ReadOnly) ; /etc/cron.monthly -> $(ReadOnly) ; /etc/default -> $(ReadOnly) ; /etc/fstab -> $(ReadOnly) ; /etc/group- -> $(ReadOnly) ; # changes should be infrequent /etc/host.conf -> $(ReadOnly) ; /etc/hosts.allow -> $(ReadOnly) ; /etc/hosts.deny -> $(ReadOnly) ; /etc/lilo.conf -> $(ReadOnly) ; /etc/logrotate.conf -> $(ReadOnly) ; /etc/pwdb.conf -> $(ReadOnly) ; /etc/securetty -> $(ReadOnly) ; /etc/sendmail.cf -> $(ReadOnly) ; /etc/protocols -> $(ReadOnly) ; /etc/services -> $(ReadOnly) ; /etc/rc.d/init.d -> $(ReadOnly) ; /etc/rc.d -> $(ReadOnly) ; /etc/motd -> $(ReadOnly) ; /etc/passwd -> $(ReadOnly) ; /etc/passwd- -> $(ReadOnly) ; /etc/profile.d -> $(ReadOnly) ; /etc/rpc -> $(ReadOnly) ; /etc/sysconfig -> $(ReadOnly) ; /etc/shells -> $(ReadOnly) ; /etc/nsswitch.conf -> $(ReadOnly) ; } # Critical devices (emailto = admin@openna.com, rulename = "Critical devices", severity = $(SIG_HI), recurse = false) { /dev/kmem -> $(Device) ; /dev/mem -> $(Device) ; /dev/null -> $(Device) ; /dev/zero -> $(Device) ; /proc/devices -> $(Device) ; /proc/net -> $(Device) ; /proc/tty -> $(Device) ; /proc/sys -> $(Device) ; /proc/cpuinfo -> $(Device) ; /proc/modules -> $(Device) ; /proc/mounts -> $(Device) ; /proc/dma -> $(Device) ; /proc/filesystems -> $(Device) ; /proc/ide -> $(Device) ; /proc/interrupts -> $(Device) ; /proc/ioports -> $(Device) ; /proc/scsi -> $(Device) ; /proc/kcore -> $(Device) ; /proc/self -> $(Device) ; /proc/kmsg -> $(Device) ; /proc/stat -> $(Device) ; /proc/ksyms -> $(Device) ; /proc/loadavg -> $(Device) ; /proc/uptime -> $(Device) ; /proc/locks -> $(Device) ; /proc/version -> $(Device) ; /proc/meminfo -> $(Device) ; /proc/cmdline -> $(Device) ; /proc/misc -> $(Device) ; } Tip : This is an example policy file we provide you; of course, you must modify this file to fit your system files and specific needs. 2. Once you are ready to use your policy file for the first time, install it with the following command: [root@deep] /#twadmin --create-polfile /usr/TSS/policy/twpol.txt Please enter your site passphrase: Wrote policy file: /usr/TSS/policy/tw.pol ----------------------------------------------------------------------------- 17.5. Securing Tripwire for Linux It is important to make sure that the integrity of the system you are running has not been already compromised. For maximum confidence in your baseline database, you should generate operating system and application files from a clean installation and original media. Also, it is recommended that you delete the plain text copy of the Tripwire configuration file named twcfg.txt located under the /usr/bin directory to hide the location of Tripwire's files and prevent anyone from creating a second, or alternate, configuration file. To delete the plain text copy of the tripwire configuration file, use the following command: [root@deep] /#rm -f /usr/bin/twcfg.txt Further documentation for more details, there are several man pages you can read: siggen(8) - signature gathering routine for Tripwire tripwire(8) - a file integrity checker for UNIX systems twadmin(8) - Tripwire administrative and utility tool twconfig(4) - Tripwire configuration file reference twfiles(5) - overview of files used by Tripwire and file backup process twintro(8) - introduction to Tripwire software twpolicy(4) - Tripwire policy file reference twprint(8) - Tripwire database and report printer ----------------------------------------------------------------------------- 17.5.1. Often used Commands The commands listed below are some that we use often in our regular use, but many more exist. Check the man page for more details. Creating the database for the first time; once your policy file has been installed, it is time to build and initialize your database of file system objects, based on the rules from your policy file. This database will serve as the baseline for later integrity checks. The syntax for Database Initialization mode is: [root@deep] /#tripwire --init To initialize your database file, use the following command: [root@deep] /#tripwire --init Please enter your local passphrase: Parsing policy file: /usr/TSS/policy/tw.pol Generating the database... *** Processing Unix File System *** Wrote database file: /usr/TSS/db/deep.openna.com.twd The database was successfully generated. Tip : When this command has executed, the database is ready and you can check system integrity and review the report file. ----------------------------------------------------------------------------- 17.6. Integrity or Interactive Check Mode Tripwire has a feature called Integrity Check Mode. Now that our database has been built, we can run this feature to compare the current file system objects with their properties as recorded in the Tripwire database. All violations of files will be printed to stdout, the report-generated file will be saved and can later be accessed by the twprint utility. The syntax for integrity check mode is: [root@deep] /#tripwire --check To run the integrity check mode, use the command: [root@deep] /#tripwire --check Tripwire can also be run in Interactive Check Mode. In this mode you can automatically update your changes via the terminal. To run in interactive check mode, use the command: [root@deep] /#tripwire --check --interactive An email option exists with Tripwire and allows you to send email. This option will specify that reports be emailed to the recipients designated in the policy file. To run in integrity check mode and send email to the recipient, use the command: [root@deep] /#tripwire --check --email-report Updating the database after an integrity check If you have decided to use the Integrity Check Mode of Tripwire instead of the Interactive Check Mode, you must update the Tripwire database with the Database Update Mode feature. This update process allows you to save time by updating the database without having to regenerate it, and it also enables selective updating, which cannot be done through regeneration. The syntax for database update mode is: [root@deep] /# tripwire --update -r To update the database, use the command: [root@deep] /#tripwire --update -r /usr/TSS/report/deep.openna.com-200001-021854.twr Where -r read the specified report file deep.openna.com-200001-021854.twr. This option is required since the REPORTFILE variable in the current configuration file uses $(DATE). Important : In Database Update Mode or Interactive Check Mode, Tripwire software displays the report in your terminal with a ballot box next to each policy violation. You can approve a change to the file system by leaving the x next to each policy violation or remove the x from the ballot box and the database will not be updated with the new value(s) for that object. After you exit the editor and provide the local pass phrase, Tripwire software will update and save your changes. Updating the policy file Some times you want to change the rules in your policy file to reflect new file locations or policy rules. A special command exists to do the work and update the database without requiring a complete re-initialization of the policy file. This can save a significant amount of time and preserves security by keeping the policy file synchronized with the database it uses. The syntax for policy update mode is: [root@deep] /#tripwire --update-policy /path/to/new/policy/file To update the policy file, use the command: [root@deep] /#tripwire --update-policy /usr/TSS/policy/newtwpol.txt The policy Update mode runs with the --secure-mode high option by default. You may encounter errors when running with this option if the file system has changed since the last database update, and if the changes cause a violation in the new policy. After determining that all of the violations reported in high security mode are authorized, you can update the policy file in low security mode to solve this situation: To update the policy file in low security mode, use the command: [root@deep] /#tripwire --update-policy --secure-mode low /usr/TSS/policy/newtwpol.txt ----------------------------------------------------------------------------- 17.7. Installed files These are the files Installed by Tripwire: /usr/TSS /usr/TSS/policy/tw.pol /usr/man/man5 /usr/bin /usr/TSS/policy/twpol.txt.bak /usr/man/man5/ twfiles.5 /usr/bin/siggen /usr/TSS/report /usr/man/man8 /usr/bin/twprint /usr/TSS/db /usr/man/man8/ siggen.8 /usr/bin/twadmin /usr/TSS/key /usr/man/man8/ tripwire.8 /usr/bin/tripwire /usr/TSS/key/site.key /usr/man/man8/ twadmin.8 /usr/bin/twcfg.txt /usr/TSS/key/ /usr/man/man8/ deep.openna.com-local.key twintro.8 /usr/bin/tw.cfg /usr/man /usr/man/man8/ twprint.8 /usr/TSS/policy /usr/man/man4 /usr/README /usr/TSS/policy/ /usr/man/man4/twconfig.4 /usr/Release_Notes policyguide.txt /usr/TSS/policy/twpol.txt /usr/man/man4/twpolicy.4 /usr/License.txt ----------------------------------------------------------------------------- Chapter 18. Linux Tripwire ASR 1.3.1 Tripwire ASR 1.3.1 is the Academic Source Release (ASR) of Tripwire software. Personally, I prefer the 1.3.1 version of the software rather than the 2.2.1 version because it can compile and be installed without any compatibility problems on all versions of Linux systems. ----------------------------------------------------------------------------- 18.1. Install, Compile and Optimize +---------------------------------------------------------------------------+ | As explained in the [Tripwire ASR goals]: | | | | With the advent of increasingly sophisticated and subtle account | | break-ins on Unix systems, the need for tools to aid in the detection of | | unauthorized modification of files becomes clear. Tripwire is a tool that | | aids system administrators and users in monitoring a designated set of | | files for any changes. Used with system files on a regular (e.g., daily) | | basis, Tripwire can notify system administrators of corrupted or tampered | | files, so damage control measures can be taken in a timely manner. | +---------------------------------------------------------------------------+ Tripwire is a file and directory integrity checker, a utility that compares a designated set of files and directories against information stored in a previously generated database. Any differences are flagged and logged, including added or deleted entries. When run against system files on a regular basis, any changes in critical system files will be spotted -- and appropriate damage control measures can be taken immediately. With Tripwire, system administrators can conclude with a high degree of certainty that a given set of files remain free of unauthorized modifications if Tripwire reports no changes. These installation instructions assume:   *  Commands are Unix-compatible.   *  The source path is /var/tmp -other paths are possible.   *  Installations were tested on Red Hat Linux 6.1 and 6.2.   *  All steps in the installation will happen in super-user account root.   *  Tripwire version number is 1.3.1-1 These are the package(s) required and Tripwire Homepage: http://www.tripwiresecurity.com/ You must be sure to download: Tripwire-1.3.1-1.tar.gz You need to decompress the Tarballs, It is a good idea to make a list of files on the system before you install it, and one afterwards, and then compare them using diff to find out what file it placed where. Simply run find /* > Tripwire1 before and find /* > Tripwire2 after you install the tarball, and use diff Tripwire1 Tripwire2 > Tripwire-Installed to get a list of what changed. [root@deep] /# cp Tripwire-version.tar.gz /var/tmp [root@deep] /# cd /var/tmp [root@deep ]/tmp# tar xzpf Tripwire-version.tar.gz Move into the new Tripwire directory and Edit the utils.c file (vi +462 src /utils.c) and change the line: else if (iscntrl(*pcin)) { To read: else if (!(*pcin & 0x80) && iscntrl(*pcin)) { Edit the config.parse.c file, vi +356 src/config.parse.c and change the line: rewind(fpout); To read: else { rewind(fpin); } Edit the config.h file, vi +106 include/config.h and change the line: #define CONFIG_PATH "/usr/local/bin/tw" #define DATABASE_PATH "/var/tripwire" To read: #define CONFIG_PATH "/etc" #define DATABASE_PATH "/var/spool/tripwire" Edit the config.h file, vi +165 include/config.h and change the line: #define TEMPFILE_TEMPLATE "/tmp/twzXXXXXX" To read: #define TEMPFILE_TEMPLATE "/var/tmp/.twzXXXXXX" Edit the config.pre.y file vi +66 src/config.pre.y and change the line: #ifdef TW_LINUX To read: #ifdef TW_LINUX_UNDEF Edit the Makefile, vi +13 Makefile and change the line: DESTDIR = /usr/local/bin/tw To read: DESTDIR = /usr/sbin DATADIR = /var/tripwire To read: DATADIR = /var/spool/tripwire LEX = lex To read: LEX = flex CC=gcc To read: CC=egcs CFLAGS = -O To read: CFLAGS = -O9 -funroll-loops -ffast-math -malign-double -mcpu=pentiumpro -march=pentiumpro -fomit-frame-pointer -fno-exceptions [root@deep ]/tw_ASR_1.3.1_src# make [root@deep ]/tw_ASR_1.3.1_src# make install [root@deep ]/tw_ASR_1.3.1_src# chmod 700 /var/spool/tripwire/ [root@deep ]/tw_ASR_1.3.1_src# chmod 500 /usr/sbin/tripwire [root@deep ]/tw_ASR_1.3.1_src# chmod 500 /usr/sbin/siggen [root@deep ]/tw_ASR_1.3.1_src# rm -f /usr/sbin/tw.config   *  The above commands make and make install will configure the software to ensure your system has the necessary functionality and libraries to successfully compile the package, compile all source files into executable binaries, and then install the binaries and any supporting files into the appropriate locations.   *  The chmod command will change the default mode of tripwire directory to be 700 drwx------ only readable, writable, and executable by the super-user root. It will make the binary /usr/sbin/tripwire only readable, and executable by the super-user root -r-x------ and finally make the siggen program under /usr/sbin directory only executable and readable by root.   *  The rm command as used above will remove the file tw.config under /usr/ sbin. We don't need this file since we will create a new one under /etc directory later. Do Cleanup later: [root@deep] /# cd /var/tmp [root@deep ]/tmp# rm -rf tw_ASR_version/ Tripwire-version.tar.gz The rm command as used above will remove all the source files we have used to compile and install Tripwire. It will also remove the Tripwire compressed archive from the /var/tmp directory. ----------------------------------------------------------------------------- 18.2. Configurations Note : All the configuration files required for each software described in this book has been provided by us as a gzipped file, floppy.tgz for your convenience. This can be downloaded from this web address: http:// www.openna.com/books/floppy.tgz You can unpack this to any location on your local machine, say for example /tmp, assuming you have done this your directory structure will be /tmp/floppy. Within this floppy directory each configuration file has its own directory for respective software. For example Tripwire-1.3.1. configuration file are organised like this: total 8 -rwx------ 1 harrypotter harrypotter 504 Jun 8 13:00 tripwire.verify* -rw------- 1 harrypotter harrypotter 611 Jun 8 13:00 tw.config You can either cut and paste this directly if you are faithfully following our instructions from the begining or manually edit these to modify to your needs. This facility is there though as a convenience but please don't forget ultimately it will be your responsibility to check, verify, etc. before you use them whether modified or as it is. To run Tripwire, the following files are required and must be created or copied to their appropriate directories on your server. 1. Copy the tw.config file to the /etc directory. 2. Copy the tripwire.verify script to the /etc/cron.daily directory. ----------------------------------------------------------------------------- 18.3. Configure the /etc/tw.config file The /etc/tw.config file is the Tripwire configuration file where you decide and set which system files and directories that you want monitored. Note that extensive testing and experience are necessary when editing this file before you get working file reports. The following is a working example from where you can start you own customization. 1. Create the tw.config file, touch /etc/tw.config and add in this file all files and directories that you want monitored. The format of the configuration file is described in its header and in the man page tw.config(5): # Gerhard Mourani: gmourani@videotron.ca # last updated: 1999/11/12 # First, root's "home" /root R !/root/.bash_history / R # OS itself /boot/vmlinuz R # critical boot resources /boot R # Critical directories and files /chroot R /etc R /etc/inetd.conf R /etc/nsswitch.conf R /etc/rc.d R /etc/mtab L /etc/motd L /etc/group R /etc/passwd L # other popular filesystems /usr R /usr/local R /dev L-am /usr/etc R # truncate home =/home R # var tree =/var/spool L /var/log L /var/lib L /var/spool/cron L !/var/lock # unusual directories =/proc E =/tmp =/mnt/cdrom =/mnt/floppy 2. Now, for security reasons, change the mode of this file to be 0600 with the following command: [root@deep] /# chmod 600 /etc/tw.config ----------------------------------------------------------------------------- 18.4. Configure the /etc/cron.daily/tripwire.verify script The tripwire.verify file is a small script executed by the crond program of your server each day to scan your hard disk for possible changed files or directories and mail the results to the system administrator. This script will automate the procedure of integrity checking for you. If you intend to automate this task, follow the simple steps below. 1. Create the tripwire.verify script file, touch /etc/cron.daily/ tripwire.verify and add in this script: #!/bin/sh /usr/sbin/tripwire -loosedir -q | (cat < File: '/root/tmp/firewall' ---> Update entry? [YN(y)nh?] Note : In interactive mode, Tripwire first reports all added, deleted, and changed files, then allows the user to update the entry in the database. ----------------------------------------------------------------------------- 18.6. Run Tripwire in Database Update Mode Running Tripwire in Database Update Mode mixed with the tripwire.verify script file that mails the results to the system administrator, will reduce the time of scanning the system. Instead of running Tripwire in Interactive Checking Mode and waiting for the long scan to finish, the script file tripwire.verify will scan the system and report via mail the result, then you run Tripwire in Database Update Mode and update only single files or directories that has changed. Example 18-1. Usage of Tripwire If a single file has changed, you can: [root@deep] /# tripwire -update /etc/newly.installed.file Or, if an entire set of files or directories has changed, you can run: [root@deep] /# tripwire -update /usr/lib/Package_Dir In either case, Tripwire regenerates the database entries for every specified file. A backup of the old database is created in the ./databases directory. These are Some possible uses of Tripwire software 1. Check the integrity of your files system. 2. Get a list of new installed or removed files on your system. ----------------------------------------------------------------------------- 18.6.1. Installed Files These are the files Installed by the software TripWire ASR on your system: /etc/cron.daily/tripwire.verify /etc/tw.config /usr/man/man5/tw.config.5 /usr/man/man8/siggen.8 /usr/man/man8/tripwire.8 /usr/sbin/tripwire /usr/sbin/siggen /var/spool/tripwire /var/spool/tripwire/tw.db_TEST ----------------------------------------------------------------------------- 18.6.1.1. Alternatives to Tripwire These are some of the alternatives to Tripwire: ViperDB ViperDB Homepage: http://www.resentment.org/projects/viperdb/ FCHECK FCHECK Homepage:http://sites.netscape.net/fcheck/fcheck.html Sentinel Sentinel Homepage:http://zurk.netpedia.net/zfile.html ----------------------------------------------------------------------------- Chapter 19. Software -Securities/Management & Limitation Encryption of data sources is an invaluable feature that gives us a high degree of confidentiality for our work. A tool like GnuPG does much more than just encryption of mail messages. It can be used for all kinds of data encryptions, and its utilization can only be stopped by the imagination. GnuPG RPM package comes already installed on you computer, but this version is not up to date and it is recommended to install the latest release available to fit our needs and CPU architecture. ----------------------------------------------------------------------------- 19.1. Linux GnuPG +---------------------------------------------------------------------------+ | According to the [official GnuPG README] file: | | | | GnuPG is GNU's tool for secure communication and data storage. It can be | | used to encrypt data and to create digital signatures. It includes an | | advanced key management facility and is compliant with the proposed | | OpenPGP Internet standard as described in RFC2440. Because GnuPG does not | | use any patented algorithm it cannot be compatible with PGP2 versions. | | PGP 2.x uses only IDEA (which is patented worldwide) and RSA (which is | | patented in the United States until Sep 20, 2000). | +---------------------------------------------------------------------------+ These installation instructions assume:   *  Commands are Unix-compatible.   *  The source path is /var/tmp -other paths are possible.   *  Installations were tested on Red Hat Linux 6.1 and 6.2.   *  All steps in the installation will happen in super-user account root.   *  GnuPG version number is 1.0.1 These are the Package(s) you must be sure to download: GnuPG Homepage: http://www.gnupg.org/ Package to download: gnupg-1.0.1.tar.gz You must decompress the tarball to compile, it is a good idea to make a list of files on the system before you install it, and one afterwards, and then compare them using diff to find out what file it placed where. Simply run find /* > GnuPG1 before and find /* > GnuPG2 after you install the tarball, and use diff GnuPG1 GnuPG2 > GnuPG-Installed to get a list of what changed. Decompress the tarball (tar.gz): [root@deep] /# cp gnupg-version.tar.gz /var/tmp [root@deep] /# cd /var/tmp [root@deep ]/tmp# tar xzpf gnupg-version.tar.gz You need to Compile and Optimize, move into the new GnuPG dir and type the following on your terminal: CC="egcs" \ CFLAGS="-O9 -funroll-loops -ffast-math -malign-double -mcpu=pentiumpro -march=pentiumpro -fomit-frame-pointer -fno-exceptions" \ ./configure \ --prefix=/usr \ --enable-shared [root@deep ]/gnupg-1.0.1# make [root@deep ]/gnupg-1.0.1# make check [root@deep ]/gnupg-1.0.1# make install [root@deep ]/gnupg-1.0.1# strip /usr/bin/gpg The make command compiles all source files into executable binaries, The make check will run any self-tests that come with the package finally, the make install command installs the binaries and any supporting files into the appropriate locations. The strip command will reduce the size of the gpg binary for better performance. Cleanup after work [root@deep] /# cd /var/tmp [root@deep ]/tmp# rm -rf gnupg-version/ gnupg-version.tar.gz The rm command as used above will remove all the source files we have used to compile and install GnuPG. It will also remove the GnuPG compressed archive from the /var/tmp directory. ----------------------------------------------------------------------------- 19.2. Often used Commands The commands listed below are some that we use often, but many more exist. Check the man page for more details and information. First of all, we must create a new key-pair (public and private) if this is a first use of the GnuPG software to be able to use its encryption features. 1. To create a new key-pair, use the following command: [root@deep] /# gpg --gen-key gpg (GnuPG) 1.0.1; Copyright (C) 1999 Free Software Foundation, Inc. This program comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions. See the file COPYING for details. gpg: /root/.gnupg: directory created gpg: /root/.gnupg/options: new options file created gpg: you have to start GnuPG again, so it can read the new options file This asks some questions and then starts key generation. 2. We start GnuPG again with the following command: [root@deep] /# gpg --gen-key gpg (GnuPG) 1.0.1; Copyright (C) 1999 Free Software Foundation, Inc. This program comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions. See the file COPYING for details. gpg: /root/.gnupg/secring.gpg: keyring created gpg: /root/.gnupg/pubring.gpg: keyring created Please select what kind of key you want: (1) DSA and ElGamal (default) (2) DSA (sign only) (4) ElGamal (sign and encrypt) Your selection? 1 DSA keypair will have 1024 bits. About to generate a new ELG-E keypair. minimum keysize is 768 bits default keysize is 1024 bits highest suggested keysize is 2048 bits What keysize do you want? (1024) 2048 Do you really need such a large keysize? y Requested keysize is 2048 bits Please specify how long the key should be valid. 0 = key does not expire = key expires in n days w = key expires in n weeks m = key expires in n months y = key expires in n years Key is valid for? (0) 0 correct (y/n)? y You need a User-ID to identify your key; the software constructs the user id from Real Name, Comment and Email Address in this form: "Heinrich Heine (Der Dichter) " Real name: Gerhard Mourani Email address: gmourani@videotron.ca Comment: [Press Enter] You selected this USER-ID: "Gerhard Mourani " Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? o You need a Passphrase to protect your secret key. We need to generate a lot of random bytes. It is a good idea to perform some other action (type on the keyboard, move the mouse, utilize the disks) during the prime generation; this gives the random number generator a better chance to gain enough entropy. +++++..+++++++++++++++..+++++.++++++++++++++++++++++++++++++++++++++++..+++++++ +++.+++++++++++++++++++++++++.+++++++++++++++...+++++++++++++++++++++++++.+++++ ..+++++>+++++...+++++++++++++++>+++++.......>+++++.......>+++++................ ..........+++++^^^^ public and secret key created and signed. A new key-pair is created (secret and public key) in the root home directory ~/root. ----------------------------------------------------------------------------- 19.3. Importing keys Once our own key-pair is created, we can begin to put into our public keyring database of all keys we have from some trusted third partly in order to be able to use his/her keys for future encryption and authentication communication. To import Public Keys to your keyring, use the following command: [root@deep] /# gpg --import Example 19-1. Importing using gpg [root@deep] /# gpg --import redhat2.asc gpg: key DB42A60E: public key imported gpg: /root/.gnupg/trustdb.gpg: trustdb created gpg: Total number processed: 1 gpg: imported: 1 The above command will append all new keys to our keyring database and will update all already existing keys. It is important to note that GnuPG does not import keys that are not self-signed. In the above example we import the Public Key file redhat2.asc from the company Red Hat Linux, downloadable from the Red Hat Internet site, into our keyring. ----------------------------------------------------------------------------- 19.3.1. Key signing When you import keys into your public keyring database and are sure that trusted third party is really the person they claim, you can start signing his/her keys. Signing a key certifies that you know the owner of the keys. To sign a key for the company RedHat that we have added on our keyring above, use the following command: [root@deep] /# gpg --sign-key Example 19-2. Signing key [root@deep] /# gpg --sign-key RedHat pub 1024D/DB42A60E created: 1999-09-23 expires: never trust: -/q sub 2048g/961630A2 created: 1999-09-23 expires: never (1) Red Hat, Inc pub 1024D/DB42A60E created: 1999-09-23 expires: never trust: -/q Fingerprint: CA20 8686 2BD6 9DFC 65F6 ECC4 2191 80CD DB42 A60E Red Hat, Inc Are you really sure that you want to sign this key with your key: "Gerhard Mourani " Really sign? y You need a passphrase to unlock the secret key for user: "Gerhard Mourani " 1024-bit DSA key, ID E92D6C97, created 1999-12-30 Enter passphrase: Note : You should only sign a key as being authentic when you are Absolutely sure that the key is really authentic! You should never sign a key based on any assumption. ----------------------------------------------------------------------------- 19.4. Encrypt and decrypt After installing, importing, signing and configuring everything in the way that we want, we can start on encrypting and decrypting our work. To encrypt and sign data for the user RedHat that we have added on our keyring above, use the following command: [root@deep] /# gpg -sear RedHat Example 19-3. Encrypting [root@deep] /# gpg -sear RedHat message-to-RedHat.txt You need a passphrase to unlock the secret key for user: "Gerhard Mourani (Open Network Architecture) " 1024-bit DSA key, ID BBB4BA9B, created 1999-10-26 Enter passphrase: Of the arguments passed, The s is for signing To avoid the risk that somebody else claims to be you, it is very useful to sign everything you encrypt,   *  e for encrypting,   *  a to create ASCII armored output .asc ready for sending by mail,   *  r to encrypt the user id name   *  is the message you want to encrypt. To decrypt data, use the following command: [root@deep] /# gpg -d Example 19-4. Decrypting [root@deep] /# gpg -d message-to-Gerhard.asc You need a passphrase to unlock the secret key for user: "Gerhard Mourani (Open Network Architecture) " 2048-bit ELG-E key, ID 71D4CC44, created 1999-10-26 (main key ID BBB4BA9B) Enter passphrase: Where   *  -d is for decrypting   *  is the message you want to decrypt. It is important that the public key of the sender of the message we want to decrypt be in our public keyring database. or of course nothing will work. ----------------------------------------------------------------------------- 19.4.1. Exporting your public key You can spread your wings by exporting and distributing your public key to the world. This can be done by publishing it on your homepage, through an available key server on the Internet, or any other available method. GnuPG has some useful options to help you publish your public keys. To extract your public key in ASCII armored output, use the following command: [root@deep] /# gpg --export --armor > Public-key.asc where   *  --export is for extracting your Public-key from your pubring encrypted file,   *  --armor is to create ASCII armored output that you can mail, publish or put it on a web page   *  > Public-key.asc is to put the result in a file that you've named Public-key.asc. You need to Check the signature, once you have extracted your public key and exported it, everyone who knows or gets your public key should be able to check whether encrypted data from you is also really signed by you. To check the signature of encrypted data, use the following command: [root@deep] /# gpg --verify The --verify option will check the signature where is the encrypted data/file you want to verify. Some possible uses of GnuPG software 1. Send encrypted mail massage. 2. Encrypt backup files before transmission over the network. 3. Encrypt individual sensitive files i.e. a file that handle all your passwords. +-------------------------------+ | Installed files | | | | /usr/bin/gpg | | /usr/lib/gnupg | | /usr/lib/gnupg/rndunix | | /usr/lib/gnupg/rndegd | | /usr/lib/gnupg/tiger | | /usr/man/man1/gpg.1 | | /usr/share/gnupg | | /usr/share/gnupg/options.skel | +-------------------------------+ ----------------------------------------------------------------------------- Chapter 20. Set Limits using Qouta 20.1. Qouta Quota is a system administration tools for monitoring and limiting users and/or groups disk usage, per file system. Two features of disk storage with quota are available to set limits:   *  The first is the number of inodes number of files a user or a group of users may possess.   *  The second is the number of disk blocks amount of space in kilobytes that may be allocated to a user or a group of users. With quota, the users are forced by the system administrator to not consume unlimited disk space on a system. This program is handled on per user, per file system basis and must be set for each file system separately. The first thing you need to do is ensure that your kernel has been built with Quota support enabled. In the 2.2.14 kernel version you need ensure that you have answered Y to the following questions: Filesystems Quota support (CONFIG_QUOTA) [N/y/?] Y Tip : If you have followed the Linux Kernel chapter in this book and have recompiled your kernel, the option Quota support shown above is already set. ----------------------------------------------------------------------------- 20.1.1. Modify the /etc/fstab file The /etc/fstab file contains information about the various file systems installed on your Linux server. Quota must be enabled in the fstab file before you can use it. Since Quota must be set for each file system separately, and because in the fstab file, each file system is described on a separate line, quota must be set on each of the separate lines in the fstab for which you want to enable quota support. With the program quota, depending on your intentions, needs, etc, you can enable quota only for users, groups or both users and groups. For all examples below, we'll use the /home directory on the /dev/sda6 partition and shows you the three possibilities. +-------------------------------------------------------------------------------------------------------------+ | Possibility 1 | | | | To enable user quota support on a specific file system, edit your fstab file vi /etc/fstab and add the | | usrquota option to the fourth field after the word defaults or any other options you may have set for this | | specific file system. | | | | | | Example 20-1. usrquota | | | | change: | | /dev/sda6 /home ext2 defaults 1 2 (1) | | /dev/sda6 /home ext2 nosuid,nodev 1 2 (2) | | | | | | (1) as an example: the word defaults | | (2) as an example: any other options you have set | | | | To read: | | /dev/sda6 /home ext2 defaults,usrquota 1 2 | | /dev/sda6 /home ext2 nosuid,nodev,usrquota 1 2 | | | +-------------------------------------------------------------------------------------------------------------+ +-------------------------------------------------------------------------------------------------------------+ | Possibility 2 | | | | To enable group quota support on a file system, edit your fstab file vi /etc/fstab and add grpquota to the | | fourth field after the word defaults or any other options you may have set for this specific file system. | | | | | | Example 20-2. grpquota | | | | change: | | /dev/sda6 /home ext2 defaults 1 2 (1) | | /dev/sda6 /home ext2 nosuid,nodev 1 2 (2) | | | | | | (1) as an example: the word defaults | | (2) as an example: any other options you have set | | | | To read: | | /dev/sda6 /home ext2 defaults,grpquota 1 2 | | /dev/sda6 /home ext2 nosuid,nodev,grpquota 1 2 | | | +-------------------------------------------------------------------------------------------------------------+ +----------------------------------------------------------------------------------------------------------------------+ | Possibility 3 | | | | To enable both users quota and group quota support on a file system, edit your fstab file vi /etc/fstab and add | | usrquota,grpquota to the fourth field after the word defaults or any other options you may have set for this | | specific file system. Change: | | /dev/sda6 /home ext2 defaults 1 2 (1) | | /dev/sda6 /home ext2 nosuid,nodev 1 2 (2) | | | | | | (1) as an example: the word defaults | | (2) as an example: any other options you have set | | | | To read: | | /dev/sda6 /home ext2 defaults,usrquota,grpquota 1 2 | | /dev/sda6 /home ext2 nosuid,nodev,usrquota,grpquota 1 2 | | | +----------------------------------------------------------------------------------------------------------------------+ ----------------------------------------------------------------------------- 20.2. Create of the quota.user and quota.group After the modification of your /etc/fstab file, in order for quotas to be established on a file system, the root directory of the file system i.e. / home in our example must contain a file, owned by root, called quota.user if you want to use user quota, quota.group if you want to use group quota, or both if you want to use users and group quota. 1. Create the quota.user and/or quota.group files, as root go to the root of the partition you wish to enable quota i.e. /home doing: [root@deep] /# touch /home/quota.user [root@deep] /# touch /home/quota.group [root@deep] /# chmod 600 /home/quota.user [root@deep] /# chmod 600 /home/quota.group The touch command will create new empty files under the home directory named quota.user and quota.group. The chmod command will set the mode of these files to be read-write only by the super-user root. Important : Both quota record files, quota.user and quota.group, should be owned by root, with read-write permission for root and none for anybody else. 2. Now we must initialize the files quota.user and quota.group in the root directory of the file system in order to not receive an error messages about quota during the reboot of our server. To initialize quota.user and /or quota.group files, use the following commands: [root@deep] /# edquota -u wahib [root@deep] /# edquota -g wahib The steps above are necessary just to initialize the files quota.user and /or quota.group; the command edquota -u will edit the quota for the user wahib and -g will edit the quota for the group wahib. Note that you must edit an existing UID/GID on your system to initialize the files successfully. 3. After you have finished setting the appropriate options for your quota program in the /etc/fstab file, and created and initialized the quota.users, and/or quota.group files, you must reboot the system for the changes you have made in the /etc/fstab file and/or the files quota.user, quota.group to take effect. To reboot your system, use the following command: [root@deep] /# reboot After your system has been rebooted you can assign quotas to users or groups of users on your system. This operation is performed with the edquota command. See man page edquota(8) ----------------------------------------------------------------------------- 20.3. edquota The edquota program is a quota editor that creates a temporary file of the current disk quotas used by the super-user root to set quotas for users or group of users in the system. The example below shows you how to setup quotas for users or groups on your system. Consider, for example, that you have a user with the login id wahib on your system. The following command opens the editor vi to edit and set quotas for user wahib on each partition that has quotas enabled: 1. To edit and modify quota for user wahib, use the following command: [root@deep] /# edquota -u wahib Quotas for user wahib: /dev/sda6: blocks in use: 6, limits (soft = 0, hard = 0) inodes in use: 5, limits (soft = 0, hard = 0) After the execution of the above command, you will see the following lines related to the user wahib appear on the screen. The blocks in use: display the total number of blocks in kilobytes the user has consumed on a partition. The inodes in use: display the total number of files the user has on a partition. These parameters blocks in use, and inodes in use are controlled and set automatically by the system and you don't need to set or change them. 2. To assign 5MB of quota for user wahib, change the following parameters in the vi editor: Quotas for user wahib: /dev/sda6: blocks in use: 6, limits (soft = 0, hard = 0) inodes in use: 5, limits (soft = 0, hard = 0) To read: Quotas for user wahib: /dev/sda6: blocks in use: 6, limits (soft = 5000, hard = 0) inodes in use: 5, limits (soft = 0, hard = 0) The soft limit (soft =) specifies the maximum amount of disk usage a quota user is allowed to have. The hard limit (hard =) specifies the absolute limit on the disk usage a quota user can't go beyond it. Tip : Take a note that the hard limit value works only when the grace period parameter is set. ----------------------------------------------------------------------------- 20.3.1. The grace period parameter The grace period parameter allow you to set a time limit before the soft limit value is enforced on a file system with quota enabled, see the soft limit above for more information. For example this parameter can be used to warn your users about a new policy that will set a quota of 5MB of disk space in their home directory in 7 days. You can set the 0 days default part of this parameter to any length of time you feel reasonable. The changes of this setting require two steps as follows, in my example I assume 7 days. 1. Edit the default grace period parameter, by using the following command: [root@deep] /# edquota -t Time units may be: days, hours, minutes, or seconds Grace period before enforcing soft limits for users: /dev/sda6: block grace period: 0 days, file grace period: 0 days 2. Modify the grace period to 7 days. Change or set the following parameters in the vi editor: Time units may be: days, hours, minutes, or seconds Grace period before enforcing soft limits for users: /dev/sda6: block grace period: 0 days, file grace period: 0 days To read: Time units may be: days, hours, minutes, or seconds Grace period before enforcing soft limits for users: /dev/sda6: block grace period: 7 days, file grace period: 7 days The command edquota -t edits the soft time limits for each file system with quotas enabled. ----------------------------------------------------------------------------- 20.4. Assign quota for a particular group Consider, for example, you have a group with the group id webusers on your system. The following command takes you into the vi editor to edit quotas for the group webusers on each partition that has quotas enabled: To edit and modify quota for group webusers, use the following command: [root@deep] /# edquota -g webusers Quotas for group webusers: /dev/sda6: blocks in use: 6, limits (soft = 0, hard = 0) inodes in use: 6, limits (soft = 0, hard = 0) The procedure is the same as for assigning quotas for a particular user; as described above, you must modify the parameter of soft = and save your change. ----------------------------------------------------------------------------- 20.4.1. Assign quota for groups of users with the same value The edquota program has a special option -p that assign quotas for groups of users with the same value assigned to an initial user. Assuming that you want to assign users starting at UID 500 on the system the same value as the user wahib, we would first edit and set wahib's quota information, then execute: To assign quota for group of users with the same value, use the following command: [root@deep] /# edquota -p wahib `awk -F: '$3 > 499 {print $1}' /etc/passwd` The edquota program will duplicate the quota that we have set for the user wahib to all users in the /etc/passwd file that begin after UID 499. Further documentation for more details, please consult man pages: edquota(8) - edit user quotas quota(1) - display disk usage and limits quotacheck(8) - scan a file system for disk usages quotactl(2) - manipulate disk quotas quotaon, quotaoff(8) - turn file system quotas on and off repquota(8) - summarize quotas for a file system rquota(3) - implement quotas on remote machines ----------------------------------------------------------------------------- 20.5. Often used Commands The commands listed below are some that we use often, but many more exist. Check the man page for more details and information. Quota. Quota displays users' disk usage and limits on a file system. To display user disk usage and limits, use the command: [root@deep] /# quota -u wahib Disk quotas for user wahib (uid 501): Filesystem blocks quota limit grace files quota limit grace /dev/sda6 6001* 6000 0 none 7 0 0 To display group quotas for the group of which the user is a member, use the command: [root@deep] /# quota -g wahib Disk quotas for group wahib (gid 501): Filesystem blocks quota limit grace files quota limit grace /dev/sda6 5995* 5000 0 none 1 0 0 If the group quota is not set for the user specified, you will receive the following message: Disk quotas for group wahib (gid 501): none Repquota . Repquota produces summarized quota information of the disk usage and quotas for the specified file systems. Also, it prints for each user the current number of files and amount of space used (in kilobytes). Here is a sample output repquota gives you results may vary: [root@deep] /# repquota -a Block limits File limits User used soft hard grace used soft hard grace Roo -- 21 0 0 4 0 0 Named -- 6 0 0 5 0 0 Admin -- 388657 0 0 21 21 0 0 Wahib -- 6001 0 0 7 0 0 Block limits File limits User used soft hard grace used soft hard grace root -- 21 0 0 4 0 0 named -- 6 0 0 5 0 0 admin -- 388657 0 0 2121 0 0 wahib -- 6001 6000 0 none 7 0 0 ----------------------------------------------------------------------------- Chapter 21. Software -Networking Once we have installed all the necessary security software in our Linux server, it's time to finetune the network part of our server. DNS is the MOST important network service for IP networks communication, and for this reason, all Linux client machines should be configured to perform caching functions as a minimum. ----------------------------------------------------------------------------- 21.1. Linux DNS and BIND Server Setting up a caching server for client local machines will reduce the load on the site's primary server. A caching only name server will find the answer to name queries and remember the answer the next time we need it. This will shorten the waiting time the next time significantly. For security reasons, it is very important that DNS doesn't exist between hosts on the corporate network and external hosts; it is far safer to simply use IP addresses to connect to external machines from the corporate network and vice-versa. In our configuration and installation we'll run BIND/DNS as non root-user and in a chrooted environment. We also provide you three different configurations;   *  one for a simple caching name server only client   *  one for a slave secondary server   *  one for a master name server primary server. The simple caching name server configuration will be used for your servers that don't act as a master or slave name server, and the slave and master configurations will be used for your servers that act as a master name server and slave name server. Usually one of your servers acts as master, another one acts as slave and the rest act as simple caching client name server. This is a graphical representation of the DNS configuration we use in this book. We try to show you different settings DNS caching name server   *  Caching Only DNS   *  Master DNS   *  Slave DNS on different servers. A lot of possibilities exist, and depend on your needs, and network architecture. These installation instructions assume   *  Commands are Unix-compatible.   *  The source path is /var/tmp. other paths are possible.   *  Installations were tested on Red Hat Linux 6.1 and 6.2.   *  All steps in the installation will happen in super-user account root.   *  ISC BIND version number is 8.2.2-patchlevel5 These are the Package(s) required: ISC BIND Homepage:http://www.isc.org/ ISC BIND FTP Site: 204.152.184.27 You must be sure to download: bind-contrib.tar.gz, bind-doc.tar.gz, bind-src.tar.gz Before you decompress Tarballs and install, it is a good idea to make a list of files on the system before you install BIND, and one afterwards, and then compare them using diff to find out what file it placed where. Simply run find /* > DNS1 before and find /* > DNS2 after you install the software, and use diff DNS1 DNS2 > DNS-Installed to get a list of what changed. Compile and Decompress the tarball (tar.gz). [root@deep] /# mkdir /var/tmp/bind [root@deep] /# cp bind-contrib.tar.gz /var/tmp/bind/ [root@deep] /# cp bind-doc.tar.gz /var/tmp/bind/ [root@deep] /# cp bind-src.tar.gz /var/tmp/bind/ We create a directory named bind to handle the tar archives and copy them to this new directory. Move into the new bind directory cd /var/tmp/bind and decompress the tar files: [root@deep ]/bind# tar xzpf bind-contrib.tar.gz [root@deep ]/bind# tar xzpf bind-doc.tar.gz [root@deep ]/bind# tar xzpf bind-src.tar.gz ----------------------------------------------------------------------------- 21.2. Configure Configuration files for different services are very specific depending on your needs and your network architecture. People can install DNS Servers at home as a caching-only server, though companies may install it with primary, secondary and caching DNS servers. Note : All the configuration files required for each software described in this book has been provided by us as a gzipped file, floppy.tgz for your convenience. This can be downloaded from this web address: http:// www.openna.com/books/floppy.tgz You can unpack this to any location on your local machine, say for example /tmp, assuming you have done this your directory structure will be /tmp/floppy. Within this floppy directory each configuration file has its own directory for respective software. For example BIND-DNS configuration file are organised like this: total 24 drwxr-xr-x 2 harrypotter harrypotter 4096 Jun 8 13:00 Caching-Only-DNS/ -rw-r--r-- 1 harrypotter harrypotter 484 Jun 8 13:00 Compile-BIND drwxr-xr-x 2 harrypotter harrypotter 4096 Jun 8 13:00 Primary-Master-DNS/ drwxr-xr-x 2 harrypotter harrypotter 4096 Jun 8 13:00 Secondary-Slave-DNS/ -rwx------ 1 harrypotter harrypotter 300 Jun 8 13:00 bind.sh* drwxr-xr-x 3 harrypotter harrypotter 4096 Jun 8 13:00 init.d/ You can either cut and paste this directly if you are faithfully following our instructions from the begining or manually edit these to modify to your needs. This facility is there though as a convenience but please don't forget ultimately it will be your responsibility to check, verify, etc. before you use them whether modified or as it is. To run a caching-only name server, the following files are required and must be created or copied to the appropriate directories on your server. i. Copy the named.conf file to the /etc/ directory. ii. Copy the db.127.0.0 file to the /var/named/ directory. iii. Copy the db.cache file to the /var/named/ directory. iv. Copy the named script file to the /etc/rc.d/init.d/ directory. To run a master name server, the following files are required and must be created or copied to the appropriate directories on your server. i. Copy the named.conf file to the /etc/ directory. ii. Copy the db.127.0.0 file to the /var/named/ directory. iii. Copy the db.cache file to the /var/named/ directory. iv. Copy the db.208.164.186 file to the /var/named/ directory. v. Copy the db.openna file to the /var/named/ directory. vi. Copy the named script file to the /etc/rc.d/init.d/ directory. To run a slave name server, the following files are required and must be created or copied to the appropriate directories on your server. i. Copy the named.conf file to the /etc/ directory. ii. Copy the db.127.0.0 file to the /var/named/ directory. iii. Copy the db.cache file to the /var/named/ directory. iv. Copy the named script file to the /etc/rc.d/init.d/ directory. Tip : You can obtain the configuration files listed over the next few sections on the floppy.tgz archive. Copy the following files from the decompressed floppy.tgz archive to the appropriate places, or copy them directly from this book to the concerned file. ----------------------------------------------------------------------------- 21.3. Caching-only name Server Caching-only name servers are servers not authoritative for any domains except 0.0.127.in-addr.arpa, the localhost. A caching-only name server can look up names inside and outside your zone, as can primary and slave name servers. The difference is that when a caching-only name server initially looks up a name within your zone, it ends up asking one of the primary or slave names servers for your zone for the answer. The necessary files to setup a simple caching name server are: 1. named.conf 2. db.127.0.0 3. db.cache 4. named script To configure the /etc/named.conf file for a simple caching name server, use this for all servers that dont act as a master or slave name server. Setting up a simple caching server for local client machines will reduce the load on the network's primary server. Many users on dialup connections may use this configuration along with bind for such a purpose. Create the named.conf file, touch /etc/named.conf and add the following lines to the file: options { directory "/var/named"; forwarders { 208.164.186.1; 208.164.186.2; };(1) forward only; }; // // a caching only nameserver config zone "." in { type hint; file "db.cache"; }; zone "0.0.127.in-addr.arpa" in { type master; file "db.127.0.0"; }; (1) In the forwarders line, 208.164.186.1 and 208.164.186.2 are the IP addresses of your Primary Master and Secondary Slave DNS server. They can also be the IP addresses of your ISPs DNS server and another DNS server, respectively. Tip : To improve the security of your BIND/DNS server you can stop it from even trying to contact an off-site server if their forwarder is down or doesn't respond. With the forward only option set in your named.conf file, the name server doesn't try to contact other servers to find out information if the forwarder doesn't give it an answer. To configure the /var/named/db.127.0.0 file for a simple caching name server,you can use this configuration for all machines on your network that don't act as a master or slave name server. The db.127.0.0 file covers the loopback network. Create the following files in /var/named/, touch /var/named /db.127.0.0 and add the following lines in the file: $TTL 345600 @ IN SOA localhost. root.localhost. ( 00 ; Serial 86400 ; Refresh 7200 ; Retry 2592000 ; Expire 345600 ) ; Minimum IN NS localhost. 1 IN PTR localhost. Configure the /var/named/db.cache file for a simple caching name server before starting your DNS server. You must take a copy of db.cache file and copy this file to the /var/named/ directory. The db.cache tells your server where the servers for the root zone are. Use the following commands on another Unix computer in your organization to query a new db.cache file for your DNS Server or pick one from your Red Hat Linux CD-ROM source distribution: [root@deep]# dig @.aroot-servers.net . ns > db.cache Don't forget to copy the db.cache file to the /var/named/ directory on your server where you're installing DNS server after retrieving it over the Internet. Tip : Internal addresses like 192.168.1/24 are not included in the DNS configuration files for security reasons. It is very important that DNS doesn't exist between hosts on the corporate network and external hosts. ----------------------------------------------------------------------------- 21.4. Primary master name Server A primary master name server for a zone reads the data for the zone from a file on it's host and are authoritative for that zone.The necessary files to setup a primary master name server are: a. named.conf b. db.127.0.0 c. db.208.164.186 d. db.openna e. db.cache f. named script To configure the /etc/named.conf file for a master name server, use this configuration for the server on your network that acts as a master name server. After compiling DNS, you need to set up a primary domain name for your server. We'll use openna.com as an example domain, and assume you are using IP network address of 208.164.186.0. To do this, add the following lines to your /etc/named.conf. Create the named.conf file touch /etc/ named.conf and add: options { directory "/var/named"; fetch-glue no; (1) recursion no; (2) allow-query { 208.164.186/24; 127.0.0/8; }; (3) allow-transfer { 208.164.186.2; }; (4) transfer-format many-answers; }; // These files are not specific to any zone zone "." in { type hint; file "db.cache"; }; zone "0.0.127.in-addr.arpa" in { type master; file "db.127.0.0"; }; // These are our primary zone files zone "openna.com" in { type master; file "db.openna "; }; zone "186.164.208.in-addr.arpa" in { type master; file "db.208.164.186"; }; (1) (2) The fetch-glue no option can be used in conjunction with the option recursion no to prevent the server's cache from growing or becoming corrupted. Also, disabling recursion puts your name servers into a passive mode, telling it never to send queries on behalf of other name servers or resolvers. A non-recursive name server is very difficult to spoof, since it doesn't send queries, and hence doesn't cache any data. (3) In the allow-query line, 208.164.186/24 and 127.0.0/8 are the IP addresses allowed to ask ordinary questions to the server. (4) In the allow-transfer line, 208.164.186.2 is the IP address allowed to receive zone transfers from the server. You must ensure that only your real slave name servers can transfer zones from your name serve, as the information provided is often used by spammers and IP spoofers. Note : The options recursion no, allow-query, and allow-transfer in the named.conf file above are security features. To configure the /var/named/db.127.0.0 file for a master and slave name server, you can use this configuration file by both a master name server and a slave name server. The db.127.0.0 file covers the loopback network. Create the following files in /var/named/. Create the db.127.0.0 file, touch /var/named/db.127.0.0 and add: ; Revision History: April 22, 1999 - admin@mail.openna.com ; Start of Authority (SOA) records. $TTL 345600 @ IN SOA deep.openna.com. admin.mail.openna.com. ( 00 ; Serial 86400 ; Refresh 7200 ; Retry 2592000 ; Expire 345600 ) ; Minimum ; Name Server (NS) records. NS deep.openna.com. NS mail.openna.com. ; only One PTR record. 1 PTR localhost. To configure the /var/named/db.208.164.186 file for a master name server, Use this configuration for the server on your network that acts as a master name server. The file db.208.164.186 maps host names to addresses. Create the following files in /var/named/. Create the db.208.164.186 file, touch /var/named/db.208.164.186 and add: ; Revision History: April 22, 1999 - admin@mail.openna.com ; Start of Authority (SOA) records. $TTL 345600 @ IN SOA deep.openna.com. admin.mail.openna.com. ( 00 ; Serial 86400 ; Refresh 7200 ; Retry 2592000 ; Expire 345600 ) ; Minimum ; Name Server (NS) records. NS deep.openna.com. NS mail.openna.com. ; Addresses Point to Canonical Names (PTR) for Reverse lookups 1 PTR deep.openna.com. 2 PTR mail.openna.com. 3 PTR www.openna.com. To configure of the /var/named/db.openna file for a master name server, use this configuration for the server on your network that acts as a master name server. The file db.openna maps addresses to host names. Create the following file in /var/named/. Create the db.openna file touch /var/named/db.openna and add: ; Revision History: April 22, 1999 - admin@mail.openna.com ; Start of Authority (SOA) records. $TTL 345600 @ IN SOA deep.openna.com. admin.mail.openna.com. ( 00 ; Serial 86400 ; Refresh 7200 ; Retry 2592000 ; Expire 345600 ) ; Minimum ; Name Server (NS) records. NS deep.openna.com. NS mail.openna.com. ; Mail Exchange (MX) records. MX 0 mail.openna.com. ; Address (A) records. localhost A 127.0.0.1 deep A 208.164.186.1 mail A 208.164.186.2 www A 208.164.186.3 ; Aliases in Canonical Name (CNAME) records. ;www CNAME deep.openna.com. To configure the /var/named/db.cache file for a master and slave name servers Before starting your DNS server you must take a copy of the db.cache file and copy it into the /var/named/ directory. The db.cache tells your server where the servers for the root zone are. Use the following command on another Unix computer in your organization to query a new db.cache file for your DNS Server or pick one from your Red Hat Linux CD-ROM source distribution: [root@deep] /# dig @.aroot-servers.net . ns > db.cache Don't forget to copy the db.cache file to the /var/named/ directory on your server where you're installing DNS server after retrieving it over the Internet. ----------------------------------------------------------------------------- 21.5. Secondary slave name Server The purpose of a slave name server is to share the load with the master server, or handle the entire load if the master server is down. A slave name server loads its data over the network from another name server usually the master name server, but it can load from another slave name server too. This process is called a zone transfer. Necessary files to setup a secondary slave name server are: i. named.conf ii. db.127.0.0 iii. db.cache iv. named script To configure the /etc/named.conf file for a slave name server, use this configuration for the server on your network that acts as a slave name server. You must modify the named.conf file on the slave name server host. Change every occurrence of primary to secondary except for 0.0.127.in-addr.arpa and add a masters line with the IP address of the master server as shown below. Create the named.conf file (touch /etc/named.conf) and add: options { directory "/var/named"; fetch-glue no; recursion no; allow-query { 208.164.186/24; 127.0.0/8; }; allow-transfer { 208.164.186.1; }; transfer-format many-answers; }; // These files are not specific to any zone zone "." in { type hint; file "db.cache"; }; zone "0.0.127.in-addr.arpa" in { type master; file "db.127.0.0"; }; // These are our slave zone files zone "openna.com" in { type slave; file "db.openna"; masters { 208.164.186.1; }; }; zone "186.164.208.in-addr.arpa" in { type slave; file "db.208.164.186"; masters { 208.164.186.1; }; }; This tells the name server that it is a slave for the zone openna.com and should track the version of this zone that is being kept on the host 208.164.186.1. A slave name server doesn't need to retrieve all of its database (db) files over the network because these db files db.127.0.0 and db.cache are the same as on a primary master, so you can keep a local copy of these files on the slave name server. i. Copy the db.127.0.0file from master name server to slave name server. ii. Copy the db.cache file from master name server to slave name server. ----------------------------------------------------------------------------- 21.5.1. /etc/rc.d/init.d/named script Configure your /etc/rc.d/init.d/named script file to start and stop the BIND/DNS daemon on your Server. This configuration script file can by used for all type of name server caching, master or slave. Create the named script file touch /etc/rc.d/init.d/named and add: #!/bin/sh # # named This shell script takes care of starting and stopping # named (BIND DNS server). # # chkconfig: - 55 45 # description: named (BIND) is a Domain Name Server (DNS) \ # that is used to resolve host names to IP addresses. # probe: true # Source function library. . /etc/rc.d/init.d/functions # Source networking configuration. . /etc/sysconfig/network # Check that networking is up. [ ${NETWORKING} = "no" ] && exit 0 [ -f /usr/sbin/named ] || exit 0 [ -f /etc/named.conf ] || exit 0 RETVAL=0 # See how we were called. case "$1" in start) # Start daemons. echo -n "Starting named: " daemon named RETVAL=$? [ $RETVAL -eq 0 ] && touch /var/lock/subsys/named echo ;; stop) # Stop daemons. echo -n "Shutting down named: " killproc named RETVAL=$? [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/named echo ;; status) /usr/sbin/ndc status exit $? ;; restart) $0 stop $0 start ;; reload) /usr/sbin/ndc reload exit $? ;; probe) # named knows how to reload intelligently; we don't want linuxconf # to offer to restart every time /usr/sbin/ndc reload >/dev/null 2>&1 || echo start exit 0 ;; *) echo "Usage: named {start|stop|status|restart}" exit 1 esac exit $RETVAL Now, make this script executable and change its default permissions: [root@deep]# chmod 700 /etc/rc.d/init.d/named Create the symbolic rc.d links for BIND/DNS with the command: [root@deep]# chkconfig --add named The BIND/DNS script will not automatically start the named daemon when you reboot the server. You can change its default by executing the following command: [root@deep]# chkconfig --level 345 named on Start your DNS Server manually with the following command: [root@deep]# /etc/rc.d/init.d/named start Starting named: [ OK ] ----------------------------------------------------------------------------- 21.6. Run ISC BIND/DNS in a chroot jail The main benefit of a chroot jail is that the jail will limit the portion of the file system the DNS daemon program can see to the root directory of the jail. Additionally, since the jail only needs to support DNS, the programs related to ISC BIND/DNS available in the jail can be extremely limited. Most importantly, there is no need for setuid-root programs, which can be used to gain root access and break out of the jail. +---------------------------------------------------------------------------+ | Securing ISC BIND/DNS | | | | This part focuses on preventing ISC BIND/DNS from being used as a point | | of break-in to the system hosting it. Since ISC BIND/DNS performs a | | relatively large and complex function, the potential for bugs that affect | | security is rather high with this software. In fact, there have been | | exploitable bugs in the past that allowed a remote attacker to obtain | | root access to hosts running ISC BIND/DNS. To minimize this risk, ISC | | BIND/DNS can be run as a non-root user, which will limit any damage to | | what can be done as a normal user with a local shell. Of course, this is | | not enough for the security requirements of most DNS servers, so an | | additional step can be taken - that is, running ISC BIND in a chroot | | jail. | | | | DNS in chroot | +---------------------------------------------------------------------------+ Important : The named binary program must be in a directory listed within your PATH environment variable for this to work. For the rest of the documentation, I'll assume the path of your original named program is / usr/sbin/named. The following are the necessary steps to run ISC BIND/DNS software in a chroot jail: We must find the shared library dependencies of named, named is the DNS daemon. These will need to be copied into the chroot jail later. 1. To find the shared library dependencies of named, execute the following command: [root@deep] /# ldd /usr/sbin/named libc.so.6 => /lib/libc.so.6 (0x40017000) /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000) 2. Make a note of the files listed above; you will need these later in our steps. Now we must set up the chroot environment, and create the root directory of the jail. We've chosen /chroot/named because we want to put this on its own separate file system to prevent file system attacks. Early in our Linux installation procedure we created a special partition /chroot for this purpose. 1. [root@deep] /# /etc/rc.d/init.d/named stop (1) (1) Require only if an existing named daemon is running. Shutting down named: [ OK ] [root@deep] /# mkdir -p /chroot/named 2. Next, create the rest of directories as follows: [root@deep] /# mkdir /chroot/named/dev [root@deep] /# mkdir /chroot/named/lib [root@deep] /# mkdir /chroot/named/etc [root@deep] /# mkdir -p /chroot/named/usr/sbin [root@deep] /# mkdir -p /chroot/named/var/run [root@deep] /# mkdir /chroot/named/var/named 3. Now copy the main configuration file, the zone files, the named and the named-xfer programs into the appropriate places in the chroot jail directory: [root@deep] /# cp /etc/named.conf /chroot/named/etc/ [root@deep] /# cd /var/named ; cp -a . /chroot/named/var/named/ [root@deep] /# mknod /chroot/named/dev/null c 1 3 [root@deep] /# chmod 666 /chroot/named/dev/null [root@deep] /# cp /usr/sbin/named /chroot/named/usr/sbin/ [root@deep] /# cp /usr/sbin/named-xfer /chroot/named/usr/sbin/ Important : The owner of the /chroot/named/var/named directory and all files in this directory must be the process name named under the slave server and only the slave server or you wouldn't be able to make a zone transfer. 4. To make the named directory and all its files own by the named process name under the slave server, use the command: [root@deep] /# chown -R named.named /chroot/named/var/named/ Copy the shared libraries identified above to the chrooted lib directory: [root@deep] /# cp /lib/libc.so.6 /chroot/named/lib/ [root@deep] /# cp /lib/ld-linux.so.2 /chroot/named/lib/ Copy the localtime and nsswitch.conf files to the chrooted etc directory so that log entries are adjusted for your local timezone properly: [root@deep] /# cp /etc/localtime /chroot/named/etc/ [root@deep] /# cp /etc/nsswitch.conf /chroot/named/etc/ We must set some files under the /chroot/named/etc directory with the immutable bit enabled for better security: 1. Set the immutable bit on nsswitch.conf file: [root@deep] /# cd /chroot/named/etc/ [root@deep etc]# chattr +i nsswitch.conf 2. Set the immutable bit on named.conf file: [root@deep] /# cd /chroot/named/etc/ [root@deep etc]# chattr +i named.conf A file with the +i attribute cannot be modified, deleted or renamed; no link can be created to this file and no data can be written to it. Only the superuser can set or clear this attribute. Add a new UID and a new GID for running the daemon named if this is not already set. This is important because running it as root defeats the purpose of the jail, and using a different user id that already exists on the system can allow your services to access each others' resources. Check the /etc/ passwd and /etc/group files for a free UID/GID number available. In our example we'll use the number 53 and the name named. [root@deep] /#useradd -c DNS Server -u 53 -s /bin/false -r -d /chroot/named named 2>/dev/null || : ----------------------------------------------------------------------------- 21.7. The syslog daemon We must tell syslogd the syslog daemon program about the new chrooted service, since normally, processes talk to syslogd through /dev/log. As a result of the chroot jail, this won't be possible, so syslogd needs to be told to listen to /chroot/named/dev/log instead of the default dev/log. To do this, edit the syslog startup script file to specify additional places to listen. Edit the syslog script file vi +24 /etc/rc.d/init.d/syslog and change the line: daemon syslogd -m 0 To read: daemon syslogd -m 0 -a /chroot/named/dev/log The default named script file of ISC BIND/DNS starts the daemon named outside the chroot jail. We must change it to start named from the chroot jail. Edit the named script file vi /etc/rc.d/init.d/named and change the lines: 1. [ -f /usr/sbin/named ] || exit 0 To read: [ -f /chroot/named/usr/sbin/named ] || exit 0 2. [ -f /etc/named.conf ] || exit 0 To read: [ -f /chroot/named/etc/named.conf ] || exit 0 3. daemon named To read: daemon /chroot/named/usr/sbin/named -t /chroot/named/ -unamed -gnamed The -t option tells named to start up using the new chroot environment. The -u option specifies the user to run as. The -g option specifies the group to run as. In BIND 8.2 version, the ndc command of ISC BIND/DNS software became a binary file; before, it was a script file, which renders the shipped ndc useless in this setting. To fix it, the ISC BIND/DNS package must be compiled again from source. To do this, in the top level of ISC BIND/DNS source directory. 1. For ndc utility: [root@deep] /# cp bind-src.tar.gz /vat/tmp [root@deep] /# cd /var/tmp/ [root@deep ]/tmp# tar xzpf bind-src.tar.gz [root@deep ]/tmp# cd src [root@deep ]/src# cp port/linux/Makefile.set port/linux/Makefile.set-orig 2. Edit the Makefile.set file, vi port/linux/Makefile.set to make the changes listed below: 'CC=egcs -D_GNU_SOURCE' 'CDEBUG=-O9 -funroll-loops -ffast-math -malign-double -mcpu=pentiumpro -march=pentiumpro -fomit-frame-pointer -fno-exceptions -g 'DESTBIN=/usr/bin' 'DESTSBIN=/chroot/named/usr/sbin' 'DESTEXEC=/chroot/named/usr/sbin' 'DESTMAN=/usr/man' 'DESTHELP=/usr/lib' 'DESTETC=/etc' 'DESTRUN=/chroot/named/var/run' 'DESTLIB=/usr/lib/bind/lib' 'DESTINC=/usr/lib/bind/include' 'LEX=flex -8 -I' 'YACC=yacc -d' 'SYSLIBS=-lfl' 'INSTALL=install' 'MANDIR=man' 'MANROFF=cat' 'CATEXT=$$N' 'PS=ps p' 'AR=ar crus' 'RANLIB=:' 3. The difference between the Makefile we used before and this one is that we modify the DESTSBIN=, DESTEXEC=, and DESTRUN= lines to point to the chrooted directory of BIND/DNS. With this modification, the ndc program knows where to find named. [root@deep ]/src# make clean [root@deep ]/src# make [root@deep ]/src# cp bin/ndc/ndc /usr/sbin/ [root@deep ]/src# cp: overwrite `/usr/sbin/ndc'? y [root@deep ]/src# strip /usr/sbin/ndc We build the binary file, then copy the result of ndc program to /usr/ sbin and overwrite the old one. We dont forget to strip our new ndc binary for better performance. ----------------------------------------------------------------------------- 21.8. Clean-up and Test the new chrooted jail Remove the unnecessary files and directory. [root@deep] /# rm -f /usr/sbin/named [root@deep] /# rm -f /usr/sbin/named-xfer [root@deep] /# rm -f /etc/named.conf [root@deep] /# rm -rf /var/named/ We remove the named and named-xfer binaries from the /usr/sbin directory, since the ones we'll work with now on a daily basis are located under the chroot directory. The same applies for the named.conf file and /var/named directory. We must test the new chrooted jail configuration of our ISC BIND/DNS software. 1. The first thing to do is to restart our syslogd daemon with the following command: [root@deep] /# /etc/rc.d/init.d/syslog restart Shutting down kernel logger: [ OK ] Shutting down system logger: [ OK ] Starting system logger: [ OK ] Starting kernel logger: [ OK ] 2. Now, start the new chrooted jail ISC BIND/DNS with the following command: [root@deep] /# /etc/rc.d/init.d/named start Starting named: [ OK ] 3. Make sure it's running as user named and with the new arguments. To verify that ISC BIND/DNS is running as user named with the new arguments, use the following command: [root@deep] /# ps auxw | grep named named 11446 0.0 1.2 2444 1580 ? S 23:09 0:00 /chroot/named/usr/sbin/named -t /chroot/named/ -unamed -gnamed The first column should be named, which is the UID named daemon is running under. The end of the line should be named -t /chroot/named/ -unamed -gnamed, which are the new arguments. 4. Please dont forget to cleanup: [root@deep] /# rm -rf /var/tmp/src bind-src.tar.gz This will remove the source file and tar archive we used to compile and install ISC BIND/DNS. Further documentation, for more details there are several man pages you can read: dnsdomainname(1) - show the system's DNS domain name dnskeygen(1) - generate public, private, and shared secret keys for DNS Security dnsquery(1) - query domain name servers using resolver named(8) - Internet domain name server DNS hesiod_to_bind [hesiod](3) - Hesiod name server interface library ldconfig(8) - determine run-time link bindings lesskey(1) - specify key bindings for less raw(8) - bind a Linux raw character device mkfifo(1) - make FIFOs named pipes named-bootconf(8) - convert name server configuration files named-xfer(8) - ancillary agent for inbound zone transfers named.conf [named](5) - configuration file for Opcode(3) - Disable named opcodes when compiling perl code dig(1) - send domain name query packets to name servers nslookup(8) - query Internet name servers interactively ndc(8) - name daemon control program ----------------------------------------------------------------------------- 21.9. DNS Administrative Tools The commands listed belows are some that we use often, but many more exist. Check the man pages and documentation for more details and information. dig. The dig command utility domain information groper can be used to update your db.cache file by telling your server where the servers for the root zone are. When the server knows about the location of these zones, it queries a new db.cache from it. The root name servers do not change very often, but they do change. A good practice is to update your db.cache file every month or two. Use the following command to query a new db.cache file for your DNS Server: [root@deep] /# dig @.aroot-servers.net . ns > db.cache Copy the db.cache file to /var/named/ after retrieving it. [root@deep] /# cp db.cache /var/named/ Where @a.root-servers.net is the address of the root server for querying the new db.cache file and db.cache file is the name of your new db.cache file. ndc. The ndc command utility of ISC BIND/DNS allows the system administrator to control interactively via a terminal the operation of a name server. Type ndc on your terminal and then help to see help on different command. [root@deep] /# ndc Type help -or- /h if you need help. ndc> help getpid status stop exec reload [zone] ... reconfig (just sees new/gone zones) dumpdb stats trace [level] notrace querylog qrylog help quit ndc> /e ----------------------------------------------------------------------------- 21.10. DNS Users Tools The commands listed belows are some that we use often, but many more exist. Check the man pages and documentation for more details and information. nslookup. The nslookup program allows the user to query Internet domain name servers interactively or non-interactively. In interactive mode the user can query name servers for information about various hosts and domains, and print a list of hosts in a domain. In non-interactive mode the user can just print the name and request information for a host or domain. Interactive mode has a lot of options and commands; it is recommended that you see the man page for nslookup, or the help under nslookup Interactive mode. To enter under nslookup Interactive mode, use the command: [root@deep] /# nslookup Default Server: deep.openna.com Address: 208.164.186.1 > help $Id: nslookup.help,v 8.4 1996/10/25 18:09:41 vixie Exp $ Commands: (identifiers are shown in uppercase, [] means optional) NAME - print info about the host/domain NAME using default server NAME1 NAME2 - as above, but use NAME2 as server help or ? - print info on common commands; see nslookup(1) for details set OPTION - set an option all - print options, current server and host [no]debug - print debugging information [no]d2 - print exhaustive debugging information To run in non-interactive mode, use the command: [root@deep] /# nslookup www.redhat.com Server: deep.openna.com Address: 208.164.186.1 Non-authoritative answer: Name: www.portal.redhat.com Addresses: 206.132.41.202, 206.132.41.203 Aliases: www.redhat.com Where www.redhat.com is the host name or Internet address of the name server to be looked up. dnsquery. The dnsquery program queries domain name servers via the resolver library calls /etc/resolv.conf. To query domain name servers using resolver, use the command: [root@deep] /# dnsquery Example 21-1. dnsquery [root@deep] /# dnsquery www.redhat.com ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 40803 ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 4, ADDITIONAL: 4 ;; www.redhat.com, type = ANY, class = IN www.redhat.com. 2h19m46s IN CNAME www.portal.redhat.com. redhat.com. 2h18m13s IN NS ns.redhat.com. redhat.com. 2h18m13s IN NS ns2.redhat.com. redhat.com. 2h18m13s IN NS ns3.redhat.com. redhat.com. 2h18m13s IN NS speedy.redhat.com. ns.redhat.com. 1d2h18m8s IN A 207.175.42.153 ns2.redhat.com. 1d2h18m8s IN A 208.178.165.229 ns3.redhat.com. 1d2h18m8s IN A 206.132.41.213 speedy.redhat.com. 2h18m13s IN A 199.183.24.251 Where is the name of the host you want to query. host. The host program looks up host names using DNS. To look up host names using domain server, use the command: [root@deep] /# host Example 21-2. Look up host names [root@deep] /# host redhat.com redhat.com has address 207.175.42.154 Where is either FDQN www.redhat.com, domain names redhat.com, host names www or host numbers 207.175.42.154. To find all of the information about a host maintained by the DNS, use the command: [root@deep] /# host -a Example 21-3. Using host [root@deep] /# host -a redhat.com Trying null domain rcode = 0 (Success), ancount=6 The following answer is not authoritative: The following answer is not verified as authentic by the server: redhat.com 8112 IN NS ns.redhat.com redhat.com 8112 IN NS ns2.redhat.com redhat.com 8112 IN NS ns3.redhat.com redhat.com 8112 IN NS speedy.redhat.com redhat.com 8112 IN A 207.175.42.154 redhat.com 11891 IN SOA ns.redhat.com noc.redhat.com( 2000021402 ;serial (version) 3600 ;refresh period 1800 ;retry refresh this often 604800 ;expiration period 86400 ;minimum TTL ) For authoritative answers, see: redhat.com 8112 IN NS ns.redhat.com redhat.com 8112 IN NS ns2.redhat.com redhat.com 8112 IN NS ns3.redhat.com redhat.com 8112 IN NS speedy.redhat.com Additional information: ns.redhat.com 94507 IN A 207.175.42.153 ns2.redhat.com 94507 IN A 208.178.165.229 ns3.redhat.com 94507 IN A 206.132.41.213 speedy.redhat.com 8112 IN A 199.183.24.251 This option can be used to find all of the information that is maintained by the domain server about this host, in our example redhat.com. To list a complete domain, use the command: [root@deep] /# host -l Example 21-4. List a complete domain [root@deep] /# host -l openna.com openna.com name server deep.openna.com openna.com name server mail.openna.com localhost.openna.com has address 127.0.0.1 deep.openna.com has address 208.164.186.1 mail.openna.com has address 208.164.186.2 www.openna.com has address 208.164.186.3 This option, in the official master file format, will give a complete download of the zone data for the domain name openna.com. This command should be used only if it is absolutely necessary. ----------------------------------------------------------------------------- 21.11. Installed files /etc/rc.d/init.d/named /usr/lib/bind/include/hesiod.h /etc/rc.d/rc0.d/K45named /usr/lib/bind/include/sys /etc/rc.d/rc1.d/K45named /usr/lib/bind/include/net /etc/rc.d/rc2.d/K45named /usr/lib/bind/lib /etc/rc.d/rc3.d/K45named /usr/lib/bind/lib/libbind.a /etc/rc.d/rc4.d/K45named /usr/lib/bind/lib/libbind_r.a /etc/rc.d/rc5.d/K45named /usr/lib/nslookup.help /etc/rc.d/rc6.d/K45named /usr/man/man1/dig.1 /etc/named.conf /usr/man/man1/host.1 /usr/bin/addr /usr/man/man1/dnsquery.1 /usr/bin/nslookup /usr/man/man1/dnskeygen.1 /usr/bin/dig /usr/man/man3/hesiod.3 /usr/bin/dnsquery /usr/man/man3/gethostbyname.3 /usr/bin/host /usr/man/man3/inet_cidr.3 /usr/bin/nsupdate /usr/man/man3/resolver.3 /usr/bin/mkservdb /usr/man/man3/getnetent.3 /usr/lib/bind /usr/man/man3/tsig.3 /usr/lib/bind/include /usr/man/man3/getaddrinfo.3 /usr/lib/bind/include/arpa /usr/man/man3/getipnodebyname.3 /usr/lib/bind/include/arpa/inet.h /usr/man/man5/resolver.5 /usr/lib/bind/include/arpa/nameser.h /usr/man/man5/irs.conf.5 /usr/lib/bind/include/arpa/nameser_compat.h /usr/man/man5/named.conf.5 /usr/lib/bind/include/isc /usr/man/man7/hostname.7 /usr/lib/bind/include/isc/eventlib.h /usr/man/man7/mailaddr.7 /usr/lib/bind/include/isc/misc.h /usr/man/man8/named.8 /usr/lib/bind/include/isc/tree.h /usr/man/man8/ndc.8 /usr/lib/bind/include/isc/logging.h /usr/man/man8/named-xfer.8 /usr/lib/bind/include/isc/heap.h /usr/man/man8/named-bootconf.8 /usr/lib/bind/include/isc/memcluster.h /usr/man/man8/nslookup.8 /usr/lib/bind/include/isc/assertions.h /usr/man/man8/nsupdate.8 /usr/lib/bind/include/isc/list.h /usr/sbin/ndc /usr/lib/bind/include/isc/dst.h /usr/sbin/named /usr/lib/bind/include/isc/irpmarshall.h /usr/sbin/named-xfer /usr/lib/bind/include/netdb.h /usr/sbin/irpd /usr/lib/bind/include/resolv.h /usr/sbin/dnskeygen /usr/lib/bind/include/res_update.h /usr/sbin/named-bootconf /usr/lib/bind/include/irs.h /var/named /usr/lib/bind/include/irp.h   ----------------------------------------------------------------------------- Chapter 22. Software -Server/Mail Network The Sendmail program is one of the most widely used Internet Mail Transport Agents -MTAs in the world. The purpose of an MTA is to send mail from one machine to another, and nothing else. Sendmail is not a client program, which you use to read your e-mail. Instead, it actually moves your email over networks, or the Internet, to where you want it to go. Sendmail has been an easy target for system crackers to exploit in the past, but with the advent of Sendmail version 8, this has become much more difficult. ----------------------------------------------------------------------------- 22.1. Linux Sendmail Server In our configuration and installation we'll provide you two different configurations that you can set up for Sendmail; Central Mail Hub Relay, The Central Mail Hub Relay Server configuration will be used for your server where the assigned task is to send, receive and relay all mail for all local or neighbor client and server mail machines you may have on your network. local or neighbor clients and servers. A local or neighbor client and server refer to all other local server or client machines on your network that run Sendmail and send all outgoing mail to the Central Mail Hub for future delivery. This kind of internal client never receives mail directly via the Internet; Instead, all mail from the Internet for those computers is kept on the Mail Hub server. It is a good idea to run one Central Mail Hub Server for all computers on your network; this architecture will limit the task managements on the server and client machines, and improve the security of your site. You can configure the neighbor Sendmail so that it accepts only mail that is generated locally, thus insulating neighbor machines for easier security. The Gateway server outside the firewall, or part of it acts as a proxy and accepts external mail via its Firewall rules file that is destined for internal delivery from the outside, and forwards it to the Central Mail Hub Server. Also note that the Gateway server is configured like a neighbor Sendmail server to never accept incoming mail from the outside the Internet. Here is a graphical representation of the Sendmail configuration used in this book, with different settings:   *  Central Mail Hub Relay,   *  local or neighbor client and servers on different servers. Lots of possibilities exist, and depends on your need and network architecture. Sendmail configuration examples These installation instructions assume   *  Commands are Unix-compatible.   *  The source path is /var/tmp, other paths are possible.   *  Installations were tested on Red Hat Linux 6.1 and 6.2.   *  All steps in the installation will happen in super-user account root.   *  Sendmail version number is 8.10.1 These are the package(s) you need to download and they are available here Sendmail Homepage: http://www.sendmail.org/ Sendmail FTP Sire: 204.152.184.34 You must be sure to download: sendmail.8.10.1.tar.gz Before you decompress the tarballs, it is a good idea to make a list of files on the system before you install Sendmail, and one afterwards, and then compare them using diff to find out what file it placed where. Simply run find /* > Sendmail1 before and find /* > Sendmail2 after you install the software, and use diff Sendmail1 Sendmail2 > Sendmail-Installed to get a list of what changed. You need to compile, so decompress the tarball (tar.gz). which you have downloaded:d [root@deep] /# cp sendmail.version.tar.gz /var/tmp [root@deep] /# cd /var/tmp [root@deep ]/tmp# tar xzpf sendmail.version.tar.gz Before you compile it is always better to configure to your needs, move into the new Sendmail directory and edit the smrsh.c file vi +77 smrsh/ smrsh.c and change the line: # define CMDDIR "/usr/adm/sm.bin" To read: # define CMDDIR "/etc/smrsh" This modification specifies the default search path for commands runs by smrsh program. It allows us to limit the location where these programs may reside. ----------------------------------------------------------------------------- 22.2. Compile and optimize The Build script of Sendmail uses by default a site configuration file that correspond to your operating system type to get information about definitions for system installation and various compilation values. This file is located under the subdirectory named devtools/OS and if you're running a Linux system, it'll be named Linux. We'll rebuild this site configuration file to suit our Linux system installation and put it in the default devtools/OS sub-directory of the Sendmail source distribution since the Build script will look for the default site configuration file in this directory during compile time of Sendmail. Move into the new Sendmail directory, edit the Linux file, vi devtools/OS/ Linux, and remove all predefined lines then add the following lines inside the file: define(`confENVDEF', `-DPICKY_QF_NAME_CHECK -DXDEBUG=0') define(`confCC', `egcs') define(`confOPTIMIZE', `-O9 -funroll-loops -mcpu=pentiumpro -march=pentiumpro -fomit-frame-pointer -fno-exceptions') define(`confLIBS', `-lnsl') define(`confLDOPTS', `-s') define(`confMANROOT', `/usr/man/man') define(`confMANOWN', `root') define(`confMANGRP', `root') define(`confMANMODE', `644') define(`confMAN1SRC', `1') define(`confMAN5SRC', `5') define(`confMAN8SRC', `8') define(`confDEPEND_TYPE', `CC-M') define(`confNO_HELPFILE_INSTALL) define(`confSBINGRP', `root') define(`confSBINMODE', `6755') define(`confUBINOWN', `root') define(`confUBINGRP', `root') define(`confEBINDIR', `/usr/sbin') This tells Linux file to set itself up for this particular configuration setup with: define(`confENVDEF', `-DPICKY_QF_NAME_CHECK -DXDEBUG=0') This macro option is used primarily to specify code that should either be specially included or excluded. With -DPICKY_QF_NAME_CHECK defined, Sendmail will log an error if the name of the qf file is incorrectly formed and will rename the qf file into a Qf file. The -DXDEBUG=0 argument disables the step of additional internal checking during compile time. define(`confCC', `egcs') This macro option defines the C compiler to use for compilation of Sendmail. In our case we use the egcs C compiler for better optimization. define(`confOPTIMIZE', `-O9 -funroll-loops -mcpu=pentiumpro -march=pentiumpro -fomit-frame-pointer -fno-exceptions') This macro option defines the flags passed to CC for optimization related to our specific CPU architecture. define(`confLIBS', `-lnsl') This macro option defines the -l flags passed to ld. define(`confLDOPTS', `-s') This macro option defines the linker options passed to ld. define(`confMANROOT', `/usr/man/man') This macro option defines the location to install the Sendmail man pages. define(`confMANOWN', `root') This macro option defines the owner for all Sendmail installed man pages. define(`confMANGRP', `root') This macro option defines the group for all Sendmail installed man pages. define(`confMANMODE', `644') This macro option defines the mode for all Sendmail installed man pages. define(`confMAN1SRC', `1') This macro option defines the source for man pages installed in confMAN1. define(`confMAN5SRC', `5') This macro option defines the source for man pages installed in confMAN5. define(`confMAN8SRC', `8') This macro option defines the source for man pages installed in confMAN8. define(`confDEPEND_TYPE', `CC-M') This macro option specifies how to build dependencies with Sendmail. define(`confNO_HELPFILE_INSTALL') This macro option specifies to not install the Sendmail help file by default. Some experienced administrators recommend it, for better security. define(`confSBINGRP', `root') This macro option defines the group for all Sendmail setuid binaries. define(`confSBINMODE', `6755') This macro option defines the mode for all Sendmail setuid binaries. define(`confUBINOWN', `root') This macro option defines the owner for Sendmail binaries. define(`confUBINGRP', `root') This macro option defines the group for Sendmail binaries. define(`confEBINDIR', `/usr/sbin') This macro option defines where to install binaries executed from other binaries. On Red Hat Linux the path must be set to the /usr/sbin directory. Now we must compile and install Sendmail in the server: [root@deep ]/sendmail-8.10.1# cd sendmail [root@deep ]/sendmail# sh Build [root@deep ]/sendmail# sh Build install [root@deep ]/sendmail# cd .. [root@deep ]/sendmail-8.10.1# cd mailstats [root@deep ]/mailstats# sh Build install [root@deep ]/mailstats# cd .. [root@deep ]/sendmail-8.10.1# cd smrsh [root@deep ]/smrsh# sh Build install [root@deep ]/smrsh# cd .. [root@deep ]/sendmail-8.10.1# cd makemap (1) [root@deep ]/makemap# sh Build install (2) [root@deep ]/makemap# cd .. [root@deep ]/sendmail-8.10.1# cd praliases (3) [root@deep ]/praliases# sh Build install (4) [root@deep ]/praliases# cd .. [root@deep ]/sendmail-8.10.1# ln -fs /usr/sbin/sendmail /usr/lib/sendmail [root@deep ]/sendmail-8.10.1# chmod 511 /usr/sbin/smrsh [root@deep ]/sendmail-8.10.1# install -d -m 755 /var/spool/mqueue [root@deep ]/sendmail-8.10.1# chown root.mail /var/spool/mqueue [root@deep ]/sendmail-8.10.1# mkdir /etc/smrsh (1) Required only for Mail Hub configuration (2) Required only for Mail Hub configuration (3) Required only for Mail Hub configuration (4) Required only for Mail Hub configuration   *  The sh Build command would build and make the necessary dependencies for the different binary files required by Sendmail before installation on your system.   *  The sh Build install command would install sendmail, mailstats, makemap, praliases, smrsh binaries as well as the corresponding man pages on your system if compiled with this command.   *  The ln -fs command would make a symbolic link of the sendmail binary to the /usr/lib directory. This is required, since some programs hope to find the sendmail binary in this directory /usr/lib.   *  The install command would create the directory mqueue with permission 755 under /var/spool. A mail message can be temporarily undeliverable for a wide variety of reasons. To ensure that such messages are eventually delivered, Sendmail stores them in its queue directory until they can be delivered successfully.   *  The chown command would set UID root and GID mail for the mqueue directory.   *  The mkdir command would create the /etc/smrsh directory on your system. This directory is where we'll put all program mailers that we allow Sendmail to be able to run. Note : The programs makemap, and praliases must only be installed on the Central Mail Hub Server. makemap permits you to create a database map like the /etc/mail/aliases.db or /etc/mail/access.db files, for Sendmail. The praliases display the system mail aliases, the content of /etc/mail/ aliases file. Since it is better to only have one place like our Central Mail Hub to handle and manage all the db files in our network, then it is not necessary to use the makemap, and praliases programs and build db files on your other hosts in the network. ----------------------------------------------------------------------------- 22.3. Configurations Note : All the configuration files required for each software described in this book has been provided by us as a gzipped file, floppy.tgz for your convenience. This can be downloaded from this web address: http:// www.openna.com/books/floppy.tgz You can unpack this to any location on your local machine, say for example /tmp, assuming you have done this your directory structure will be /tmp/floppy. Within this floppy directory each configuration file has its own directory for respective software. For example Sendmail configuration file are organised like this: total 32 -rw-r--r-- 1 harrypotter harrypotter 684 Jun 8 13:00 Linux -rw-r--r-- 1 harrypotter harrypotter 3648 Jun 8 13:00 access -rw-r--r-- 1 harrypotter harrypotter 547 Jun 8 13:00 aliases drwxr-xr-x 2 harrypotter harrypotter 4096 Jun 8 13:00 init.d/ -rw-r--r-- 1 harrypotter harrypotter 137 Jun 8 13:00 local-host-names -rw-r--r-- 1 harrypotter harrypotter 109 Jun 8 13:00 null.mc -rw-r--r-- 1 harrypotter harrypotter 685 Jun 8 13:00 sendmail.mc drwxr-xr-x 2 harrypotter harrypotter 4096 Jun 8 13:00 sysconfig/ You can either cut and paste this directly if you are faithfully following our instructions from the begining or manually edit these to modify to your needs. This facility is there though as a convenience but please don't forget ultimately it will be your responsibility to check, verify, etc. before you use them whether modified or as it is. To run a Central Mail Hub Server, the following files are required and must be created or copied to the appropriate directories on your server.   *  Copy the sendmail file in the /etc/sysconfig directory.   *  Copy the sendmail script file in the /etc/rc.d/init.d/ directory.   *  Copy the local-host-names file in the /etc/mail directory.   *  Copy the access file in the /etc/mail directory.   *  Copy the aliases file in the /etc/mail directory. Create the virtusertable, domaintable, mailertable and .db files in /etc/mail directory. To run a Local or Neighbor Client, Server, the following files are required and must be created or copied to the appropriate directories on your server.   *  Copy the sendmail file in the /etc/sysconfig directory.   *  Copy the sendmail script file in the /etc/rc.d/init.d/ directory.   *  Copy the local-host-names file in the /etc/mail directory. Tip : You can obtain the configuration files listed below on our floppy.tgz archive. Copy the following files from the decompressed floppy.tgz archive to the appropriate places or copy and paste them directly from this book to the concerned file. ----------------------------------------------------------------------------- 22.4. The /etc/sendmail.mc file /Central Mail Hub The /etc/sendmail.mc file for the Central Mail Hub, instead of having each individual server or workstation in a network handle its own mail, it can be advantageous to have powerful central server that handles all mail. Such a server is called a Mail Hub. The advantage of a Central Mail Hub is: i. All incoming mail is sent to the hub, and no mail is sent directly to a client machine. ii. All outgoing mail from clients is sent to the Hub, and the Hub then forwards that mail to its ultimate destination. iii. All outgoing mail appears to come from a single server and no client's name needs to be known to the outside world. iv. No client needs to run a sendmail daemon to listen for mail. The sendmail.cf is the first file reading by Sendmail when it runs and one of the most important for Sendmail. Among the many items contained in that file are the locations of all the other files, the default permissions for those files and directories that Sendmail needs. The m4 macro preprocessor program of Linux is used by Sendmail V8 to produce a Sendmail configuration file. This macro program will produce the /etc/mail/sendmail.cf configuration file by processing a file whose name ends in .mc. For this reason, we'll create this file sendmail.mc and put the necessary macro values in it to allow the m4 program to process, read its input and gathers definitions of macros, and then replaces those macros with their values and output the result to create our sendmail.cf file. Please refer to the Sendmail documentation and README file under the cf subdirectory of the V8 Sendmail source distribution for more information. Create the sendmail.mc file, touch /var/tmp/sendmail-version/cf/cf/ sendmail.mc and add the following lines: define(`confDEF_USER_ID',``8:12'')dnl OSTYPE(`linux')dnl DOMAIN(`generic')dnl define(`confTRY_NULL_MX_LIST',true)dnl define(`confDONT_PROBE_INTERFACES',true)dnl define(`PROCMAIL_MAILER_PATH',`/usr/bin/procmail')dnl define(`LOCAL_MAILER_FLAGS', `ShPfn')dnl define(`LOCAL_MAILER_ARGS', `procmail -a $h -d $u')dnl FEATURE(`smrsh',`/usr/sbin/smrsh')dnl FEATURE(`mailertable')dnl FEATURE(`virtusertable',`hash -o /etc/mail/virtusertable')dnl FEATURE(`redirect')dnl FEATURE(`always_add_domain')dnl FEATURE(`use_cw_file')dnl FEATURE(`local_procmail')dnl FEATURE(`access_db')dnl FEATURE(`blacklist_recipients')dnl FEATURE(`dnsbl')dnl MAILER(`local')dnl MAILER(`smtp')dnl MAILER(`procmail')dnl This tells the sendmail.mc file to set itself up for this particular configuration with: define(`confDEF_USER_ID',``8:12'')dnl This configuration option specifies the default user id. In our case the user mail and group mail, which correspond to ID number 8:12 see the /etc/passwd and /etc/group file. OSTYPE(`linux')dnl This configuration option specifies the default operating system Sendmail wil bel running on; in our case the linux system. This item is one of the minimal pieces of information required by the mc file. DOMAIN(`generic')dnl This configuration option will specify and describe a particular domain appropriated for your environment. define(`confTRY_NULL_MX_LIST',true)dnl This configuration option specifies whether the receiving server is the best MX for a host and if so, try connecting to that host directly. define(`confDONT_PROBE_INTERFACES',true)dnl This configuration option, if set to true, means Sendmail will _not_insert the names and addresses of any local interfaces into the $=w class, list of known equivalent addresses. define(`PROCMAIL_MAILER_PATH',`/usr/bin/procmail')dnl This configuration option sets the path to the procmail program installed in your server. Since the path in Red Hat Linux differs from other Linux versions, we must specify the new path with this macro. It's important to note that this macro is also used by FEATURE (`local_procmail') as defined later in this file. define(`LOCAL_MAILER_FLAGS', `ShPfn')dnl This configuration option defines the flags that must be used by the local mailer (procmail). See your Sendmail documentation for more information of each one. define(`LOCAL_MAILER_ARGS', `procmail -a $h -d $u')dnl This configuration option defines the arguments that must be passed to the local mailer (procmail). See your Sendmail documentation for more information on each one. FEATURE(`smrsh',`/usr/sbin/smrsh')dnl This m4 macro enables the use of smrsh, the sendmail restricted shell, instead of the default /bin/sh for mailing programs. With this feature you can control what program gets run via e-mail through the /etc/mail/ aliases and ~/.forward files. The default location for the smrsh program is /usr/libexec/smrsh. Since we have installed smrsh in another location, we need to add an argument to the smrsh feature to indicate the new placement /usr/sbin/smrsh. The use of smrsh is recommended by CERT, so you are encouraged to use this feature as often as possible. FEATURE(`mailertable')dnl This m4 macro enables the use of mailertable database selects new delivery agents. A mailertable is a database that maps host.domain names to special delivery agent and new domain name pairs. With this feature, mail can be delivered through the use of a specified or particular delivery agent to a new domain name. Usually, this feature must be available only on a Central Mail Hub server. FEATURE(`virtusertable',`hash -o /etc/mail/virtusertable')dnl This m4 macro enables the use of virtusertable, support for virtual domains, which allow multiple virtual domains to be hosted on one machine. A virtusertable is a database that maps virtual domains into new addresses. With this feature, mail for virtual domains can be delivered to a local, remote, or single user address. Usually this feature must be available only on a Central Mail Hub server. FEATURE(`redirect')dnl This m4 macro enables the use of redirect support for address.REDIRECT. With this feature, mail addressed to a retired user account wahib, for example, will be bounced with an indication of the new forwarding address. The retired accounts must be set up in the aliases file on the mail server. Usually this feature must be available only on a Central Mail Hub server. FEATURE(`always_add_domain')dnl This m4 macro enables the use of always_add_domain, add the local domain even on local mail. With this feature, all addresses that are locally delivered will be fully qualified. It is safe and recommended to set this feature for security reasons. FEATURE(`use_cw_file')dnl This m4 macro enables the use of use_cw_file, use /etc/mail/ local-host-names file for local hostnames. With this feature you can declare a list of hosts in the /etc/mail/local-host-names file for which the local host is acting as the MX recipient. In other word this feature causes the file /etc/mail/local-host-names to be read to obtain alternative names for the local host. FEATURE(`local_procmail')dnl This m4 macro enables the use of local_procmail use procmail as local delivery agent. With this feature you can use procmail as a Sendmail delivery agent. FEATURE(`access_db')dnl This m4 macro enables the access database feature. With this feature you have the ability through the access db to allow or refuse to accept mail from specified domains. Usually this feature must be available only in a Central Mail Hub server. FEATURE(`blacklist_recipients')dnl This m4 macro enables the ability to block incoming mail for certain recipient usernames, hostnames, or addresses. With this feature you can, for example, block incoming mail to user nobody, host foo.mydomain.com, or guest@bar.mydomain.com. FEATURE(`dnsbl')dnl This m4 macro enables Sendmail to reject mail from any site in the Realtime Blackhole List database rbl.maps.vix.com. The DNS based rejection is a database maintained in DNS of spammers. For details, see http://maps.vix.com/rbl/. MAILER(`local'), MAILER(`smtp'), and MAILER(`procmail')dnl This m4 macro enables the use of local, smtp, and procmail as delivery agents in Sendmail by default, delivery agents are not automatically declared. With this feature, you can specify which ones you want to support and which ones to ignore. The MAILER(`local'), MAILER(`smtp'), and MAILER(`procmail') options cause support for local, smtp, esmtp, smtp8, relay delivery agents and procmail to be included. It's important to note that MAILER(`smtp') should always precede MAILER(`procmail'). Note : Sometimes, a domain with which you wish to continue communications may end up in the RBL list. In this case, Sendmail allows you to override these domains to allow their e-mail to be received. To do this, simply edit the /etc/mail/access file and add the appropriate domain information. Example 22-1. Overriding RBL blacklisted.domain OK ----------------------------------------------------------------------------- 22.5. Build and Tweak Sendmail Now that our macro configuration file sendmail.mc is created, we can build the sendmail configuration file sendmail.cf from these statements with the following commands: [root@deep] /# cd /var/tmp/sendmail-version/cf/cf/ [root@deep ]/cf# m4 ../m4/cf.m4 sendmail.mc > /etc/mail/sendmail.cf Note : Here, the ../m4/cf.m4 tells m4 program where to look for its default configuration file information. ----------------------------------------------------------------------------- 22.5.1. The null.mc file Since our local clients machines never receive mail directly from the outside world, and relay, send all their mail through the Mail Hub server, we will create a special file called null.mc which, when later processed, will create a customized sendmail.cf configuration file that responds to this special setup for our neighbour or local server client machines. This m4 macro file is simple to create and configure because it doesn't need a lot of features, as the configuration file -sendmail.mc, for the Central Mail Hub server did. +---------------------------------------------------------------------------+ | Caution | +---------------------------------------------------------------------------+ |The null.mc file is for the local or neighbour client and server machines | |only | +---------------------------------------------------------------------------+ 1. Create the null.mc file, touch /var/tmp/sendmail-version/cf/cf/null.mc and add the following lines: OSTYPE(`linux')dnl (1) DOMAIN(`generic')dnl (2) FEATURE(`nullclient',`mail.openna.com')dnl (3) undefine(`ALIAS_FILE')dnl (4) (1) This configuration option specifies the default operating system Sendmail will be running on, in our case, the linux system. This item is one of the minimal pieces of information required by the mc file. (2) This configuration option will specify and describe a particular domain appropriated for your environment. (3) This m4 macro sets your clients machines to never receive mail directly, to send their mail to a Central Mail Hub, and relay all mail through that server rather than sending directly. This feature creates a stripped down configuration file containing nothing but support for forwarding all mail to a Mail Hub via a local SMTP-based network. The argument `mail.openna.com' included in this feature is the canonical name of that Mail Hub. You should, of course, change this canonical name to reflect your Mail Hub Server for example: FEATURE(`nullclient',` my.mailhub.com'). (4) This configuration option prevents the nullclient version of Sendmail from trying to access /etc/mail/aliases and /etc/mail/ aliases.db files. With the adding of this line in the .mc file, you don't need to have an aliases file on all your internal neighbor client Sendmail machines. Aliases files are required only on the Mail Hub Server for all server and client aliases on the network. Tip : We advice that with this kind of configuration, no mailers should be defined, and no aliasing or forwarding is done. 2. Now that our macro configuration file null.mc is created, we can build the Sendmail configuration file sendmail.cf from these statements in all our neighbor servers, and client machines with the following commands: [root@deep] /# cd /var/tmp/sendmail-version/cf/cf/ [root@deep ]/cf# m4 ../m4/cf.m4 null.mc > /etc/mail/sendmail.cf 3. No mail should ever again be delivered to your local machine. Since there will be no incoming mail connections, you no longer needed to run a Sendmail daemon on your neighbor or local server, client machines. To stop the Sendmail daemon from running on your neighbor or local server, or client machines, edit or create the /etc/sysconfig/sendmail file and change/add the lines that read: DAEMON=yes To read: DAEMON=no And: QUEUE=1h Note : The QUEUE=1h under /etc/sysconfig/sendmail file causes Sendmail to process the queue once every 1 hour. We leave that line in place because Sendmail still needs to process the queue periodically in case the Mail Hub is down. 4. Remove the following files from your system, use the following command: [root@client /]# rm -f /usr/bin/newaliases [root@client /]# rm -f /usr/man/man1/newaliases.1 [root@client /]# rm -f /usr/man/man5/aliases.5 Note : Local machines never use aliases, access, or other maps database. Since all map file databases are located and used on the Central Mail Hub Server for all local machines we may have on the network, we can safety remove the following commands and man pages from all our local machines.   o  /usr/bin/newaliases   o  /usr/man/man1/newaliases.1   o  /usr/man/man5/aliases.5 5. Remove the unnecessary Procmail program from your entire local Sendmail server or client. Since local machines send all internal and outgoing mail to the mail Hub Server for future delivery, we don't need to use a complex local delivery agent program like Procmail to do the job. Instead we can use the default /bin/mail program. To remove Procmail from your system, use the following command: [root@client ]# rpm -e procmail ----------------------------------------------------------------------------- 22.6. The /etc/mail/access and access.db files The access database file can be created to accept or reject mail from selected domains. For example, you may choose to reject all mail originating from known spammers, or to accept to relay all mail from your local network since now relaying is denied by default with Sendmail -this is an Anti-Spam feature. In the access file example below, we'll allow relaying from localhost and all local network addresses beginning with the IP address 192.168.1. The files access and access.db are not required for Local or Neighbor Client setups. It is required only if you decide to set up a Central Mail Hub to handle all your mail. Also note that the use of a Central Mail Hub will improve the security and the management of other servers and clients on your network that run Sendmail. 1. Create the access file touch /etc/mail/access and add the following lines: # Description showing bellow for the format of this file comes from # the Sendmail source distribution under "cf/README" file. # # The table itself uses e-mail addresses, domain names, and network # numbers as keys. For example, # # spammer@aol.com REJECT # cyberspammer.com REJECT # 192.168.212 REJECT # # would refuse mail from spammer@aol.com, any user from cyberspammer.com # (or any host within the cyberspammer.com domain), and any host on the # 192.168.212.* network. # # The value part of the map can contain: # # OK Accept mail even if other rules in the # running ruleset would reject it, for example, # if the domain name is unresolvable. # RELAY Accept mail addressed to the indicated domain or # received from the indicated domain for relaying # through your SMTP server. RELAY also serves as # an implicit OK for the other checks. # REJECT Reject the sender or recipient with a general # purpose message. # DISCARD Discard the message completely using the # $#discard mailer. This only works for sender # addresses (i.e., it indicates that you should # discard anything received from the indicated # domain). # ### any text where ### is an RFC 821 compliant error code # and "any text" is a message to return for # the command. # # For example: # # cyberspammer.com 550 We don't accept mail from spammers # okay.cyberspammer.com OK # sendmail.org OK # 128.32 RELAY # # would accept mail from okay.cyberspammer.com, but would reject mail # from all other hosts at cyberspammer.com with the indicated message. # It would allow accept mail from any hosts in the sendmail.org domain, # and allow relaying for the 128.32.*.* network. # # You can also use the access database to block sender addresses based on # the username portion of the address. For example: # # FREE.STEALTH.MAILER@ 550 Spam not accepted # # Note that you must include the @ after the username to signify that # this database entry is for checking only the username portion of the # sender address. # # If you use like we do in our "sendmail.mc macro configuration: # # FEATURE(`blacklist_recipients') # # then you can add entries to the map for local users, hosts in your # domains, or addresses in your domain which should not receive mail: # # badlocaluser 550 Mailbox disabled for this username # host.mydomain.com 550 That host does not accept mail # user@otherhost.mydomain.com 550 Mailbox disabled for this recipient # # This would prevent a recipient of badlocaluser@mydomain.com, any # user at host.mydomain.com, and the single address # user@otherhost.mydomain.com from receiving mail. Enabling this # feature will keep you from sending mails to all addresses that # have an error message or REJECT as value part in the access map. # Taking the example from above: # # spammer@aol.com REJECT # cyberspammer.com REJECT # # Mail can't be sent to spammer@aol.com or anyone at cyberspammer.com. # # Now our configuration of access file, # by default we allow relaying from localhost... localhost.localdomain RELAY localhost RELAY 127.0.0.1 RELAY 192.168.1 RELAY Note : Don't forget to specify in this file access your private IP address range you want to relay or you'll be unable to send mail from your internal network. 2. Create the access.db file, remember, since /etc/mail/access is a database, after creating the text file as described above, you must use the makemap utility program to create the database map. To create the access database map, use the following command: [root@deep] /# makemap hash /etc/mail/access.db < /etc/mail/access ----------------------------------------------------------------------------- 22.7. The /etc/mail/aliases and aliases.db files Aliasing is the process of converting one local recipient name on the system into another -aliasing occurs only on local names. Example uses are to convert a generic name -such as root, into a real username on the system, or to convert one name into a list of many names -for mailing lists. For every envelope that lists a local user as a recipient, Sendmail looks up that recipient's name in the aliases file. Because Sendmail may have to search through thousands of names in the aliases file, a copy of the file is stored in a separate db database format file to significantly improve lookup speed. If you configure your Sendmail to use a Central Server Mail Hub to handles all mail, you don't need to install the aliases and aliases.db files on the neighbor server or client machines. 1. Create the aliases file touch /etc/mail/aliases and add the following lines by default: # # @(#)aliases 8.2 (Berkeley) 3/5/94 # # Aliases in this file will NOT be expanded in the header from # Mail, but WILL be visible over networks or from /bin/mail. # # >>>>>>>>>> The program "newaliases" must be run after # >> NOTE >> this file is updated for any changes to # >>>>>>>>>> show through to sendmail. # # Basic system aliases -- these MUST be present. MAILER-DAEMON: postmaster postmaster: root # General redirections for pseudo accounts. bin: root daemon: root nobody: root # Person who should get root's mail #root: admin Note : Your aliases file will be probably far more complex, but even so, note how the example shows the minimum form of aliases. 2. Since /etc/mail/aliases is a database, after creating the text file as described above, you must use the makemap program to create the database map. To create the aliases database map, use the following command: [root@deep] /# makemap hash /etc/mail/aliases.db < /etc/mail/aliases ----------------------------------------------------------------------------- 22.7.1. The /etc/mail/ Directory The   *  /etc/mail/virtusertable,   *  domaintable   *  mailertable and   *  virtusertable.db,   *  domaintable.db,   *  mailertable.db All of these files relate to particular features of Sendmail that can be tuned by the system administrator. Once again, these features are usually required only in the Central Mail Hub server. The following is the explanation of each one. The virtusertable & virtusertable.db files A virtusertable is a database that maps virtual domains into news addresses. With this feature, mail for virtual domain on your network can be delivered to local, remote, or a single user address. The domaintable & domaintable.db files A domaintable is a database that maps old domain to a new one. With this feature, multiple domain names on your network can be rewritten from the old domain to the new. The mailertable & mailertable.db files A mailertable is a database that maps host.domain names to special delivery agent and new domain name pairs. With this feature mail on your network can be delivered through the use of a particular delivery agent to a new local or remote domain name. To create the virtusertable, domaintable, mailertable, and their corresponding .db files into /etc/mail directory, use the following commands: [root@deep] /# for map in virtusertable domaintable mailertable > do > touch /etc/mail/${map} > chmod 0644 /etc/mail/${map} > makemap hash /etc/mail/${map}.db < /etc/mail/${map} > chmod 0644 /etc/mail/${map}.db > done ----------------------------------------------------------------------------- 22.8. The /etc/mail/local-host-names file Note : Please note that the /etc/mail/local-host-names file is for all type of configuration. The /etc/mail/local-host-names file is read to obtain alternative names for the local host. One use for such a file might be to declare a list of hosts in your network for which the local host is acting as the MX recipient. On that machine we simply need to add the names of machines for which it i.e. mail.openna.com, will handle mail to /etc/mail/local-host-names. Here is an example: Example 22-2. Alternative names Create the local-host-names file, touch /etc/mail/local-host-names and add the following line: # local-host-names - include all aliases for your machine here. openna.com deep.openna.com www.openna.com win.openna.com mail.openna.com With this type of configuration, all mail sent will appear as if it were sent from openna.com, and any mail sent to www.openna.com or the other hosts will be delivered to mail.openna.com our mail Hub. +---------------------------------------------------------------------------+ | Caution | +---------------------------------------------------------------------------+ |Please be aware that if you configure your system to masquerade as another,| |any e-mail sent from your system to your system will be sent to the machine| |you are masquerading as. For example, in the above illustration, log files | |that are periodically sent to by the cron daemon of | |Linux would be sent to our Mail Hub. | +---------------------------------------------------------------------------+ ----------------------------------------------------------------------------- 22.8.1. Configure the /etc/sysconfig/sendmail file The /etc/sysconfig/sendmail file is used to specify SENDMAIL configuration information, such as if sendmail should run as a daemon, if it should listen for mail or not, and how much time to wait before sending a warning if messages in the queue directory have not been delivered. Create the sendmail file touch /etc/sysconfig/sendmail and add in this file: DAEMON=yes (1) QUEUE=1h (2) (1) The DAEMON=yes option instructs Sendmail to run as a daemon. This line is useful when Sendmail client machines are configured to not accept mail directly from outside in favor of forwarding all local mail to a Central Hub, not running a daemon also improves security. If you have configured your server or client machines in this way, all you have to do is to replace the DAEMON=yes to DAEMON=no. (2) Mail is usually placed into the queue because it could not be transmitted immediately. The QUEUE=1h sets the time interval before sends a warning to the sender if the messages has not been delivered. ----------------------------------------------------------------------------- 22.9. The /etc/rc.d/init.d/sendmail script file Note : Please note that the /etc/rc.d/init.d/sendmail file is for all type of configuration. To configure your /etc/rc.d/init.d/sendmail script file to start and stop the Sendmail daemon, You have to create the sendmail script file, touch /etc/ rc.d/init.d/sendmail and add: #!/bin/sh # # sendmail This shell script takes care of starting and stopping # sendmail. # # chkconfig: 2345 80 30 # description: Sendmail is a Mail Transport Agent, which is the program \ # that moves mail from one machine to another. # processname: sendmail # config: /etc/sendmail.cf # pidfile: /var/run/sendmail.pid # Source function library. . /etc/rc.d/init.d/functions # Source networking configuration. . /etc/sysconfig/network # Source sendmail configuration. if [ -f /etc/sysconfig/sendmail ] ; then . /etc/sysconfig/sendmail else DAEMON=yes QUEUE=1h fi # Check that networking is up. [ ${NETWORKING} = "no" ] && exit 0 [ -f /usr/sbin/sendmail ] || exit 0 RETVAL=0 # See how we were called. case "$1" in start) # Start daemons. echo -n "Starting sendmail: " /usr/bin/newaliases > /dev/null 2>&1 for i in virtusertable access domaintable mailertable ; do if [ -f /etc/mail/$i ] ; then makemap hash /etc/mail/$i < /etc/mail/$i fi done daemon /usr/sbin/sendmail $([ "$DAEMON" = yes ] && echo -bd) \ $([ -n "$QUEUE" ] && echo -q$QUEUE) RETVAL=$? echo [ $RETVAL -eq 0 ] && touch /var/lock/subsys/sendmail ;; stop) # Stop daemons. echo -n "Shutting down sendmail: " killproc sendmail RETVAL=$? echo [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/sendmail ;; restart|reload) $0 stop $0 start RETVAL=$? ;; status) status sendmail RETVAL=$? ;; *) echo "Usage: sendmail {start|stop|restart|status}" exit 1 esac exit $RETVAL Now, make this script executable and change its default permissions: [root@deep] /# chmod 700 /etc/rc.d/init.d/sendmail Create the symbolic rc.d links for Sendmail with the command: [root@deep] /# chkconfig --add sendmail Start your Sendmail Server manually with the following command: [root@deep] /# /etc/rc.d/init.d/sendmail start Starting sendmail: [ OK ] Please do a cleanup as always later: [root@deep] /# cd /var/tmp [root@deep ]/tmp# rm -rf sendmail-version/ sendmail.version.tar.gz The rm command as used above will remove all the source files we have used to compile and install Sendmail. It will also remove the Sendmail compressed archive from the /var/tmp directory. ----------------------------------------------------------------------------- 22.10. Secure Sendmail using smrsh The smrsh program is intended as a replacement for /bin/sh in the program mailer definition of Sendmail. It's a restricted shell utility that provides the ability to specify, through the /etc/smrsh directory, an explicit list of executable programs available to Sendmail. To be more accurate, even if somebody with malicious intentions can get Sendmail to run a program without going through an aliases or forward file, smrsh limits the set of programs that he or she can execute. When used in conjunction with Sendmail, smrsh effectively limits Sendmail's scope of program execution to only those programs specified in smrsh's directory. If you have followed what we did above, smrsh program is already compiled and installed on your computer under /usr/sbin/smrsh. 1. The first thing we need to do is to determine the list of commands that smrsh should allow Sendmail to run. By default we include, but are not limited to:   +  /bin/mail -if you have it installed on your system   +  /usr/bin/procmail -if you have it installed on your system +-----------------------------------------------------------------------+ | Warning | +-----------------------------------------------------------------------+ |You should not include interpreter programs such as sh(1), csh(1), perl| |(1), uudecode(1) or sed(1) -the stream editor, in your list of | |acceptable commands. | +-----------------------------------------------------------------------+ 2. You will next need to populate the /etc/smrsh directory with the programs that are allowable for Sendmail to execute. To prevent duplicate programs, and do a nice job, it is better to establish links to the allowable programs from /etc/smrsh rather than copy programs to this directory. To allow the mail program /bin/mail, use the following commands: [root@deep] /# cd /etc/smrsh [root@deep ]/smrsh# ln -s /bin/mail mail To allow the procmail program /usr/bin/procmail, use the following commands: [root@deep] /# cd /etc/smrsh [root@deep ]/smrsh# ln -s /usr/bin/procmail procmail This will allow the mail and procmail programs to be run from a user's .forward file or an aliases file which uses the program syntax. Important : Procmail is required only in Mail Hub Server and not in Local Client Mail Server. If you've configured your system like a Mail Hub Server then make the link with procmail as explained above, if you've configured your system as a Local Client Server then skip the procmail step above. 3. We can now configure Sendmail to use the restricted shell. The program mailer is defined by a single line in the Sendmail configuration file, / etc/mail/sendmail.cf. You must modify this single line Mprog definition in the sendmail.cf file, by replacing the /bin/sh specification with /usr /sbin/smrsh. Edit the sendmail.cf file, vi /etc/mail/sendmail.cf and change the line: Example 22-3. sendmail.cf Mprog, P=/bin/sh, F=lsDFMoqeu9, S=10/30, R=20/40, D=$z:/, T=X-Unix, A=sh -c $u Which should be changed to: Mprog, P=/usr/sbin/smrsh, F=lsDFMoqeu9, S=10/30, R=20/40, D=$z:/, T=X-Unix, A=sh -c $u 4. Now re-start the sendmail process manually with the following command: [root@deep] /# /etc/rc.d/init.d/sendmail restart Note : In our sendmail.mc configuration file for the Mail Hub Server above, we have already configured this line Mprog to use the restricted shell /usr/sbin/smrsh with the m4 macro FEATURE(`smrsh',`/usr/sbin/ smrsh'), so don't be surprised if the /usr/sbin/smrshspecification is already set in your /etc/mail/sendmail.cf file for the Mail Hub relay. Instead, use the technique shown above for other /etc/mail/sendmail.cf files in your network like the one for the nullclient local or neighbor client and servers that use the null.mc macro configuration file to generate the /etc/mail/sendmail.cf file. ----------------------------------------------------------------------------- 22.11. The /etc/mail/aliases file A poorly or carelessly administered aliases file can easily be used to gain privileged status. For example, many vendors ship systems with a decode alias in the /etc/mail/aliases file. The intention is to provide an easy way for users to transfer binary files using mail. At the sending site the user converts the binary to ASCII with uuencode, then mails the result to the decode alias at the receiving site. That alias pipes the mail message through the /usr/bin/uuencode program, which converts the ASCII back into the original binary file. Remove the decode alias line from your /etc/mail/aliases file. Similarly, every alias that executes a program that you did not place there yourself and check completely should be questioned and probably removed. Edit the aliases file vi /etc/mail/aliases and remove the following lines: # Basic system aliases -- these MUST be present. MAILER-DAEMON: postmaster postmaster: root # General redirections for pseudo accounts. bin: root daemon: root games: root (1) ingres: root (2) nobody: root system: root (3) toor: root (4) uucp: root (5) # Well-known aliases. manager: root (6) dumper: root (7) operator: root (8) # trap decode to catch security attacks decode: root (9) # Person who should get root's mail #root: marc (1) (2) (3) (4) (5) (6) (7) (8) (9) Remove all these lines For the changes to take effect you will need to run: [root@deep] /# /usr/bin/newaliases You need to prevent your Sendmail being abused by unauthorized users, Sendmail now includes powerful Anti-Spam features, which can help prevent your mail server from being abused by unauthorized users. To do this, make a change to the configuration file to block off spammers. Edit the sendmail.cf file, vi /etc/mail/sendmail.cf and change the line: O PrivacyOptions=authwarnings To read: O PrivacyOptions=authwarnings,goaway Setting the goaway option causes Sendmail to disallow all SMTP EXPN commands, it also causes it to reject all SMTP VERB commands and to disallow all SMTP VRFY commands. These changes prevent spammers from using the EXPN and VRFY commands in Sendmail. You have to restrict who can examine the queues contents, ordinarily, anyone may examine the mail queue's contents by using the mailq command. To restrict who may examine the queues contents, you must specify the restrictmailq option in the /etc/mail/sendmail.cf file. With this option, Sendmail allows only users who are in the same group as the group ownership of the queue directory root to examine the contents. This allows the queue directory to be fully protected with mode 0700, while selected users are still able to see the contents. Edit the sendmail.cf file, vi /etc/mail/sendmail.cf and change the line: O PrivacyOptions=authwarnings,goaway To read: O PrivacyOptions=authwarnings,goaway,restrictmailq Now we change the mode of our queue directory to be fully protected: [root@deep] /# chmod 0700 /var/spool/mqueue Now re-start the sendmail process manually for the change to take effect: [root@deep] /# /etc/rc.d/init.d/sendmail restart Shutting down sendmail: [ OK ] Starting sendmail: [ OK ] Tip : We have already added the goaway option to the line PrivacyOptions= in sendmail.cf file. Now we can just add the restrictmailq option to this line. Any non-privileged user who attempts to examine the mail queue content will get this message: [user@deep /]$ /usr/bin/mailq You are not permitted to see the queue ----------------------------------------------------------------------------- 22.12. Limit queue processing to root Ordinarily, anyone may process the queue with the -q switch. To limit queue processing to root and the owner of the queue directory, you must specify the restrictqrun option in the /etc/mail/sendmail.cf file. Edit the sendmail.cf file, vi /etc/mail/sendmail.cf and change the line: O PrivacyOptions=authwarnings,goaway,restrictmailq To read: O PrivacyOptions=authwarnings,goaway,restrictmailq,restrictqrun Now re-start the sendmail process manually for the change to take effect: [root@deep] /# /etc/rc.d/init.d/sendmail restart Shutting down sendmail: [ OK ] Starting sendmail: [ OK ] Any non-privileged user who attempts to process the queue will get this message: [user@deep /]$ /usr/sbin/sendmail -q You do not have permission to process the queue ----------------------------------------------------------------------------- 22.12.1. The SMTP greeting message When Sendmail accepts an incoming SMTP connection it sends a greeting message to the other host. This message identifies the local machine and is the first thing it sends to say it is ready. Edit the sendmail.cf file, vi /etc/mail/sendmail.cf and change the line: O SmtpGreetingMessage=$j Sendmail $v/$Z; $b To read: O SmtpGreetingMessage=$j Now re-start the sendmail process manually for the change to take effect: [root@deep] /# /etc/rc.d/init.d/sendmail restart Shutting down sendmail: [ OK ] Starting sendmail: [ OK ] Tip : This change doesn't actually affect anything, but was recommended by folks in the news.admin.net-abuse.email newsgroup as a legal precaution. It modifies the banner, which Sendmail displays upon receiving a connection. Do set the immutable bit on important Sendmail files, important Sendmail files can be set immutable for better security with the chattr command of Linux. A file with the +i attribute cannot be modified, deleted or renamed. No link can be created to this file, and no data can be written to the file. Only the super-user can set or clear this attribute. 1. Set the immutable bit on the sendmail.cf file: [root@deep] /# chattr +i /etc/mail/sendmail.cf 2. Set the immutable bit on the local-host-names file: [root@deep] /# chattr +i /etc/mail/local-host-names 3. Set the immutable bit on the aliases file: [root@deep] /# chattr +i /etc/mail/aliases 4. Set the immutable bit on the access file: [root@deep] /# chattr +i /etc/mail/access Further documentation and for more details, there are several man pages you can read: aliases(5) - aliases file for sendmail makemap(8) - create database maps for sendmail sendmail(8) - an electronic mail transport agent mailq(1) - print the mail queue newaliases(1) - rebuild the data base for the mail aliases file mailstats(8) - display mail statistics praliases(8) - display system mail aliases ----------------------------------------------------------------------------- 22.13. Sendmail Administr