* The project o Scope o Protect from o Doesn't protect from o Support o How to contribute o Donations o Development o Products o Community o Partners o News o Staff o About o Legal o Contacts * Build HowTo o Hardware requirements o Hardware tweaking o Quick start o Disks setup o Hardened Gentoo setup o Boot setup o System setup o Verification o System hardening o Network hardening o Services hardening o Creating users o Creating chroots o Creating shares * User notify o The Judger o Notipy Welcome to Lollobox 0.1 Lollobox is an hardened notebook project designed to bring confidentiality and security to the masses. In short you'll get an hardened and tuned Linux system with full disk encryption. Lollobox can be your pimp and minimize risk of others playing with your butt. The Lollobox project First of all welcome! You just reached the very first page of the project documentation. Here you'll be introduced to the key concepts of Lollobox. Lollobox is a secure notebook project, a collaborative effort to bring the most effective software together configured to fit stronger security requirements. Lollobox features incude FDE (Full Disk Encryption), boot from external device, kernel and userspace hardening, network stack and system tuning, RBAC and filesystem restrictions together with some unique utility. We think that usable security can and should be delivered, also if it doesn't sell in the short term. Luckily we are not a commercial vendor and follow different rules. What amazed us initially was that a great percentage of the needed components was already available, it was just a matter of putting the right pieces of technology together. This is the Lollobox goal: deliver an usable and more secure Linux recipe to the masses. Our focus is on notebooks as they are even more exposed and vulnerable but the recommendations are applicable to personal computers, workstations, embedded devices, terminal clients and servers. There's no presumption to have invented something new, we just hope you'll enjoy our efforts (-; Protect from Memory management issued, like stack and heap overflows, format strings, null pointer dereference. Memory management issues Stack smashing protection and PIE Lollobox uses GCC Stack-Smashing Protector (abbreviated SSP, also known as ProPolice?), the second generation of stack canary protection build into GCC (StackGuard? is the old one). While the -fstack-protector flag enables string protection in Lollobox -fstack-protector-all is used for protection of all types. Lollobox makes use of the Gentoo hardened build toolchain, an easy way to compile ebuilds using these and other protections (for userspace utilities see gcc-config). In this way every binary of a Lollobox system is more resilient against stack overflows. -fstack-protector-all The hardened toolchain also implements a second runtime protection method: PIE (Position Independent Code/Executables). -fPIC -fPIE Limitations: * Stack-smashing protection is unable to protect against certain forms of attack. For example, it cannot protect against buffer overflows in heap. * StackGuard? and ProPolice? cannot protect against overflows in automatically allocated structures which overflow into function pointers. ProPolice? at least will rearrange the allocation order to get such structures allocated before function pointers. * There is no sane way to alter the structure of a structure; structures are expected to be the same between modules, especially with shared libraries. Any data in a structure after a buffer is impossible to protect with canaries; thus, programmers must be very careful about how they organize their variables and use their structures. Structures with buffers should be malloc()ed or new[]ed pointers. More informations about SSP and PIE can be found at the following urls: * http://en.wikipedia.org/wiki/Stack-smashing_protection * http://dev.gentoo.org/pappy/presentations/hardened-toolchain-full/hardened-toolchain-full.pdf * http://www.hackerz.ir/e-books/123%20Gentoo%20Hardened.pdf Heap smashing protection http://www.google.it/search?hl=it&q=HeapShield DieHard? HeapShield? PHKmalloc Samurai Address space layout randomization Address space randomization hinders some types of security attack by preventing an attacker being able to easily predict target addresses. For example attackers trying to execute return-to-libc attacks must locate the code to be executed; while other attackers trying to execute shellcode injected on the stack have to first find the stack. In both cases, the related memory addresses are obscured from the attackers; these values have to be guessed, and a mistaken guess is not usually recoverable due to the application crashing. In Linux, a weak form of ASLR has been enabled by default since kernel version 2.6.12. The PaX and ExecShield? patchsets to the Linux kernel provide more complete implementations. Various Linux distributions including Adamantix, Hardened Gentoo, and Hardened Linux From Scratch come with PaX's implementation of ASLR by default. NX bit memory protection The NX bit, which stands for No eXecute, is a technology used in CPUs to segregate areas of memory for use by either storage of processor instructions (or code) or for storage of data, a feature normally only found in Harvard architecture processors. However, the NX bit is being increasingly used in conventional von Neumann architecture processors, for security reasons. Linux kernel currently supports standard hardware NX on CPUs that support it, such as the current 64-bit CPUs of AMD, Intel, Transmeta and VIA. Some desktop Linux distributions such as Fedora Core 6, Ubuntu and openSUSE do not enable the HIGHMEM64 option, which is required to gain access to the NX bit in 32-bit mode, in their default kernel; this is because the PAE mode that is required to use the NX bit causes pre-Pentium Pro (including Pentium MMX) and Celeron M and Pentium M processors without NX support to fail to boot. Other processors that do not support PAE are AMD K6 and earlier, Transmeta Crusoe, VIA C3 and earlier, and Geode GX and LX. The PaX NX technology can emulate an NX bit or NX functionality, or use a hardware NX bit. PaX works on x86 CPUs that do not have the NX bit, such as 32-bit x86. PaX supplies two methods of NX bit emulation, called SEGMEXEC and PAGEEXEC. When the PAGEEXEC method is used on a CPU supplying a hardware NX bit, the hardware NX bit is used; no emulation is used, thus no significant overhead is incurred. Additional PAX protections PaX supplies fine-grained control over protections. It allows individual control over the following functions of the technology for each binary executable: * mprotect() restrictions * Trampoline emulation * Randomized executable base * Randomized mmap() base Grsecurity grsecurity is a patchset to the Linux kernel that implements many security features, it's a core component in a Lollobox setup. grsecurity is an innovative approach to security utilizing a multi-layered detection, prevention, and containment model. It is licensed under the GPL. http://www.grsecurity.net/ It offers among many other features (http://www.grsecurity.net/features.php): * An intelligent and robust Role-Based Access Control (RBAC) system that can generate least privilege policies for your entire system with no configuration * Change root (chroot) hardening * /tmp race prevention * Extensive auditing * Prevention of arbitrary code execution, regardless of the technique used (stack smashing, heap corruption, etc) * Prevention of arbitrary code execution in the kernel * Randomization of the stack, library, and heap bases * Kernel stack base randomization * Protection against exploitable null-pointer dereference bugs in the kernel * Reduction of the risk of sensitive information being leaked by arbitrary-read kernel bugs * A restriction that allows a user to only view his/her processes * Security alerts and audits that contain the IP address of the person causing the alert grsecurity 2.0 RBAC features * Role-Based Access Control * User, group, and special roles * Domain support for users and groups * Role transition tables * IP-based roles * Non-root access to special roles * Special roles that require no authentication * Nested subjects * Variable support in configuration * And, or, and difference set operations on variables in configuration * Object mode that controls the creation of setuid and setgid files * Create and delete object modes * Kernel interpretation of inheritance * Real-time regular-expression resolution * Ability to deny ptraces to specific processes * User and group transition checking and enforcement on an inclusive or exclusive basis * /dev/grsec entry for kernel authentication and learning logs * Next-generation code that produces least-privilege policies for the entire system with no configuration * Policy statistics for gradm * Inheritance-based learning * Learning configuration file that allows the administrator to enable inheritance-based learning or disable learning on specific paths * Full pathnames for offending process and parent process * RBAC status function for gradm * /proc//ipaddr gives the remote address of the person who started a given process * Secure policy enforcement * Supports read, write, append, execute, view, and read-only ptrace object permissions * Supports hide, protect, and override subject flags * Supports the PaX flags * Shared memory protection feature * Integrated local attack response on all alerts * Subject flag that ensures a process can never execute trojaned code * Full-featured fine-grained auditing * Resource, socket, and capability support * Protection against exploit bruteforcing * /proc/pid filedescriptor/memory protection * Rules can be placed on non-existent files/processes * Policy regeneration on subjects and objects * Configurable log suppression * Configurable process accounting * Human-readable configuration * Not filesystem or architecture dependent * Scales well: supports as many policies as memory can handle with the same performance hit * No runtime memory allocation * SMP safe * O(1) time efficiency for most operations * Include directive for specifying additional policies * Enable, disable, reload capabilities * Option to hide kernel processes Chroot restrictions * No attaching shared memory outside of chroot * No kill outside of chroot * No ptrace outside of chroot (architecture independent) * No capget outside of chroot * No setpgid outside of chroot * No getpgid outside of chroot * No getsid outside of chroot * No sending of signals by fcntl outside of chroot * No viewing of any process outside of chroot, even if /proc is mounted * No mounting or remounting * No pivot_root * No double chroot * No fchdir out of chroot * Enforced chdir("/") upon chroot * No (f)chmod +s * No mknod * No sysctl writes * No raising of scheduler priority * No connecting to abstract unix domain sockets outside of chroot * Removal of harmful privileges via capabilities * Exec logging within chroot Address space modification protection * PaX: Page-based implementation of non-executable user pages for i386, sparc, sparc64, alpha, parisc, amd64, ia64, ppc, and svr32; negligible performance hit on all i386 CPUs but Pentium 4 * PaX: Segmentation-based implementation of non-executable user pages for i386 with no performance hit * PaX: Segmentation-based implementation of non-executable KERNEL pages for i386 * PaX: Mprotect restrictions prevent new code from entering a task * PaX: Randomization of stack and mmap base for i386, sparc, sparc64, alpha, parisc, amd64, ia64, ppc, and mips * PaX: Randomization of heap base for i386, sparc, sparc64, alpha, parisc, amd64, ia64, ppc, and mips * PaX: Randomization of executable base for i386, sparc, sparc64, alpha, parisc, amd64, ia64, and ppc * PaX: Randomization of kernel stack * PaX: Protection against exploitation of all null ptr dereference bugs * PaX: Physical memory sanitization to prevent forensics * PaX: Automatically emulate sigreturn trampolines (for libc5, glibc 2.0, uClibc, Modula-3 compatibility) * PaX: No ELF .text relocations * PaX: Trampoline emulation (GCC and linux sigreturn) * PaX: PLT emulation for non-i386 archs * No kernel modification via /dev/mem, /dev/kmem, or /dev/port * Option to disable use of raw I/O * Removal of addresses from /proc//[maps|stat] Auditing features * Option to specify single group to audit * Exec logging with arguments * Denied resource logging * Chdir logging * Mount and unmount logging * IPC creation/removal logging * Signal logging * Failed fork logging * Time change logging Other features * /proc restrictions that don't leak information about process owners * Symlink/hardlink restrictions to prevent /tmp races * FIFO restrictions * Dmesg(8) restriction * Enhanced implementation of Trusted Path Execution * GID-based socket restrictions * Nearly all options are sysctl-tunable, with a locking mechanism * All alerts and audits support a feature that logs the IP address of the attacker with the log * Stream connections across unix domain sockets carry the attacker's IP address with them (on 2.4 only) * Detection of local connections: copies attacker's IP address to the other task * Automatic deterrence of exploit bruteforcing * Low, Medium, High, and Custom security levels * Tunable flood-time and burst for logging Lollobox doesn't protect you from Trojaned hardware/software Hardware that contains backdoors or unintentional features. Back doored or vulnerable software in the distribution portage. If you know of preferred hardware or software please mention in in our page Community/PreferredComponents?. "Hardware/Software" memory access * Some types of DMA with the collaboration of the OS. Please understand that this is an "hardware" attack and cannot be fixed without proper engineering from hardware vendors. Lollobox instead is mostly a software project and there are few things software can do to protect you from hardware defects and backdoors. Anyway if you correctly follow the instructions in BuildHowto/HardwareTweaking we believe this attack is mitigated. The mitigation anyhow is done through disable, which is not very cool but necessary. "Hardware" memory access or "physical-memory-DMA" DMA can subvert OS. Custom DMA device. PCI, PCMCIA, USB, Firewire http://www.csoonline.com/read/050106/ipods_pf.html * Firewire Firewire, DMA & Windows * Cardbus * Dock port * http://md.hudora.de/presentations/firewire/2005-firewire-cansecwest.pdf * USB MacLockPick Can be defeated (Rutkowska, 2007) Beyond The CPU: Defeating Hardware Based RAM Acquisition Tools (Part I: AMD case) More detailed informations: * Linux Device Drivers, 2nd Edition. Chapter 13: mmap and DMA * Rutkowska on Cheating Physical Memory Acquisition: Details Please understand that this is an "hardware" attack and cannot be fixed without proper engineering from hardware vendors. Lollobox instead is mostly a software project and there are few things software can do to protect you from hardware defects and backdoors. Anyway if you correctly follow the instructions in BuildHowto/HardwareTweaking we believe this attack is mitigated. The mitigation anyhow is done through disable, which is not very cool but necessary. "Hardware" memory dump * ColdBoot? Cold Boot Attacks on Encryption Keys Please understand that this is an "hardware" attack and cannot be fixed without proper engineering from hardware vendors. Lollobox instead is mostly a software project and there are few things software can do to protect you from hardware defects and backdoors. Anyway if you correctly follow the instructions in BuildHowto/HardwareTweaking we believe this attack is mitigated. The mitigation anyhow is done through disable, which is not very cool but necessary. Attachments * bh-dc-07-Rutkowska-up.pdf (0.8 MB) - added by ascii 7 months ago. "Beyond The CPU: Defeating Hardware Based RAM Acquisition (Joanna Rutkowska, Black Hat DC 2007)" * 2005-firewire-cansecwest.pdf (3.8 MB) - added by ascii 7 months ago. "FireWire?: all your memory are belong to us (Michael Becher, Maximillian Dornseif, Christian N. Klein, CanSecWest? 2005)" * pythonraw1394-1.0.tar.gz (447.5 KB) - added by anonymous 6 months ago. Hardware Requirements Needed components: * A notebook that satisfy the requirements described in this page. * An external boot device, like an USB key or a CD-ROM. Optionally needed components: * Soldier or soldiering station * Screwdrivers and the other tools needed to dismount some parts of your system (usually Torks, see HardwareTweaking/HardwareTweaking?_torks_screwdrivers_set.jpg). * Hot gule or anything you feel correct for the task Notebook You are virtually free to choose any notebook you want since Lollobox doesn't come with an installer, if you are able to successfully install Lollobox on the target system then the hardware you choose was the right one. For who is less brave please consider to strictly follow the recommendations. Good Linux support (requirement) Notebooks that are known to work very well with Linux are for example the Compaq Armada and HP NX6110. Other notebooks have a good support too, for an updated chart see Linux Laptop. Good luck with your choice (-; Ability to boot from USB or CD-ROM (requirement) Lollobox uses an external media for booting, suggested options is an USB stick or a CD-ROM. Your computer has to be able to boot from such device. BIOS boot password (requirement) A password prompt on boot and reboot is required in order to stop some (but sadly not all) physical attacks. A bios capable of password protecting it's own setup console is strongly recommended while the boot/reboot password alone could suffice if it's prompted before the attacker has the ability to ask for the setup console. Support for an opensource bios (recommended) While you could use the bios provided by the vendor nowadays there are many open source bios projects that can be audited and inspected and are less likely to contain unwanted features. * OpenBIOS * U-Boot * coreboot (also known as LinuxBIOS) We are currently investigating this field and would like to know your success/failure stories with such component. Boot device Even a system with FDE (Full Disk Encryption) has a boot loader and a boot partition that are unencrypted (except for TC, Trusted Computing, TPM assisted boot; a component that we absolutely dislike). This poses a great security risk in the case that somebody wants to dump or worst alter the contents of such cleartext data in order to subvert the cryptosystem. For this Lollobox uses an external boot device, a USB stick or a CD-ROM, that contains both the boot loader and the boot partition. Doing so the hard-disk inside the computer will exhibit only an apparently "random" stream of bytes (except for some information that dm-crypt, the chosen cryptosystem, stores about the algorithm). This setup works even without a proper partition table. USB sticks and CD-ROM have both advantages as disadvantaged as synthesized below: USB Stick CD-ROM Size Advantage: Small and easily to carry Disadvantage: Can be small but always bigger Tamperable Flaw: There is no real read-only Advantage: Is read-only if finalized Duplicable Advantage: It's easy to spot if replaced Disadvantage: Don't use a wildspread model Speed Advantage: Has good performance Advantage: Has good performance Synthesizing a CD-ROM is the preferred choice but you can safely switch to it after the system works using the USB stick. The USB stick if lost could get tampered in order to subvert the whole trust chain. Since dm-crypt needs a key to unlock the disk and this key has to be stored somewhere, in our case inside the external boot device, we choose to protect it with GPG (GNU Pretty Good Privacy). Doing so even if the boot media get lost the key is encrypted and the disk's contents cannot be unlocked without brute-forcing the password. As you probably understood this is a last resort protection and the physical security of the boot media is really important. Most of USB keys and CD-ROM copes with Lollobox requirements but if possible choose uncommon and high-quality items. Also remember to clone the boot device or the key and safely store it somewhere. Our advice is to buy a device that can be attached to your key chain so it's harder to lose and is small enough to be easily carried. Extras This section is totally optional and represents a collection of ideas that could apply to a Lollobox system. * Self destruction button * 007 USB Drive Hardware Tweaking Hardware tweaking is a necessary step to prevent or mitigate the attacks described in TheProject/DoesntProtectFrom. While we consider this section a requirement consider the possibility to apply such modifications only when you successfully build your system or in the cases where you already gained experience with Lollobox. Doing so will save you from rendering unsuitable your system form other scopes and us from your hate. Set a BIOS password It's very important to set a BIOS setup password. This should effectively lock the ability to change BIOS settings. Since the maximum password length is generally limited to 6 or 8 chars use the whole available length and spend some time thinking to a password hard to spot by somebody looking at you typing it (eg: avoid doubles), that is strong (use special chars and numbers) and that you can remember. There is no need to use one that is easy to type as once you have finalized the tuning of your system you will enter in the BIOS setup very very rarely. Remember to never reuse passwords! Chose one that you never used before and that you will never use again and that differ from the other bios password you are asked to use as explained in the next "Set a BIOS boot/reboot password" paragraph. Set a BIOS boot/reboot password It's very important to use a computer that has a BIOS with the ability to set two passwords, one for the setup as required by the previous paragraph and one for booting/rebooting. This will prevent most of the physical attacks that don't involve dismounting of the hardware. An obvious example is the cold-boot attack without the "cold" part that involves a computer reboot and booting a device with a special program able to dump the memory. The attacker has to use a media according on the one you choose (USB or CD-ROM). Note that some BIOS set a boot password but have a separate "ask the boot password also for reboots" option that have to be turned on. Disable other boot media Your BIOS should have a method of disabling boot from devices other than the primary disk inside your notebook, while this is the preferred way to go Lollobox uses an external device for booting. This is mainly a trade-off, a choice we made in the design. The idea is that is better to use a removable boot device that can be kept with yourself (think to the keys of your door or your bank OTP token) than have a cleartext /boot partition on the notebook hard-disk that can be tampered and is not easily verifiable. Disable all the other boot methods other than the one you choose (USB or CD-ROM) especially from network (PXE/Etherboot). Disable the Firewire (IEEE 1394) ports When possible disable the firewire port from the bios (example screenshot of a bios supporting this feature). Also consider real hardware hardening like glue the port, remove the controller (on some notebooks it's a removable part to facilitate the repair) or unsolder it. Combine software "bios" and hardware disable for maximum security. Please contact the development or documentation team to make us know your success/fail story. Disable Cardbus Also Cardbus has DMA access to the memory but the hardware and software requires to perform the infamous memory hijack is not available to the great public. As a side note a cheap hack is avaiable: using a firewire pcmcia adapter to get a firewire port able to perform the attack with the standard tools. This makes your Cardbus slots a viable entry from the attacker prospective (example picture of a cardbus/pcmcia device with both 1394 6-pin port and 1394 4-pin port). Some bios have the ability to disable cardbus, if so do it. The hardware tweak approach is similar to the Firewire one, both gluing, removing and unsolder are options you should mind. Please contact the development or documentation team to make us know your success/fail story. Disable USB This can be done only if your boot media is a CD-ROM. Most of the bios have the ability to disable the on-board controller (example screenshot of such feature). The hardware tweak approach is similar to the Firewire one, both gluing, removing and unsolder are options you should mind. Please contact the development or documentation team to make us know your success/fail story. Disable PCI-Express Also PCI-Express has DMA access to the memory but the hardware and software requires to perform the infamous memory hijack is not available to the great public. As a side note a cheap hack is avaiable: using a firewire pcmcia adapter to get a firewire port able to perform the attack with the standard tools. This makes your PCI-Express slots a viable entry from the attacker prospective (example of a PCI-Xpress device providing two 1394 6-pin ports). Please contact the development or documentation team to make us know your success/fail story. Disable easy removal of RAM chips As exposed in the second sentence of "Set a BIOS boot/reboot password" the cold-boot attack involve the dismounting of your RAM chip to be consequentially plugged in the attacker's equipment. RAM chips retain their data with progressive degradation for few minutes without the cooling and up to 10 minutes with the hydrogen cooling technique. Using hot glue to fix the chips to their slots can mitigate this type of attack as it require more effort and time to carry a successful attack. While for the other ports/bus/slots like Firewire and Cardbus BIOS disabling and un-soldiering can be an effective and revertible method for RAM chips it's not a viable option. Since it's a pure physical attack the only way to secure this component is to glue it. Quick start Before starting you should make sure to have everything needed and to be prepared to start an installation process that could seem crazy to most people. It will take time and require you to think and take decisions but in the meantime you probably will learn a lot and gain some security knowledge. Please understand that this project is not for everybody, don't start something that you will not finish successfully or you will inexorably end hating us and every single used component. Lollobox is just a tool: without a human capable of taking decisions and use a computer correctly it will not save you from threats. The main source for this page is http://www.gentoo.org/doc/en/gentoo-x86-quickinstall.xml. Materials checklist * A notebook (or a worstation) that satisfy the HardwareRequirements. * An external boot media as specified in the HardwareRequirements. * A broadband internet connection (like and ADSL or better). * A secondary system from where reading these instruction and Google/IRC. * A CD-writer and some virgin CDs. * The understanding that it will be long and perhaps complicated. Let's start First of all you need to download a Hardened Gentoo minimal install cd. The iso can be found from one of the mirrors. You can find the minimal CD ISO in releases/x86/current/installcd. The minimal installation CD is only useful for Internet-based installations. secondary $ wget "http://gentoo.osuosl.org/releases/x86/current/installcd/install-x86-minimal-2008.0.iso" --max-redirect=0 Once downloaded (it's about 89MB) verify the package with the sums from an other mirror. secondary $ wget "http://mirror.bytemark.co.uk/gentoo/releases/x86/current/installcd/install-x86-minimal-2008.0.iso.DIGESTS" --max-redirect=0 Sums should match, else there's a big problem. If this early stage fail don't delete the files and notify the compromise to us or to the Gentoo people over IRC. Burn the iso and boot it on your hardware verifying that is supported. Halt and power-off the system. Now prepare your hardware as described in the HardwareTweaking page. Once you have finished boot again with the live CD and verify again that you didn't damaged something. Booting Press F2 at the boot screen to find out what boot options exist. You can either start gentoo or gentoo-nofb, the latter disables the framebuffer. Normally just press enter. Several options allow to enable or disable some features. If all goes well, your hardware will be detected and all modules will be loaded. If the kernel fails to boot properly or if your computer hangs during the boot procedure, you may have to experiment with different configurations. The safest way is probably to use the nodetect option and then load required modules explicitly. Boot the minimal CD: Gentoo Linux Installation CD http://www.gentoo.org Enter to Boot; F1 for kernels F2 for options. boot: gentoo-nofb Or in case of problems: boot: gentoo-nofb nodetect If you used the nodetect option, once booted, load the required modules. You need to enable networking and have access to your disks. The lspci command can help you identify your hardware. Use lspci's output to identify required modules: livecd # lspci The following is an example, adapt it to your hardware: livecd # modprobe 3w-9xxx livecd # modprobe r8169 Network Configuration You can now start networking manually. The following example assigns the IP address 192.168.1.10 to your PC and defines 192.168.1.1 as your router and name server. livecd # ifconfig eth0 192.168.1.10/24 livecd # route add default gw 192.168.1.1 livecd # echo nameserver 192.168.1.1 > /etc/resolv.conf The installation CD allows you to start an sshd server, add additional users, run irssi (a command-line chat client) and surf the web using lynx or links. To make sure nobody wants to play with layer 2 Address Resolution Protocol (ARP) ping the gateway and verify it's MAC address. If it's correct you can set that MAC as static in the ARP table. livecd # ping 192.168.1.1 -c 2 livecd # arp -n Address HWtype HWaddress Flags Mask Iface 192.168.1.1 ether AA:BB:CC:DD:EE:FF CM eth0 livecd # arp -s 192.168.1.1 AA:BB:CC:DD:EE:FF livecd # arp -n Address HWtype HWaddress Flags Mask Iface 192.168.1.1 ether AA:BB:CC:DD:EE:FF CM eth0 Now the communication between you and the gateway is protected against ARP Spoofing/Poisoning, you probably want to do the same between your secondary computer and the target one running the live CD. livecd # ifconfig eth0 | grep HWaddr eth0 Link encap:Ethernet HWaddr AA:BB:CC:DD:EE:11 On the secondary system set the fixed ARP entry for the gateway. secondary # arp -s 192.168.1.1 AA:BB:CC:DD:EE:FF And then secondary # ping 192.168.1.10 -c 2 secondary # arp -n Address HWtype HWaddress Flags Mask Iface 192.168.1.10 ether AA:BB:CC:DD:EE:11 CM eth0 secondary # arp -s 192.168.1.10 AA:BB:CC:DD:EE:11 secondary # arp -n Address HWtype HWaddress Flags Mask Iface 192.168.1.1 ether AA:BB:CC:DD:EE:11 CM eth0 Note that the ARP for the target system (AA:BB:CC:DD:EE:11) got by the arp -s command should be the same as the one returned by the ifconfig command. If they don't match there's the possibility of someone poisoning your network. Installing a system in an ostile network is not a good idea and you should stop immediately and investigate who is hacking you. Now communication between the three involved machines (gateway, target and secondary) should be safer and you can proceed to the next step. Connect to your new box over ssh The most interesting feature is of course sshd. You can start it and then connect from another machine and cut and paste commands from this guide. Start sshd: livecd # /etc/init.d/sshd start * Generating hostkey ... (sshd generates the key and displays more output) * starting sshd ... [ok] Now, set the root password on the liveCD so that you can connect to it from another PC. Please note that allowing root to connect over ssh is not recommended under normal circumstances. If you can't trust your local network, use a long and complex password, you should use it only once as it will disappear after your first reboot. Set the root password: livecd # passwd New UNIX password: type_a_password Retype new UNIX password: type_a_password passwd: password updated successfully Now, you can start a terminal on the secondary PC and connect to your new box, follow the rest of this guide in another window, and cut and paste commands. Connect to your new box from another PC: secondary $ ssh root@192.168.1.10 The authenticity of host '192.168.1.10 (192.168.1.10)' can't be established. RSA key fingerprint is 96:e7:2d:12:ac:9c:b0:94:90:9f:40:89:b0:45:26:8f. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '192.168.1.10' (RSA) to the list of known hosts. Password: type_the_password Setup Disk * http://www.saout.de/misc/dm-crypt/ * https://help.ubuntu.com/community/EncryptedFilesystemHowto7 Big fat warning: this section is totally inaccurate an represents only a stub. Please wait until an alert like this has gone from all the pages of the BuildHowto before even trying to setup a system as we describe! Code Listing 2.9: Create the file systems and activate swap (ext2 is all you need on the /boot partition) livecd ~ # mke2fs /dev/sda1 (Let's use ext3 on the main partition) livecd ~ # mke2fs -j /dev/sda3 (Create and activate swap) livecd ~ # mkswap /dev/sda2 && swapon /dev/sda2 Mount the freshly created file systems on /mnt/gentoo. Create directories for the other mount points (like /mnt/gentoo/boot) if you need them and mount them too. Code Listing 2.10: Mount the file systems livecd ~ # mount /dev/sda3 /mnt/gentoo livecd ~ # mkdir /mnt/gentoo/boot livecd ~ # mount /dev/sda1 /mnt/gentoo/boot livecd ~ # cd /mnt/gentoo Setup Hardened Gentoo At this step of the manual you are going to install Gentoo in it's hardened flavor on the crypted filesystem you just created. Introduction Hardened Gentoo is a project which oversees the research, implementation, and maintainence of security oriented projects for Gentoo Linux. The homepage if the project can be foud at http://www.gentoo.org/proj/en/hardened/. Lollobox makes use of a number of subprojects made disposable by Hardened Gentoo. * PaX/Grsecurity Grsecurity is a complete security solution providing such features as a MAC or RBAC system, Chroot restrictions, address space modification protection (via PaX), auditing features, randomization features, linking restrictions to prevent file race conditions, ipc protections and much more. * Hardened Toolchain Transparent implementation of PaX address space layout randomizations and stack smashing protections using ELF shared objects as executables. * Hardened-Sources A kernel which provides patches for hardened subprojects, and stability/security oriented patches. Includes Grsecurity. Lollobox also includes various recommendations taken from the Bastille project. This means that it's really important that you choose the right hardened stage (an archieve that has to be decompressed in the new root and is the base gentoo filesystem) and the correct hardened profile or you will end with a normal Gentoo system that cannot be anymore converted to hardened. Umask settings Every time you boot the Gentoo install minimal cd the first task to be accomplished is to set a sane umask. Umask is the creation file mask under Unix systems and will determine the permissions of newly created files on the filesystem. Since filesystem security is a really important aspect in a Lollobox setup a proper umask has to be set early in order to always create files with strict permissions, even duiring installation. livecd # umask 077 livecd # umask -S u=rwx,g=,o= Set the date and UTC time First make sure your date and time is set correctly using date MMDDhhmmYYYY. Use UTC time. livecd # date Mon Mar 6 00:14:13 UTC 2006 Set the current date and time if required livecd # date 030600162006 (Format is MMDDhhmmYYYY) Mon Mar 6 00:16:00 UTC 2006 Download a stage3 archive Next, download a stage from one of our mirrors. Go to /mnt/gentoo and unpack the stage using tar xjpf . livecd # links http://www.gentoo.org/main/en/mirrors.xml Pick a mirror, move to the releases/x86/current/stages/hardened directory, highlight the stage3 of your choice, probably the i686 stage3 and press D to download it. Or download it directly with wget without choosing a nearby mirror: livecd # wget ftp://gentoo.osuosl.org/pub/gentoo/releases/x86/current/stages/hardened/stage3-i686*tar.bz2 Then verify the digest downloading it from a different mirror. livecd # wget ftp://gentoo.osuosl.org/pub/gentoo/releases/x86/current/stages/hardened/stage3-i686*tar.bz2.DIGESTS livecd # md5sum -c stage3-i686*tar.bz2.DIGESTS Unpack the stage3 archive livecd # tar xjpf stage3* Download and unpack the latest Portage snapshot Install the latest Portage snapshot. Proceed as for the stage3 archive: choose a nearby mirror from our list, download the latest snapshot and unpack it. livecd # cd /mnt/gentoo/usr livecd # links http://www.gentoo.org/main/en/mirrors.xml Pick a mirror, move to the snapshots/ directory, highlight portage-latest.tar.bz2 and press D to download it. Or download it directly with wget without choosing a nearby mirror livecd # cd /mnt/gentoo/usr livecd # wget http://gentoo.osuosl.org/snapshots/portage-latest.tar.bz2 Unpack the Portage snapshot livecd # tar xjf portage-lat* Chrooting Mount the /proc file system, copy over the /etc/resolv.conf file, then chroot into your Gentoo environment. livecd # cd / livecd # mount -t proc proc /mnt/gentoo/proc livedc # mount -o bind /dev /mnt/gentoo/dev livecd # cp -L /etc/resolv.conf /mnt/gentoo/etc/ livecd # chroot /mnt/gentoo /bin/bash livecd # env-update && source /etc/profile >>> Regenerating /etc/ld.so.cache... livecd # export PS1="(chroot) $PS1" Set your time zone Set your time zone information by using the correct listing in /usr/share/zoneinfo. livecd # ls /usr/share/zoneinfo (Using Brussels as an example) livecd # cp /usr/share/zoneinfo/Europe/Brussels /etc/localtime livecd # date Wed Mar 8 00:46:05 CET 2006 Edit /etc/conf.d/clock to define the time zone you used previously. livecd # nano -w /etc/conf.d/clock TIMEZONE="Europe/Brussels" Set your host name and domain name Set your host name in /etc/conf.d/hostname and /etc/hosts. In the following example, we use mybox as host name and at.myplace as domain name. You can either edit the config files with nano or use the following commands: livecd # cd /etc livecd # echo "127.0.0.1 mybox.at.myplace mybox localhost" > hosts livecd # sed -i -e 's/HOSTNAME.*/HOSTNAME="mybox"/' conf.d/hostname livecd # hostname mybox livecd # hostname -f mybox.at.myplace Kernel Configuration todo inaccurate and misleading section (hardened sources, need more recommendations about kernel options setup, etc) Install a kernel source (usually gentoo-sources), configure it, compile it and copy the arch/i386/boot/bzImage file to /boot. Install a kernel source, compile it and install the kernel livecd # emerge gentoo-sources livecd # cd /usr/src/linux Configure your kernel livecd # make menuconfig Build the kernel livecd # make -j2 livecd # make modules_install livecd # cp arch/i386/boot/bzImage /boot/kernel Configure /etc/fstab Edit your /etc/fstab and replace BOOT, ROOT and SWAP with the actual partition names. Don't forget to check that the file systems match your installation. Example fstab livecd # cd /etc livecd # nano -w fstab /dev/sda1 /boot ext2 noauto,noatime 1 2 /dev/sda3 / ext3 noatime 0 1 /dev/sda2 none swap sw 0 0 Configure networking Configure your network in /etc/conf.d/net. Add the net.eth0 init script to the default run level. If you have multiple NICs, symlink them to the net.eth0 init script and add them to the default run level as well. Either edit /etc/conf.d/net with nano or use the following commands: livecd # cd /etc/conf.d/ livecd # echo 'config_eth0=( "192.168.1.10/24" )' >> net livecd # echo 'routes_eth0=( "default via 192.168.1.1" )' >> net livecd # rc-update add net.eth0 default If you want to reconnect via ssh after you have rebooted your new box livecd # rc-update add sshd default Note: Emerge pcmciautils if you need support for PCMCIA cards. Set the root password Set the root password using passwd. livecd # passwd New UNIX password: type_the_password Retype new UNIX password: type_the_password_again passwd: password updated successfully Final /etc/rc.conf and /etc/conf.d/* configuration Check the system configuration in /etc/rc.conf, /etc/conf.d/rc, /etc/conf.d/keymaps and edit any of those files if required. Optional: edit some config files livecd # nano -w /etc/rc.conf livecd # nano -w /etc/conf.d/rc livecd # nano -w /etc/conf.d/keymaps Install a syslogger and a cron daemon Install a system logger like syslog-ng and a cron daemon like vixie-cron, and add them to the default run level. Note: Cron daemons depend on an MTA. mail-mta/ssmtp will be pulled in as a dependency. If you want to use a more advanced MTA, you might want to install it now. If you are in a hurry, let ssmtp be installed and remove it later when you install the MTA of your choice. livecd # emerge syslog-ng vixie-cron livecd # rc-update add syslog-ng default livecd # rc-update add vixie-cron default Installing System Tools Install the necessary file system tools (xfsprogs, reiserfsprogs or jfsutils) and networking tools (dhcpcd or ppp) if you need any. livecd # emerge xfsprogs (If you use the XFS file system) livecd # emerge jfsutils (If you use the JFS file system) livecd # emerge reiserfsprogs (If you use the Reiser file system) livecd # emerge dhcpcd (If you need a DHCP client) livecd # emerge ppp (If you need PPPoE ADSL connectivity) Extended informations about Gentoo and cron daemons can be found here http://www.gentoo.org/doc/en/cron-guide.xml. Use mirrorselect and set MAKEOPTS Start by selecting nearby mirrors either by defining the SYNC and GENTOO_MIRRORS variables in /etc/make.conf or by using mirrorselect. You can also define the number of concurrent compilation processes at this point. livecd # emerge mirrorselect livecd # mirrorselect -i -o >> /etc/make.conf livecd # mirrorselect -i -r -o >> /etc/make.conf Usually, (the number of processors + 1) is a good value livecd # echo 'MAKEOPTS="-j2"' >> /etc/make.conf View USE flags in use and enable or disable some Now is a good time to enable or disable some USE flags. Run emerge -vpe world to list all currently installed packages and their enabled and disabled USE flags. Either edit /etc/make.conf or use the following command to define the USE variable: mybox ~ # emerge -vpe world (Portage displays the packages and their USE flags, as an example, let's disable ipv6 and fortran, and enable unicode) mybox ~ # echo 'USE="nptl nptlonly -ipv6 -fortran unicode"' >> /etc/make.conf Last edit of make.conf Last but not least, you may want to alter the CFLAGS variable in your /etc/make.conf to optimise the code to your specific needs. Please note that using a long list of flags is rarely needed and can even lead to a broken system. It is recommended to specify the processor type in the march option and stick to -O2 -pipe. You may also want to switch to ~x86. You should only do this if you can deal with the odd broken ebuild or package. If you'd rather keep your system stable, don't add the ACCEPT_KEYWORDS variable. Adding FEATURES="ccache" is also a good idea. mybox # nano -w make.conf Set -march to your CPU type in CFLAGS CFLAGS="-O2 -march=athlon-xp -pipe" Add the following line FEATURES="ccache" You might want to recompile your whole system twice to make full use of your latest configuration changes. It would take quite a long time to complete and yield minimal speed benefits. You can let your system optimize itself gradually over time when new versions of packages are released. However, recompiling is a still good idea from the standpoint of maintaining system consistency. Please see the Gentoo GCC Upgrading Guide for a discussion on the benefits of ensuring a consistently built system and world. Recompiling only the packages that have already been updated since the release or that are affected by your new USE flags will take enough time. You might also have to remove packages that block your upgrade. Look for "[blocks B ]" in the output of emerge -vpuD --newuse world and use emerge -C to remove them. Update your packages Install ccache mybox # emerge ccache Please note that the switch to ~x86 causes many packages to be upgraded mybox # emerge -vpuD --newuse world Take a good look at the package list and their USE flags, remove blocking packages if any, and start the lengthy process mybox # time emerge -vuD --newuse world Remerge libtool to avoid further potential problems mybox # emerge --oneshot libtool Update config files, make sure you do not let dispatch-conf update config files you have edited mybox # dispatch-conf If perl has been updated, you should run the perl-cleaner script mybox # time perl-cleaner all In case of a major upgrade of python, you should run the python-updater script mybox # python-updater Setup Boot Configuring the Bootloader Emerge grub and configure it. Code Listing 2.27: Emerge grub and edit its configuration file livecd conf.d # time emerge grub livecd conf.d # nano -w /boot/grub/grub.conf Code Listing 2.28: Example grub.conf default 0 timeout 10 title Gentoo root (hd0,0) kernel /boot/kernel root=/dev/sda3 Code Listing 2.29: Install grub livecd conf.d # grub Probing devices to guess BIOS drives. This may take a long time. grub> root (hd0,0) Filesystem type is ext2fs, partition type 0xfd grub> setup (hd0) Checking if "/boot/grub/stage1" exists... yes Checking if "/boot/grub/stage2" exists... yes Checking if "/boot/grub/e2fs_stage1_5" exists... yes Running "embed /boot/grub/e2fs_stage1_5 (hd0)"... 16 sectors are embedded. succeeded Running "install /boot/grub/stage1 (hd0) (hd0)1+16 p (hd0,0)/boot/grub/stage2 /boot/ grub/menu.lst"... succeeded Done. grub> quit Reboot Exit the chrooted environment, unmount all file systems and reboot: Code Listing 2.30: Reboot livecd conf.d # exit livecd / # umount /mnt/gentoo/proc /mnt/gentoo/boot /mnt/gentoo livecd / # reboot (Don't forget to remove the CD) Finalizing the Installation Code Listing 2.31: Connect to your new box from another PC (Clean up your known_hosts file because your new box has generated a new definitive hostkey) $ nano -w ~/.ssh/known_hosts (Look for the IP of your new PC and delete the line, then save the file and exit nano) (Use the IP address of your new box) $ ssh root@192.168.1.10 The authenticity of host '192.168.1.10 (192.168.1.10)' can't be established. RSA key fingerprint is 96:e7:2d:12:ac:9c:b0:94:90:9f:40:89:b0:45:26:8f. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '192.168.1.10' (RSA) to the list of known hosts. Password: type_the_password Big fat warning: this section is totally inaccurate an represents only a stub. Please wait until an alert like this has gone from all the pages of the BuildHowto before even trying to setup a system as we describe''' le righe di avvio di grub sono le seguenti title Gentoo ElDios? KryptoMania? root (hd0,1) kernel /kernel vga=792 real_root=/dev/mapper/KM-root crypt_root=/dev/sda2 key_file=chiave key_dev=/dev/sdb2 initrd /initrd_KM.gz ovviamente devi adattare tutto al tuo contesto nello specifico il file chiave un file che vuoi anzi scusa il file che hai usato per crittare la partizione protetto da GPG con password e lo devi mettere nella partizione di boot che sta sulla chiavetta System hardening Is Linux secure? The question is much less useful, than 'Is Linux "securable"?' The answer to the latter is a definite yes. Being securable means that Linux can be made more secure (to whatever degree necessary) by applying a clearly defined sequence of steps that always produces the same result, and that can be automated and applied to systems that have been in operation for a long time. It would be ideal to be able to make securing systems understandable by regular system administrators who don’t have formal security training. However, the last requirement might be pushing it a bit, since security will likely always require expertise. Typical steps that are taken during the system hardening include: 1. Minimizing installed software 2. Patching the system 3. Securing filesystem permissions and S*ID binaries 4. Improving login and user security 5. Setting some physical and boot security controls 6. Securing the daemons via network access controls 7. Increasing logging and audit information 8. Configuring vendor supplied security software (IDS, host firewall) It is curious to note that hardening is not just a matter of fixing bad defaults the vendors throw at users. It is believed that vendors ship systems with mostly open default setting based on customer feedback. Thus hardening should be viewed not as "fighting the evil vendor", but rather as optimizing the system based on local business and security needs. The main source of this page is http://www.gentoo.org/doc/en/security/security-handbook.xml?full=1 while the intro is taken from http://www.securityfocus.com/infocus/1539. Additional ever-green raccomandations are from http://www.puschitz.com/SecuringLinux.shtml. Physical Security No matter how many safeguards you implement, they can all be easily circumvented by an attacker with physical access to your computer. Despite this, there are at least some measures that can be taken to provide a degree of security against an attacker with physical access to your machine. Putting your hardware in a locked closet prevents an attacker from simply unplugging it and carting it off. Locking your computer's case is also a good idea, to make sure that an attacker cannot simply walk away with your hard drive. To prevent an attacker from booting from another disk, nicely circumventing your permissions and login restrictions, try setting a BIOS password. It is also important to set a GRUB boot password, to prevent a malicious user from booting into single-user mode and gaining complete access to your system. It's very important that you carefully understand the threats described in TheProject/DoesntProtectFrom and follow all the applicable instructions in BuildHowto/HardwareTweaking. Password protecting GRUB GRUB supports password protection to your boot loader. The method choosen to store the password for Lollobox is the md5+salt encryption. If no password is entered at boot, GRUB will simply use the default boot setting. When adding an md5 password, you must convert your password into crypt format, which is the same format used in /etc/shadow. Warning: remember to choose a strong password that you can easily write from the keyboard and remember. It should not be a password that you will or have used in other contexts. You can encrypt your password directly at the GRUB shell: #/sbin/grub GRUB version 0.92 (640K lower / 3072K upper memory) [ Minimal BASH-like line editing is supported. For the first word, TAB lists possible command completions. Anywhere else TAB lists the possible completions of a device/filename. ] grub> md5crypt Password: ******** (Typed changeme at the prompt) Encrypted: $1$T7/dgdIJ$dJM.n2wZ8RG.oEiIOwJUs. grub> quit Then, cut and paste your password to /boot/grub/grub.conf. timeout 5 password --md5 $1$T7/dgdIJ$dJM.n2wZ8RG.oEiIOwJUs. The 5 seconds timeout becomes handy if the system is remote and should be able to reboot without any keyboard interaction. Learn more about GRUB passwords by executing info grub. Restricting console usage The /etc/securetty file allows you to specify which tty (terminal) devices root is allowed to login to. We suggest that you comment out all lines except vc/1 if you are using devfs and all lines except tty1 if you are using udev. This will ensure that root only can login once and only on one terminal. Note: Users in the group "wheel" can still su - to become root on other TTYs. Edit your /etc/securetty as follows: (For devfs) vc/1 (For udev) tty1 Reviewing Inittab and Boot Scripts The inittab file /etc/inittab also describes which processes are started at bootup and during normal operation. It is recommended to ensure that all entries in /etc/inittab are legitimate in your environment. I would at least remove the CTRL-ALT-DELETE trap entry to prevent accidental reboots: # sed -i 's/ca::ctrlaltdel:/#ca::ctrlaltdel:/g' The default runlevel should be set to 3 to disable automatic X11 (X Windows System) startup. # grep ':initdefault' /etc/inittab id:3:initdefault: To have changes in /etc/inittab become effective immediately, you can run: # init q The /etc/rc.local script is used for commands or startup scripts which are pertinent only to a specific server. (/etc/rc.local is a link to /etc/rc.d/rc.local). Ensure that all startup scripts in /etc/rc.d/rc.local are legitimate. Single User Mode Password for root Some admins suggest to add the following line to the /etc/inittab file to ensure that a root password is required for Single User Mode logons: ~~:S:wait:/sbin/sulogin This works but can be circumvented easily! At the GRUB or LILO prompt you can tell the boot loader to alternate the init program by using the boot params "init=/bin/bash". This will place you at a root shell prompt without a password. Disable "Three Finger Salute" Edit /etc/inittab and comment out the following to disable CTRL+ALT+CANC. # What to do at the "Three Finger Salute". ca:12345:ctrlaltdel:/sbin/shutdown -r now Disable Xorg "Two Finger Salute" Edit /etc/X11/xorg.conf Section "ServerFlags" Option "DontZap" "yes" EndSection Checking Accounts Checking for unlocked accounts It is important that all system and vendor accounts that are not used for logins are locked. To get a list of unlocked accounts on your system, you can check for accounts that do NOT have an encrypted password string starting with "!" or "*" in the /etc/shadow file. If you lock an account using passwd -l, it will put a '!!' in front of the encrypted password, effectively disabling the password. If you lock an account using usermod -L, it will put a '!' in front of the encrypted password. Many system and shared accounts are usually locked by default by having a '*' or '!!' in the password field which renders the encrypted password into an invalid string. To remove the password from an unused account: passwd -ld Hence, to get a list of all unlocked (encryptable) accounts, run (compare the expected output with yours, if it differ check the DontPanic? page): # egrep -v '.*:\*|:\!' /etc/shadow | awk -F: '{print $1}' root ll_desktop ll_mail ll_web ll_irc Also make sure all accounts have a 'x' in the password field in /etc/passwd. The following command lists all accounts that do not have a 'x' in the password field (should return nothing): # grep -v ':x:' /etc/passwd A 'x' in the password fields means that the password has been shadowed, i.e. the encrypted password has to be looked up in the /etc/shadow file. If the password field in /etc/passwd is empty, then the system will not lookup the shadow file and it will not prompt the user for a password at the login prompt. Checking for unused accounts All system or vendor accounts that are not being used by users, applications, by the system or by daemons should be removed from the system. You can use the following command to find out if there are any files owned by a specific account: # find / -path /proc -prune -o -user -ls The -prune option in this example is used to skip the /proc filesystem. If you are sure that an account can be deleted, you can remove the account using the following command: # userdel -r Without the "-r" option userdel will not delete the user's home directory and mail spool (/var/spool/mail/). Note that many system accounts have no home directory. Disable and tune local services todo ps aux etc Sudo echo "app-admin/sudo offensive -pam" >> /etc/portage/package.use emerge sudo Using visudo delete the previous contents and insert these: # Lollobox /etc/sudoers Defaults env_reset Defaults:ALL env_reset Defaults:ALL !syslog Defaults:ALL logfile=/var/log/sudoers.log Defaults:ALL timestamp_timeout=0 Defaults:ALL tty_tickets # Enable if you use non-interactive sudo in some script of yours #root ALL=(ALL) ALL ll_desktop ALL=(ALL) ALL ll_desktop ALL=(ALL) NOPASSWD:/bin/halt todo: stub, explain and expand! Disable and tune network services Server socket bind tuning One of the most important tasks is to detect and close network ports that are not needed. Since Lollobox is aimed as a personal system you don't need any externally accessible service. This means that no service should listen on external interfaces or worst bind on any interface. To get a list of listening network ports (TCP and UDP sockets) and associated process, you can run the following command: # netstat -anptu [todo output] All the unneeded services must be disabled and needed services must listen on localhost only. Once you have tuned the configuration files of a service and restarted it run again the netstat command and chech that the output is conguent. Running a port scanner from your secondary machine will confirm that the lockdown process was succesfully: # nmap -TU -p- [todo output] Now perform a local scan and compare the results with netstat. # nmap -TU -p- [todo output] Another method to list all of the TCP and UDP sockets to which programs are listening is lsof: # lsof -i -n | egrep 'COMMAND|LISTEN|UDP' todo output Restricting network access Usually a firewall is used to protect a server from other servers and networks. However, in some cases you may also want to protect a server within a network by using a TCP Wrapper. The Xinetd super server that comes with most Linux distributions includes a built-in TCP wrapper. It can be used to explicitly define network services to accept incoming connections from specified servers and networks. The TCP wrappers implements access control through the use of two files, /etc/hosts.allow and /etc/hosts.deny. Note that the hosts.allow file takes precedence over the hosts.deny file. And you may want to change the permissions on the two configuration files since they are both world readable. A recommended security-strategy is to block all incoming requests by default, but allow specific hosts or networks to connect. This is the strategy I will describe here. To deny everything by default, add the following line to /etc/hosts.deny: ALL: ALL To accept incoming SSH connections from e.g. nodes rac1cluster, rac2cluster and rac3cluster, add the following line to /etc/hosts.allow: sshd: rac1cluster rac2cluster rac3cluster To accept incoming SSH connections from all servers from a specific network, add the name of the subnet to /etc/hosts.allow. For example: sshd: rac1cluster rac2cluster rac3cluster .subnet.example.com To accept incoming portmap connections from IP address 192.168.0.1 and subnet 192.168.5, add the following line to /etc/hosts.allow: portmap: 192.168.0.1 192.168.5. To accept connections from all servers on subnet .subnet.example.com but not from server cracker.subnet.example.com, you could add the following line to /etc/hosts.allow: ALL: .subnet.example.com EXCEPT cracker.subnet.example.com Here are other examples that show some features of TCP wrapper: If you just want to restrict ssh connections without configuring or using /etc/hosts.deny, you can add the following entries to /etc/hosts.allow: sshd: rac1cluster rac2cluster rac3cluster sshd: ALL: DENY The version of TCP wrapper that comes with Red Hat also supports the extended options documented in the hosts_options(5) man page. Here is an example how an additional program can be spawned in e.g. the /etc/hosts.allow file: sshd: ALL : spawn echo "Login from %c to %s" | mail -s "Login Info for %s" log@loghost For information on the % expansions, see "man 5 hosts_access". The TCP wrapper is quite flexible. And xinetd provides its own set of host-based and time-based access control functions. You can even tell xinetd to limit the rate of incoming connections. I recommend reading various documentations about the Xinetd super daemon on the Internet. Securing SSH Many network services like telnet, rlogin, and rsh are vulnerable to eavesdropping which is one of several reasons why SSH should be used instead. Red Hat's default configuration for SSH meets the security requirements for many environments. However, there are a few parameters in /etc/ssh/sshd_config that you may want to change on RHEL and other Linux systems. The chapter Restricting System Access from Servers and Networks shows how direct logins can be disabled for shared and system accounts including root. But it's prudent to disable direct root logins at the SSH level as well. PermitRootLogin? no Also ensure to have privilege separation enabled where the daemon is split into two parts. With privilege separation a small part of the code runs as root and the rest of the code runs in a chroot jail environment. Note that on older RHEL systems this feature can break some functionality, for example see Preventing Accidental Denial of Service. UsePrivilegeSeparation? yes Since SSH protocol version 1 is not as secure you may want to limit the protocol to version 2 only: Protocol 2 You may also want to prevent SSH from setting up TCP port and X11 forwarding if you don't need it: AllowTcpForwarding? no X11Forwarding no Ensure the StrictModes? directive is enabled which checks file permissions and ownerships of some important files in the user's home directory like ~/.ssh, ~/.ssh/authorized_keys etc. If any checks fail, the user won't be able to login. StrictModes? yes Ensure that all host-based authentications are disabled. These methods should be avoided as primary authentication. IgnoreRhosts? yes HostbasedAuthentication? no RhostsRSAAuthentication no Disable sftp if it's not needed: #Subsystem sftp /usr/lib/misc/sftp-server After changing any directives make sure to restart the sshd daemon: /etc/init.d/sshd restart Logging Extra logging should be added to catch warnings or errors that might indicate an ongoing attack or a successful compromise. Attackers often scan or probe before attacking. It's also vital that your log files are easily readable and manageable. Gentoo Linux lets you choose between 3 different loggers when installing. Syslog-ng Syslog-ng provides some of the same features as syslog and metalog with a small difference. It can filter messages based on level and content (like metalog), provide remote logging like syslog, handle logs from syslogd (even streams from Solaris), write to a TTY, execute programs, and it can act as a logging server. Basically it is the best of both loggers combined with advanced configuration. Below is a classic /etc/syslog-ng/syslog-ng.conf configuration file slightly modified. options { chain_hostnames(off); sync(0); }; # Source where to read log source src { unix-stream("/dev/log"); internal(); }; source kernsrc { file("/proc/kmsg"); }; # Define destinations destination authlog { file("/var/log/auth.log"); }; destination syslog { file("/var/log/syslog"); }; destination cron { file("/var/log/cron.log"); }; destination daemon { file("/var/log/daemon.log"); }; destination kern { file("/var/log/kern.log"); }; destination lpr { file("/var/log/lpr.log"); }; destination user { file("/var/log/user.log"); }; destination mail { file("/var/log/mail.log"); }; destination mailinfo { file("/var/log/mail.info"); }; destination mailwarn { file("/var/log/mail.warn"); }; destination mailerr { file("/var/log/mail.err"); }; destination newscrit { file("/var/log/news/news.crit"); }; destination newserr { file("/var/log/news/news.err"); }; destination newsnotice { file("/var/log/news/news.notice"); }; destination debug { file("/var/log/debug"); }; destination messages { file("/var/log/messages"); }; destination console { usertty("root"); }; destination console_all { file("/dev/tty12"); }; destination xconsole { pipe("/dev/xconsole"); }; # Create filters filter f_authpriv { facility(auth, authpriv); }; filter f_syslog { not facility(authpriv, mail); }; filter f_cron { facility(cron); }; filter f_daemon { facility(daemon); }; filter f_kern { facility(kern); }; filter f_lpr { facility(lpr); }; filter f_mail { facility(mail); }; filter f_user { facility(user); }; filter f_debug { not facility(auth, authpriv, news, mail); }; filter f_messages { level(info..warn) and not facility(auth, authpriv, mail, news); }; filter f_emergency { level(emerg); }; filter f_info { level(info); }; filter f_notice { level(notice); }; filter f_warn { level(warn); }; filter f_crit { level(crit); }; filter f_err { level(err); }; filter f_failed { match("failed"); }; filter f_denied { match("denied"); }; # Connect filter and destination log { source(src); filter(f_authpriv); destination(authlog); }; log { source(src); filter(f_syslog); destination(syslog); }; log { source(src); filter(f_cron); destination(cron); }; log { source(src); filter(f_daemon); destination(daemon); }; log { source(kernsrc); filter(f_kern); destination(kern); }; log { source(src); filter(f_lpr); destination(lpr); }; log { source(src); filter(f_mail); destination(mail); }; log { source(src); filter(f_user); destination(user); }; log { source(src); filter(f_mail); filter(f_info); destination(mailinfo); }; log { source(src); filter(f_mail); filter(f_warn); destination(mailwarn); }; log { source(src); filter(f_mail); filter(f_err); destination(mailerr); }; log { source(src); filter(f_debug); destination(debug); }; log { source(src); filter(f_messages); destination(messages); }; log { source(src); filter(f_emergency); destination(console); }; # Default log log { source(src); destination(console_all); }; Syslog-ng is very easy to configure, but it is also very easy to miss something in the configuration file since it is huge. The author still promises some extra features like encryption, authentication, compression and MAC (Mandatory Access Control) control. With these options it will be a perfect for network logging, since the attacker cannot spy on the log. And syslog-ng does have one other advantage: it does not have to run as root! Log analysis with Logcheck Of course, keeping logs alone is only half the battle. An application such as Logcheck can make regular log analysis much easier. Logcheck is a script, accompanied by a binary called logtail, that runs from your cron daemon and checks your logs against a set of rules for suspicious activity. It then mails the output to root's mailbox. Logcheck and logtail are part of the app-admin/logsentry package. Logcheck uses four files to filter important log entries from the unimportant. These files are logcheck.hacking, which contains known hacking attack messages, logcheck.violations, which contains patterns indicating security violations, logcheck.violations.ignore, which contains keywords likely to be matched by the violations file, allowing normal entries to be ignored, and logcheck.ignore, which matches those entries to be ignored. Warning: Do not leave logcheck.violations.ignore empty. Logcheck uses grep to parse logs, some versions of which will take an empty file to mean wildcard. All violations would thus be ignored. Mounting Partitions When mounting an ext2, ext3, or reiserfs partition, you have several options you can apply to the file /etc/fstab. The options are: * nosuid - Will ignore the SUID bit and make it just like an ordinary file * noexec - Will prevent execution of files from this partition * nodev - Ignores devices Unfortunately, these settings can easily be circumvented by executing a non-direct path. However, setting /tmp to noexec will stop the majority of exploits designed to be executed directly from /tmp. /etc/fstab /dev/sda1 /boot ext2 noauto,noatime 1 1 /dev/sda2 none swap sw 0 0 /dev/sda3 / reiserfs notail,noatime 0 0 /dev/sda4 /tmp reiserfs notail,noatime,nodev,nosuid,noexec 0 0 /dev/sda5 /var reiserfs notail,noatime,nodev 0 0 /dev/sda6 /home reiserfs notail,noatime,nodev,nosuid 0 0 /dev/sda7 /usr reiserfs notail,noatime,nodev,ro 0 0 /dev/cdroms/cdrom0 /mnt/cdrom iso9660 noauto,ro 0 0 proc /proc proc defaults 0 0 Warning: Placing /tmp in noexec mode can prevent certain scripts from executing properly. Note: For disk quotas see the Quotas section. Note: I do not set /var to noexec or nosuid, even if files normally are never executed from this mount point. The reason for this is that netqmail is installed in /var/qmail and must be allowed to execute and access one SUID file. I setup /usr in read-only mode since I never write anything there unless I want to update Gentoo. Then I remount the file system in read-write mode, update and remount again. Note: Even if you do not use netqmail, Gentoo still needs the executable bit set on /var/tmp since ebuilds are made here. But an alternative path can be setup if you insist on having /var mounted in noexec mode. Securing /tmp Now /tmp will be purged and recreated with safe defaults. rm /tmp -rf mkdir /tmp chown root:root /tmp chmod 1777 /tmp After the cleanup it's possible to proceed. # dd if=/dev/zero of=/var/tmp_fs bs=1024 count=256000 # mke2fs /var/tmp_fs mke2fs 1.40.9 (27-Apr-2008) /var/tmp_fs is not a block special device. Proceed anyway? (y,n) y # echo "/var/tmp_fs /tmp ext2 loop,noexec,nosuid,nodev,noatime,rw 0 0" >> /etc/fstab # mount /tmp/ # chmod 1777 /tmp To clean the /tmp at every boot edit /etc/conf.d/local.start using the following commands: # echo >> /etc/conf.d/local.start # echo "# Lollobox: /tmp cleanup" >> /etc/conf.d/local.start # echo "# Insecure example: rm /tmp/* -rf" >> /etc/conf.d/local.start # echo "rm /tmp -rf" >> /etc/conf.d/local.start User/Group Limitations /etc/security/limits.conf Controlling resource usage can be very effective when trying to prevent a local Denial of Service or restricting the maximum allowed logins for a group or user. However, too strict settings will impede on your system's behavior and will result in program failures so make sure that you check each setting first. /etc/security/limits.conf * soft core 0 * hard core 0 * hard nproc 15 * hard rss 10000 * - maxlogins 2 @dev hard core 100000 @dev soft nproc 20 @dev hard nproc 35 @dev - maxlogins 10 If you find yourself trying to set nproc or maxlogins to 0, maybe you should delete the user instead. The example above sets the group dev settings for processes, core file and maxlogins. The rest is set to a default value. Note: /etc/security/limits.conf is part of the PAM package and will only apply to packages that use PAM. /etc/limits /etc/limits is very similar to the limit file /etc/security/limits.conf. The only difference is the format and that it only works on users or wild cards (not groups). Let's have a look at a sample configuration: /etc/limits * L2 C0 U15 R10000 kn L10 C100000 U35 Here we set the default settings and a specific setting for the user kn. Limits are part of the sys-apps/shadow package. It is not necessary to set any limits in this file if you have enabled pam in /etc/make.conf. Quotas Warning: Make sure the file systems you are working with support quotas. In order to use quotas on ReiserFS, you must patch your kernel with patches available from Namesys. User tools are available from the Linux DiskQuota? project. While quotas do work with ReiserFS, you may encounter other issues while trying to use them--you have been warned! Putting quotas on a file system restricts disk usage on a per-user or per-group basis. Quotas are enabled in the kernel and added to a mount point in /etc/fstab. The kernel option is enabled in the kernel configuration under File systems->Quota support. Apply the following settings, rebuild the kernel and reboot using the new kernel. Start by installing quotas with emerge quota. Then modify your /etc/fstab and add usrquota and grpquota to the partitions that you want to restrict disk usage on, like in the example below. /etc/fstab /dev/sda1 /boot ext2 noauto,noatime 1 1 /dev/sda2 none swap sw 0 0 /dev/sda3 / reiserfs notail,noatime 0 0 /dev/sda4 /tmp ext3 noatime,nodev,nosuid,noexec,usrquota,grpquota 0 0 /dev/sda5 /var ext3 noatime,nodev,usrquota,grpquota 0 0 /dev/sda6 /home ext3 noatime,nodev,nosuid,usrquota,grpquota 0 0 /dev/sda7 /usr reiserfs notail,noatime,nodev,ro 0 0 /dev/cdroms/cdrom0 /mnt/cdrom iso9660 noauto,ro 0 0 proc /proc proc defaults 0 0 On every partition that you have enabled quotas, create the quota files (aquota.user and aquota.group) and place them in the root of the partition. Creating the quota files # touch /tmp/aquota.user # touch /tmp/aquota.group # chmod 600 /tmp/aquota.user # chmod 600 /tmp/aquota.group This step has to be done on every partition where quotas are enabled. After adding and configuring the quota files, we need to add the quota script to the boot run level. Important: XFS does all quota checks internally, and does not need the quota script added to the boot runlevel. There may be other filesystems not listed in this document with similar behavior, so please read the manpages for your filesystem to learn more about how it handles quota checks. Code Listing 3.3: Adding quota to the boot runlevel # rc-update add quota boot We will now configure the system to check the quotas once a week by adding the following line to /etc/crontab: Adding quota check to crontab 0 3 * * 0 /usr/sbin/quotacheck -avug. After rebooting the machine, it is time to setup the quotas for users and groups. edquota -u kn will start the editor defined in $EDITOR (default is nano) and let you edit the quotas of the user kn. edquota -g will do the same thing for groups. Setting up quota's for user kn Quotas for user kn: /dev/sda4: blocks in use: 2594, limits (soft = 5000, hard = 6500) inodes in use: 356, limits (soft = 1000, hard = 1500) For more detail read man edquota or the Quota mini howto. /etc/login.defs If your security policy states that users should change their password every other week, change the value PASS_MAX_DAYS to 14 and PASS_WARN_AGE to 7. It is recommended that you use password aging since brute force methods can find any password, given enough time. We also encourage you to set LOG_OK_LOGINS to yes. /etc/login.access The login.access file is also part of the sys-apps/shadow package, which provides a login access control table. This table is used to control who can and cannot login based on user name, group name or host name. By default, all users on the system are allowed to login, so the file consists only of comments and examples. Whether you are securing your server or workstation, we recommend that you setup this file so no one other than yourself (the admin) has access to the console. Note: These settings do not apply for root. /etc/login.access -:ALL EXCEPT wheel sync:console -:wheel:ALL EXCEPT LOCAL .gentoo.org Important: Be careful when configuring these options, since mistakes will leave you with no access to the machine if you do not have root access. Note: These settings do not apply to SSH, since SSH does not execute /bin/login per default. This can be enabled by setting UseLogin? yes in /etc/ssh/sshd_config. This will setup login access so members of the wheel group can login locally or from the gentoo.org domain. Maybe too paranoid, but better to be safe than sorry. Securing filesystem permissions Umask todo 077 World/Group writable Normal users should not have access to configuration files or passwords. An attacker can steal passwords from databases or web sites and use them to deface--or even worse, delete--data. This is why it is important that your file permissions are correct. If you are sure that a file is only used by root, assign it with the permissions 0600 and assign the file to the correct user with chown. Finding world-writable files and directories # find / -type f \( -perm -2 -o -perm -20 \) -exec ls -lg {} \; 2>/dev/null >writable.txt # find / -type d \( -perm -2 -o -perm -20 \) -exec ls -ldg {} \; 2>/dev/null >>writable.txt This will create a huge file with permission of all files having either write permission set to the group or everybody. Check the permissions and eliminate world writable files to everyone, by executing /bin/chmod o-w on the files. SUID/SGID files Files with the SUID or SGID bit set execute with privileges of the owning user or group and not the user executing the file. Normally these bits are used on files that must run as root in order to do what they do. These files can lead to local root compromises (if they contain security holes). This is dangerous and files with the SUID or SGID bits set should be avoided at any cost. If you do not use these files, use chmod 0 on them or unmerge the package that they came from (check which package they belong to by using equery; if you do not already have it installed simply type emerge gentoolkit). Otherwise just turn the SUID bit off with chmod -s. Finding setuid files # find / -type f \( -perm -004000 -o -perm -002000 \) -exec ls -lg {} \; 2>/dev/null >suidfiles.txt This will create a file containing a list of all the SUID/SGID files. List of setuid binaries /bin/su /bin/ping /bin/mount /bin/umount /var/qmail/bin/qmail-queue /usr/bin/chfn /usr/bin/chsh /usr/bin/crontab /usr/bin/chage /usr/bin/expiry /usr/bin/sperl5.6.1 /usr/bin/newgrp /usr/bin/passwd /usr/bin/gpasswd /usr/bin/procmail /usr/bin/suidperl /usr/lib/misc/pt_chown /usr/sbin/unix_chkpwd /usr/sbin/traceroute /usr/sbin/pwdb_chkpwd By default Gentoo Linux does not have a lot of SUID files (though this depends on what you installed), but you might get a list like the one above. Most of the commands should not be used by normal users, only root. Switch off the SUID bit on ping, mount, umount, chfn, chsh, newgrp, suidperl, pt_chown and traceroute by executing chmod -s on every file. Don't remove the bit on su, qmail-queue or unix_chkpwd. Removing setuid from those files will prevent you from su'ing and receiving mail. By removing the bit (where it is safe to do so) you remove the possibility of a normal user (or an attacker) gaining root access through any of these files. The only SUID files that I have on my system are su, passwd, gpasswd, qmail-queue, unix_chkpwd and pwdb_chkpwd. But if you are running X, you might have some more, since X needs the elevated access afforded by SUID. Fixing /usr/bin/man mybox ~ $ sudo su - mybox ~ # ls -la `which man` mybox ~ # chmod 551 `which man`; mybox ~ # chown root:root `which man` mybox ~ # ls -la `which man` -r-xr-x--x 1 root root 51088 Sep 5 11:04 /usr/bin/man mybox ~ # exit mybox ~ $ man man SUID/SGID binaries and Hard links A file is only considered deleted when there are no more links pointing to it. This might sound like a strange concept, but consider that a filename like /usr/bin/perl is actually a link to the inode where the data is stored. Any number of links can point to the file, and until all of them are gone, the file still exists. If your users have access to a partition that isn't mounted with nosuid or noexec (for example, if /tmp, /home, or /var/tmp are not separate partitions) you should take care to ensure your users don't create hard links to SUID or SGID binaries, so that after Portage updates they still have access to the old versions. Warning: if you have received a warning from portage about remaining hard links, and your users can write to a partition that allows executing SUID/SGID files, you should read this section carefully. One of your users may be attempting to circumvent your update by keeping an outdated version of a program. If your users cannot create their own SUID files, or can only execute programs using the dynamic loader (partitions mounted noexec), you do not have to worry. Note: Users do not need read access to a file to create a link to it, they only need read permission to the directory that contains it. To check how many links a file has, you can use the stat command. Stat command $ stat /bin/su File: `/bin/su' Size: 29350 Blocks: 64 IO Block: 131072 regular file Device: 900h/2304d Inode: 2057419 Links: 1 Access: (4711/-rws--x--x) Uid: ( 0/ root) Gid: ( 0/ root) Access: 2005-02-07 01:59:35.000000000 +0000 Modify: 2004-11-04 01:46:17.000000000 +0000 Change: 2004-11-04 01:46:17.000000000 +0000 To find the SUID and SGID files with multiple links, you can use find. Finding multiply linked suid/sgid binaries $ find / -type f \( -perm -004000 -o -perm -002000 \) -links +1 -ls Unowned files Files not owned by any user or group might not necessarily be a security problem in itself. However, unowned files could pose a security problem in the future. For example, if a new user is created and the new users happens to get the same UID as the unowned files have, then this new user will automatically become the owner of these files. To locate files not owned by any user or group, use the following command: find / -path /proc -prune -o -nouser -o -nogroup /root protection /home protections /var/log protections User home protections Please refer to BuildHowto/CreatingUsers. PAM PAM is a suite of shared libraries that provide an alternative way providing user authentication in programs. The pam USE flag is turned on by default. Thus the PAM settings on Gentoo Linux are pretty reasonable, but there is always room for improvement. First install cracklib. Installing cracklib # emerge cracklib /etc/pam.d/passwd auth required pam_unix.so shadow nullok account required pam_unix.so password required pam_cracklib.so difok=3 retry=3 minlen=8 dcredit=-2 ocredit=-2 password required pam_unix.so md5 use_authtok session required pam_unix.so This will add the cracklib which will ensure that the user passwords are at least 8 characters and contain a minimum of 2 digits, 2 other characters, and are more than 3 characters different from the last password. This forces the user to choose a good password (password policy). Check the PAM documentation for more options. /etc/pam.d/sshd auth required pam_unix.so nullok auth required pam_shells.so auth required pam_nologin.so auth required pam_env.so account required pam_unix.so password required pam_cracklib.so difok=3 retry=3 minlen=8 dcredit=-2 ocredit=-2 use_authtok password required pam_unix.so shadow md5 session required pam_unix.so session required pam_limits.so Every service not configured with a PAM file in /etc/pam.d will use the rules in /etc/pam.d/other. The defaults are set to deny, as they should be. But I like to have a lot of logs, which is why I added pam_warn.so. The last configuration is pam_limits, which is controlled by /etc/security/limits.conf. See the /etc/security/limits.conf section for more on these settings. /etc/pam.d/other auth required pam_deny.so auth required pam_warn.so account required pam_deny.so account required pam_warn.so password required pam_deny.so password required pam_warn.so session required pam_deny.so session required pam_warn.so Intrusion Detection Intrusion detection (ID) is a type of security management system for computers and networks. An ID system gathers and analyzes information from various areas within a computer or a network to identify possible security breaches, which include both intrusions (attacks from outside the organization) and misuse (attacks from within the organization). ID uses vulnerability assessment (sometimes refered to as scanning), which is a technology developed to assess the security of a computer system or network. Intrusion detection functions include: * Monitoring and analyzing both user and system activities * Analyzing system configurations and vulnerabilities * Assessing system and file integrity * Ability to recognize patterns typical of attacks * Analysis of abnormal activity patterns * Tracking user policy violations Taken from: http://searchsecurity.techtarget.com/sDefinition/0,,sid14_gci295031,00.html. AIDE (Advanced Intrusion Detection Environment) AIDE is a Host-Based Intrusion Detection System (HIDS), a free alternative to Tripwire (if you already know Tripwire you should have no difficulties learning the configuration file for AIDE). HIDS are used to detect changes to important system configuration files and binaries, generally by making a unique cryptographic hash for the files to be checked and storing it in a secure place. On a regular basis (such as once a day), the stored "known-good" hash is compared to the one generated from the current copy of each file, to determine if that file has changed. HIDS are a great way to detect disallowed changes to your system, but they take a little work to implement properly and make good use of. The configuration file is based on regular expressions, macros and rules for files and directories. We have the following macros: Macro Description Syntax ifdef If definded @@ifdef "name" ifndef If not defined @@ifndef "name" define Define a variable @@define "name" "value" undef Undefine a variable @@undef "name" ifhost if "hostname" @@ifhost "hostname" ifnhost if not "hostname" @@ifnhost "hostname" endif Endif must be used after any of the above macros except define and undef @@endif These macros become very handy if you have more than one Gentoo box and want to use AIDE on all of them. But not all machines run the same services or even have the same users. Next we have sets of flags to check for on files and directories. These are a combination of permissions, file properties and cryptographic hashes (i.e. checksums). Flag Description p permissions i inode n number of links u user g group s size b block count m mtime a atime c ctime S check for growing size md5 md5 checksum sha1 sha1 checksum rmd160 rmd160 checksum tiger tiger checksum R p+i+n+u+g+s+m+c+md5 L p+i+n+u+g E Empty group > Growing logfile p+u+g+i+n+S And if AIDE is compiled with mhash support it supports a few other features: Flag Description haval haval checksum gost gost checksum crc32 crc32 checksum Now you can create you own rules based on the above flags by combining them like this: Create a ruleset for AIDE All=R+a+sha1+rmd160 Norm=s+n+b+md5+sha1+rmd160 The last thing we need to create our own configuration file is to see how to add a rule to a file or directory. To enter a rule, combine the file or directory name and the rule. AIDE will add all files recursively unless you specify an alternate rule. Flag Description ! Don't add this file or directory. = Add this directory, but not recursively. So lets watch a full blown example: /etc/aide/aide.conf @@ifndef TOPDIR @@define TOPDIR / @@endif @@ifndef AIDEDIR @@define AIDEDIR /etc/aide @@endif @@ifhost smbserv @@define smbactive @@endif # The location of the database to be read. database=file:@@{AIDEDIR}/aide.db # The location of the database to be written. database_out=file:aide.db.new verbose=20 report_url=stdout # Rule definition All=R+a+sha1+rmd160 Norm=s+n+b+md5+sha1+rmd160 @@{TOPDIR} Norm !@@{TOPDIR}etc/aide !@@{TOPDIR}dev !@@{TOPDIR}media !@@{TOPDIR}mnt !@@{TOPDIR}proc !@@{TOPDIR}root !@@{TOPDIR}sys !@@{TOPDIR}tmp !@@{TOPDIR}var/log !@@{TOPDIR}var/run !@@{TOPDIR}usr/portage @@ifdef smbactive !@@{TOPDIR}etc/smb/private/secrets.tdb @@endif =@@{TOPDIR}home Norm In the above example we specify with some macros where the topdir starts and where the AIDE directory is. AIDE checks the /etc/aide/aide.db file when checking for file integrity. But when updating or creating a new file it stores the information in /etc/aide/aide.db.new. This is done so it won't automatically overwrite the old db file. The option report_URL is not yet implemented, but the author's intention was that it should be able to e-mail or maybe even execute scripts. The AIDE ebuild now comes with a working default configuration file, a helper script and a crontab script. The helper script does a number of tasks for you and provides an interface that is a little more script friendly. To see all available options, try aide --help. To get started, all that needs to be done is aide -i and the crontab script should detect the database and send mails as appropriate every day. We recommend that you review the /etc/aide/aide.conf file and ensure that the configuration accurately reflects what is in place on the machine. Note: Depending on your CPU, disk access speed, and the flags you have set on files, this can take some time. Note: Remember to set an alias so you get roots mail. Otherwise you will never know what AIDE reports. Now there is some risk inherent with storing the db files locally, since the attacker will (if they know that AIDE is installed) most certainly try to alter the db file, update the db file or modify /usr/bin/aide. So you should create a CD or other media and put on it a copy of the .db file and the AIDE binaries. One can find information at the AIDE project page. Judger and Notipy todo Detecting malware and rootkits chkrootkit HIDS like AIDE are a great way to detect changes to your system, but it never hurts to have another line of defence. chkrootkit is a utility that scans common system files for the presence of rootkits--software designed to hide an intruder's actions and allow him to retain his access--and scans your system for likely traces of key loggers and other "malware". While chkrootkit (and alternatives like rkhunter) are useful tools, both for system maintenance and for tracking an intruder after an attack has occurred, they cannot guarantee your system is secure. The best way to use chkrootkit to detect an intrusion is to run it routinely from cron. To start, emerge app-admin/chkrootkit. chkrootkit can be run from the command line by the command of the same name, or from cron with an entry such as this: Schedule chkrootkit as a cronjob 0 3 * * * /usr/sbin/chkrootkit rkhunter Displaying login banners todo Keeping up-to-date Once you have successfully installed your system and ensured a good level of security you are not done. Security is an ongoing process; the vast majority of intrusions result from known vulnerabilities in unpatched systems. Keeping your system up-to-date is the single most valuable step you can take to greater security. If you have a recent version of portage installed, you can first sync your portage tree with emerge --sync and then issue the command glsa-check --list to check if your system is up to date security-wise. glsa-check is part of app-portage/gentoolkit. Example output of glsa-check -l # glsa-check -l WARNING: This tool is completely new and not very tested, so it should not be used on production systems. It's mainly a test tool for the new GLSA release and distribution system, it's functionality will later be merged into emerge and equery. Please read http://www.gentoo.org/proj/en/portage/glsa-integration.xml before using this tool AND before reporting a bug. [A] means this GLSA was already applied, [U] means the system is not affected and [N] indicates that the system might be affected. 200406-03 [N] sitecopy: Multiple vulnerabilities in included libneon ( net-misc/sitecopy ) 200406-04 [U] Mailman: Member password disclosure vulnerability ( net-mail/mailman ) ....... Warning: The glsa-check is still experimental, so if security really is your top priority it would be wise to double check the list with other sources. All lines with a [A] and [U] can be almost safely ignored as the system is not affected by this GLSA. Important: Please note that the usual emerge -vpuD world will not pick up all package updates. You need to use glsa-check if you want to make sure all GLSAs are fixed on your system. Check all GLSAs (check if your system is affected by GLSAs) # glsa-check -t all WARNING: This tool is completely new and not very tested, so it should not be used on production systems. It's mainly a test tool for the new GLSA release and distribution system, it's functionality will later be merged into emerge and equery. Please read http://www.gentoo.org/proj/en/portage/glsa-integration.xml before using this tool AND before reporting a bug. This system is affected by the following GLSA: 200504-06 200510-08 200506-14 200501-35 200508-12 200507-16 See what packages would be emerged # glsa-check -p $(glsa-check -t all) (partial output) Checking GLSA 200504-06 The following updates will be performed for this GLSA: app-arch/sharutils-4.2.1-r11 (4.2.1-r10) ********************************************************************** Checking GLSA 200510-08 The following updates will be performed for this GLSA: media-libs/xine-lib-1.1.0-r5 (1.1.0-r4) Apply required fixes # glsa-check -f $(glsa-check -t all) If you have upgraded a running service, you should not forget to restart it. Keeping your kernel up-to-date is also recommended. If you want an email each time a GLSA is released subscribe to the gentoo-announce mailing list. Instructions for joining it and many other great mailing lists can be found Gentoo Linux Mailing List Overview. Another great security resource is the Bugtraq mailing list. Additional software Please consider that installing additional software can cause headhackes. Anyway if you are going to get a software that is included in this list at last follow the instructions as specified the the documentation. Server * OpenSSH? SSHd installation and configuration notes. * Xorg/X11 Development * PHP Client * Evince Gnome document viewer Hardening network The sources of this page are multiple and include http://www.linuxsecurity.com/content/view/111337/65/, "IP Spoofing: Understanding the basics", the Gentoo security handbook, http://www.puschitz.com/SecuringLinux.shtml. The proc filesystem Many kernel parameters can be altered through the /proc file system or by using sysctl. To dynamically change kernel parameters and variables on the fly, you need CONFIG_SYSCTL defined in your kernel. This is on by default in a standard 2.4 kernel. All these settings will be reset when the machine is rebooted. I suggest that you add them to /etc/sysctl.conf, which is automatically sourced by the /etc/init.d/bootmisc init script. The syntax for /etc/sysctl.conf is pretty straightforward. Strip off the /proc/sys/ from the previously mentioned paths and substitute / with .: Translating to sysctl.conf Manual using echo: /bin/echo "0" > /proc/sys/net/ipv4/ip_forward Automatic in sysctl.conf: net.ipv4.ip_forward = 0 Deactivate IP forwarding # /bin/echo "0" > /proc/sys/net/ipv4/ip_forward Make sure that IP forwarding is turned off. We only want this for a multi-homed host. It's advised to set or unset this flag before all other flags since it enabled/disables other flags as well. Drop ping packets # /bin/echo "1" > /proc/sys/net/ipv4/icmp_echo_ignore_all This will cause the kernel to simply ignore all ping messages (also known as ICMP type 0 messages). The reason for this is that an IP packet carrying an ICMP message can contain a payload with information other than you think. Administrators use ping as a diagnostic tool and often complain if it is disabled, but there is no reason for an outsider to be able to ping. However, since it sometimes can be handy for insiders to be able to ping, you can disable ICMP type 0 messages in the firewall (allowing local administrators to continue to use this tool). Ignore broadcast pings # /bin/echo "1" > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts This disables response to ICMP broadcasts and will prevent Smurf attacks. The Smurf attack works by sending an ICMP type 0 (ping) message to the broadcast address of a network. Typically the attacker will use a spoofed source address. All the computers on the network will respond to the ping message and thereby flood the host at the spoofed source address. Disable source routed packets Source Routing is used to specify a path or route through the network from source to destination. This feature can be used by network people for diagnosing problems. However, if an intruder was able to send a source routed packet into the network, then he could intercept the replies and your server might not know that it's not communicating with a trusted server. # /bin/echo "0" > /proc/sys/net/ipv4/conf/all/accept_source_route Do not accept source routed packets. Attackers can use source routing to generate traffic pretending to originate from inside your network, but that is actually routed back along the path from which it came, so attackers can compromise your network. Source routing is rarely used for legitimate purposes, so it is safe to disable it. Disable redirect acceptance ICMP redirects are used by routers to tell the server that there is a better path to other networks than the one chosen by the server. However, an intruder could potentially use ICMP redirect packets to alter the hosts's routing table by causing traffic to use a path you didn't intend. # /bin/echo "0" > /proc/sys/net/ipv4/conf/all/accept_redirects Do not accept ICMP redirect packets. ICMP redirects can be used to alter your routing tables, possibly to a malicious end. More informations about ICMP redirects can be found in the Guide to IP Layer Network Administration with Linux, Chapter 4.10. Protect against bad error messages # /bin/echo "1" > /proc/sys/net/ipv4/icmp_ignore_bogus_error_responses Enable protection against bogus error message responses. Enable reverse path filtering IP spoofing is a technique where an intruder sends out packets which claim to be from another host by manipulating the source address. IP spoofing is very often used for denial of service attacks. # for i in /proc/sys/net/ipv4/conf/*; do /bin/echo "1" > $i/rp_filter done Turn on reverse path filtering. This helps make sure that packets use legitimate source addresses by automatically rejecting incoming packets if the routing table entry for their source address does not match the network interface they are arriving on. This has security advantages because it prevents IP spoofing. We need to enable it for each net/ipv4/conf/* otherwise source validation isn't fully functional. Warning: However turning on reverse path filtering can be a problem if you use asymmetric routing (packets from you to a host take a different path than packets from that host to you) or if you operate a non-routing host which has several IP addresses on different interfaces. Log all spoofed, source routed and redirect packets # /bin/echo "1" > /proc/sys/net/ipv4/conf/all/log_martians Log spoofed packets, source routed packets and redirect packets. Enable TCP SYN Cookie Protection A "SYN Attack" is a denial of service attack that consumes all the resources on a machine. Any server that is connected to a network is potentially subject to this attack. To enable TCP SYN Cookie Protection, edit the /etc/sysctl.conf file and add the following line: net.ipv4.tcp_syncookies = 1 Enable Ignoring Broadcasts Request If you want or need Linux to ignore broadcast requests, edit the /etc/sysctl.conf file and add the following line: net.ipv4.icmp_echo_ignore_broadcasts = 1 Static ARP entries If your connections are usually limited to the same apparatues Add to /etc/conf.d/local.start # Lollobox: Static ARP entries arp -s 192.168.1.1 00:11:22:33:44:55 # gateway arp -s 192.168.1.2 BB:AA:99:88:77:66 # secondary Client-only firewalling Add to /etc/conf.d/local.start # Lollobox: Firewall # Flush iptables -F iptables -X # Default policies iptables -P INPUT DROP iptables -P OUTPUT DROP iptables -P FORWARD DROP # Allow unlimited traffic on loopback iptables -A INPUT -i lo -j ACCEPT iptables -A OUTPUT -o lo -j ACCEPT # Allow established traffic iptables -A INPUT -m state --state ESTABLISHED -j ACCEPT iptables -A OUTPUT -m state --state NEW,ESTABLISHED -j ACCEPT Note that the use of RELATED can pose security risks: --state state Where state is a comma separated list of the connection states to match. Possible states are INVALID meaning that the packet is associated with no known connection, ESTABLISHED meaning that the packet is associated with a connection which has seen packets in both directions, NEW meaning that the packet has started a new con­ nection, or otherwise associated with a connection which has not seen packets in both directions, and RELATED meaning that the packet is starting a new connection, but is associated with an existing connection, such as an FTP data transfer, or an ICMP error. http://www.kalamazoolinux.org/presentations/20010417/conntrack.html Also the removal of ESTABLISHED -j ACCEPT from the INPUT chain will prevent TCP connections from closing correctly. Creating users Now users containing applications will be created, the howto take care of a common setup where the user wants to have mail, internet, an IM client and a user running the desktop. User Group Scope l_desktop lollobox Run Xorg, Gnome and is the "glue" user l_mail lollobox Used for Thunderbird l_web lollobox Used for Firefox l_irc lollobox Used for Xchat l_skype lollobox Used for Skype l_im lollobox Used for Pidgrim Add a new lollobox group groupadd lollobox Add new users, delete users To create new users you can use the following l_adduser function. function l_adduser() { adduser -g lollobox -G audio,cdrom -m "$1" mkdir "/home/$1" chown $1:lollobox "/home/$1" chmod 700 "/home/$1" } To delete a user use the following l_deluser() function. function l_deluser() { rm -rf "/home/$1" # todo deluser + real rm of chattr +i files inside the user home } Building users and relationships l_adduser l_desktop l_adduser l_mail l_adduser l_web l_adduser l_irc l_adduser l_skype l_adduser l_im Home privacy protections Put the following contents in /etc/lollobox/home-privacy.conf: .ash_history .bash_history .bash_logout .bash_profile .bashrc .gtk-bookmarks .history .keep .lesshst .logout .mysql_history .nano_history .php_history .psql_history .recently-used .recently-used.xbel .sh_history .viminfo .xchm .scapy_history .crash_report_checksum .crash_report_frames .crash_report_preview .crash_report_unsent core dead.letter null .thumbnails Then use the following function to point these files to /dev/null. functio f_homeprivacy() { cd "/home/$1" while read file; do ln -s /dev/null "$file" done < /etc/lollobox/home-privacy.conf } Home security protections Put the following contents in /etc/lollobox/home-security.conf: .bashrc .xinitrc .bash_profile .bash_logout Then use the following function to secure these files from modification. functio f_homesecurity() { cd "/home/$1" while read file; do chattr +i "$file" done < /etc/lollobox/home-security.conf } Files ~/.bashrc Edit ~/.bashrc as follows. If you are using /etc/skel/ when creating homes just put the following contents in /etc/skel/.bashrc. # Lollobox ~/.bashrc # The only sane umask umask 007 # Shell is non-interactive. Be done now! [[ $- != *i* ]] && return # Xorg configuration export XAUTHORITY=~/.Xauthority # No history export HISTFILE=/dev/null export HISTCONTROL=ignoredups export HISTFILESIZE=2 export HISTSIZE=100000000 # Base aliases alias ls="ls --color=auto" alias ll="ls -la --color=auto" alias lt="ls -laptr --color=auto" # oldest first sort alias la="ls -lap--color=auto" # alphabetical sort alias startx="startx & exit" # Very important, never leave open tty! # Xhost authentication xhost local:user1_allowed_to_access_this_xserver xhost local:user2_allowed_to_access_this_xserver # Http proxy for wget & co. #export http_proxy="antani" #export PROXY="antani" unset http_proxy unset PROXY # Shortcuts alias a="alias" alias s="sudo su -" # Other aliases alias someserver="ssh -l someuser someserver -p 1234" # Encryption encrypt(){ gpg -ac --no-options "$1"; } decrypt(){ gpg --no-options "$1"; } # Completion [ -f /etc/bash_completion ] && . /etc/bash_completion Then make the file just readable and immutable. $ cd ~ $ chmod 400 .bashrc $ sudo chattr +i .bashrc ~/.bash_profile # Lollobox ~/.bash_profile # Get the aliases and functions [ -f ~/.bashrc ] && . ~/.bashrc Then make the file just readable and immutable. $ cd ~ $ chmod 400 .bash_profile $ sudo chattr +i .bash_profile ~/.bash_logout # Lollobox ~/.bash_logout # Clear the screen for security's sake. clear Then make the file just readable and immutable. $ cd ~ $ chmod 400 .bash_logout $ sudo chattr +i .bash_logout ~/.xinitrc The .xinitrc: # Accept local connections from myself xhost local:l_desktop # Clean home rm ~/.Trash/* -rf rm ~/.serverauth.* rm ~/.ICEauthority rm ~/.Xauthority rm ~/.mozilla/firefox/*/Cache/* # Start programs xterm -bg black -fg white & # Gnome dbus-launch gnome-session Then make the file just readable and immutable. $ cd ~ $ chmod 400 .xinitrc $ sudo chattr +i .xinitrc