<!-- CVS revision of this document "$Revision: 1.68 $"  -->

<chapt>After installation

<p>Once the system is installed you can still do more to secure the system;
some of the steps described in this chapter can be taken. Of course
this really depends on your setup but for physical access prevention
you should read <ref id="bios-boot">,<ref id="lilo-passwd">,<ref
id="kernel-root-prompt">, <ref
id="restrict-console-login">, and <ref id="restrict-reboots">.

<p>Before connecting to any network, especially if it's a public one
you should, at the very least, execute a security update (see 
<ref id="security-update">). Optionally, you could take a snapshot of your
system (see <ref id="snapshot">).

<sect id="debian-sec-announce">Subscribe to the Debian Security Announce mailing list

<p>In order to receive information on available security updates you
should subscribe yourself to the debian-security-announce mailing list
in order to receive the Debian Security Advisories (DSAs). See <ref
id="debian-sec-team"> for more information on how the Debian security
team works. For information on how to subscribe to the Debian mailing
lists read <url id="http://lists.debian.org">.

<p>DSAs are signed with the Debian Security Team's signature which can
be retrieved from <url id="http://security.debian.org">.

<p>You should consider, also, subscribing to the <url
id="http://lists.debian.org/debian-security" name="debian-security
mailing list"> for general discussion on security issues in the Debian
operating system. You will be able to contact other fellow system
administrators in the list as well as Debian developers and upstream
developers of security tools who can answer your questions and offer
advice.

<p>FIXME: Add the key here too?

<sect id="security-update">Execute a security update

<p>As soon as new security bugs are detected in packages, Debian
maintainers and upstream authors generally patch them within days or
even hours. After the bug is fixed, a new package is provided on <url
name="http://security.debian.org" id="http://security.debian.org">.

<p>If you are installing a Debian release you must take into account
that since the release was made there might have been security updates
after it has been determined that a given package is vulnerable. Also,
there might have been minor releases (there have been four for the Debian
3.0 <em>sarge</em> release) which include these package updates. 

<p>During installation security updates are configured
for your system and pending updates downloaded and applied, unless you
specifically opt out of this or the system was not connected to the
Internet. The updates are applied even before the
first boot, so the new system starts its life as up to date as possible.

<p>To manually update the system, put the following line in your
<file>sources.list</file> and you will get security updates
automatically, whenever you update your system. Replace
<em>[CODENAME]</em> with the release codename, e.g. <em>squeeze</em>.

<example>
  deb http://security.debian.org/ [CODENAME]/updates main contrib non-free
</example>

<p><em>Note</em>: If you are using the <em>testing</em> branch use the security
testing mirror sources as described in <ref id="security-support-testing">.

<p>Once you've done this you can use multiple tools to upgrade your system.  If
you are running a desktop system you will have<footnote>In <em>Etch</em> and
later releases</footnote> an application called <prgn>update-notifier</prgn>
that will make it easy to check if new updates are available, by selecting it
you can make a system upgrade from the desktop (using
<prgn>update-manager</prgn>). For more information see <ref
id="update-desktop">. In
desktop environments you can also use <package>synaptic</package> (GNOME),
<package>kpackage</package> or <package>adept</package> (KDE) for more advanced
interfaces. If you are running a text-only terminal you can use
<package>aptitude</package>, <package>apt</package> or
<package>dselect</package> (deprecated) to upgrade:

<list>
<item>If you want to use <package>aptitude</package>'s text interface
you just have to press <em>u</em> (update) followed by <em>g</em> (to upgrade).
Or just do the following from the command line (as root):
<example>
# aptitude update
# aptitude upgrade
</example>

<item>If you want to use <package>apt</package> do just like with aptitude but
substitute the <prgn>aptitude</prgn> lines above with <prgn>apt-get</prgn>.

<item>If you want to use <package>dselect</package> then first [U]pdate,
then [I]nstall and finally, [C]onfigure the installed/upgraded packages.
</list>

<p>If you like, you can add the deb-src lines to 
<file>/etc/apt/sources.list</file> as well. See 
<manref name="apt" section="8"> for further details.

<sect1 id="lib-security-update">Security update of libraries

<p>Once you have executed a security update you might need to restart some
of the system services. If you do not do this, some services might still be vulnerable
after a security upgrade. The reason for this is that daemons that are running
before an upgrade might still be using the old libraries before the upgrade
<footnote>Even though the libraries have been removed from the filesystem the inodes
will not be cleared up until no program has an open file descriptor pointing
to them.</footnote>.

<p>From Debian <em>Jessie</em> and up, you can install the
<package>needrestart</package> package, which will run automatically after each
APT upgrade and prompt you to restart services that are affected by the
just-installed updates. In earlier releases, you can run the
<prgn>checkrestart</prgn> program (available in the
<package>debian-goodies</package> package) manually after your APT upgrade.

<P>Some packages (like <package>libc6</package>) will do this check in the postinst
phase for a limited set of services specially since an upgrade of essential libraries
might break some applications (until restarted)<footnote>This happened, for example,
in the upgrade from libc6 2.2.x to 2.3.x due to NSS authentication issues, see
<url id="http://lists.debian.org/debian-glibc/2003/debian-glibc-200303/msg00276.html">.</footnote>.

<P>Bringing the system to run level 1 (single user) and then back to
run level 3 (multi user) should take care of the restart of most (if not all)
system services. But this is not an option if you are executing the security
upgrade from a remote connection (like ssh) since it will be severed.

<p>Excercise caution when dealing with security upgrades if you are doing them
over a remote connection like ssh. A suggested procedure for a security
upgrade that involves a service restart is to restart the SSH daemon and then, immediately,
attempt a new ssh connection without breaking the previous one. If the connection
fails, revert the upgrade and investigate the issue. 
</sect1>

<sect1 id="kernel-security-update">Security update of the kernel

<P>First, make sure your kernel is being managed through the packaging
system. If you have installed using the installation system from Debian 3.0
or previous releases, your kernel is <em>not</em> integrated into the
packaging system and might be out of date. You can easily confirm this
by running:

<example>
$ dpkg -S `readlink -f /vmlinuz`
linux-image-2.6.18-4-686: /boot/vmlinuz-2.6.18-4-686
</example>

<p>If your kernel is not being managed you will see a message saying that
the package manager did not find the file associated to any package instead
of the message above, which says that the file associated to the current
running kernel is being provided by the
<package>linux-image-2.6.18-4-686</package>. So first, you will need
to manually install a kernel image package. The exact kernel image you need
to install depends on your architecture and your prefered kernel version.
Once this is done, you will be able to manage the security updates of the
kernel just like those of any other package. In any case, notice that
the kernel updates will <em>only</em> be done for kernel updates of
the same kernel version you are using, that is, <prgn>apt</prgn>
will not automatically upgrade your kernel from the 2.4 release to the
2.6 release (or from the 2.4.26 release to the 2.4.27 release<footnote>Unless
you have installed a kernel metapackage like 
<package>linux-image-2.6-686</package> which will always pull in the 
latest kernel minor revision for a kernel release and a given
architecture.</footnote>).

<p>The installation system of recent Debian releases will handle
the selected kernel as part of the package system.
You can review which kernels you have installed by running:

<example>
$ COLUMNS=150 dpkg -l 'linux-image*' | awk '$1 ~ /ii/ { print $0 }'
</example>

<p>To see if your kernel needs to be updated run:

<example>
$ kernfile=`readlink -f /vmlinuz`
$ kernel=`dpkg -S $kernfile | awk -F : '{print $1}'`
$ apt-cache policy $kernel
linux-image-2.6.18-4-686:
  Installed: 2.6.18.dfsg.1-12
  Candidate: 2.6.18.dfsg.1-12
  Version table:
 *** 2.6.18.dfsg.1-12 0
        100 /var/lib/dpkg/status
</example>


<P>If you are doing a security update which includes the kernel image
you <em>need</em> to reboot the system in order for the security update to be useful.
Otherwise, you will still be running the old (and vulnerable) kernel image.

<!-- FIXME: Do a script to check for the above, maybe using ps -p 1 -o etime | tail -1
and obtain the creation time of `readlink -f /vmlinuz`. -->

<p>If you need to do a system reboot (because of a kernel upgrade) you should
make sure that the kernel will boot up correctly and network connectivity will be 
restored, specially if the security upgrade is done over a remote connection like ssh.
For the former you can configure your boot loader to reboot to the original kernel in
the event of a failure (for more detailed information  read
<url id="http://www.debian-administration.org/?article=70" name="Remotely rebooting Debian GNU/Linux machines">). For the latter you have to introduce a network
connectivity test script that will check if the kernel has started up the network
subsystem properly and reboot the system if it did not<footnote>A sample
script called
<url id="http://www.debian-administration.org/articles/70/testnet" name="testnet">
is available in the <url id="http://www.debian-administration.org/?article=70" 
name="Remotely rebooting Debian GNU/Linux machines"> article. A more elaborate 
network connectivity testing script is available in the 
<url id="http://www.debian-administration.org/?article=128" 
name="Testing network connectivity"> article.</footnote>. This  should prevent
nasty surprises like updating the kernel and then realizing, after a reboot, that
it did not detect or configure the network hardware properly and you need
to travel a long distance to bring the system up again. Of course, having the
system serial console <footnote>Setting up a serial console
is beyond the scope of this document, for more information read the 
<url id="http://www.tldp.org/HOWTO/Serial-HOWTO.html" name="Serial HOWTO">
and the <url id="http://www.tldp.org/HOWTO/Remote-Serial-Console-HOWTO/index.html"
name="Remote Serial Console HOWTO">.</footnote> in the system connected to a 
console or terminal server should also help debug reboot issues remotely.
</p>

</sect1>

<sect id="bios-boot">Change the BIOS (again)

<p>Remember <ref id="bios-passwd">? Well, then you should now, once
you do not need to boot from removable media, to change the default
BIOS setup so that it <em>only</em> boots from the hard drive. Make
sure you will not lose the BIOS password, otherwise, in the event of a
hard disk failure you will not be able to return to the BIOS and
change the setup so you can recover it using, for example, a CD-ROM.

<p>Another less secure but more convenient way is to change the
setup to have the system boot up from the hard disk and, if it fails,
try removable media. By the way, this is often done because
most people don't use the BIOS password that often; it's easily forgotten.

<sect id="lilo-passwd">Set a LILO or GRUB password
<p>
Anybody can easily get a root-shell and change your passwords by
entering <tt>&lt;name-of-your-bootimage&gt; init=/bin/sh</tt> at the boot
prompt. After changing the passwords and rebooting the system, the
person has unlimited root-access and can do anything he/she wants to the
system.  After this procedure you will not have root access to your
system, as you do not know the root password.
<p>
To make sure that this cannot happen, you should set a password for
the boot loader. You can choose between a global password or a
password for a certain image.
<p>
For LILO you need to edit the config file <file>/etc/lilo.conf</file> and add
a <tt>password</tt> and <tt>restricted</tt> line as in the example below.

<example>
  image=/boot/2.2.14-vmlinuz
     label=Linux
     read-only
     password=hackme
     restricted
</example>

<p>Then, make sure that the configuration file is not world readable
to prevent local users from reading the password.
When done, rerun lilo.  Omitting the <tt>restricted</tt> line causes lilo to
always prompt for a password, regardless of whether LILO was passed
parameters. The default permissions for <file>/etc/lilo.conf</file>
grant read and write permissions to root, and enable read-only access
for <file>lilo.conf</file>'s group, root.

<p>
If you use GRUB instead of LILO, edit <file>/boot/grub/menu.lst</file>
and add the following two lines at the top (substituting, of course
<tt>hackme</tt> with the desired password). This prevents users from editing
the boot items. <tt>timeout 3</tt> specifies a 3 second delay before 
<prgn>grub</prgn> boots the default item.

<example>
  timeout 3
  password hackme
</example>

<p>To further harden the integrity of the password, you may store the password
in an encrypted form. The utility <prgn>grub-md5-crypt</prgn> generates a 
hashed password which is compatible with GRUB's encrypted password algorithm 
(MD5).
To specify in <prgn>grub</prgn> that an MD5 format password will be used, use 
the following directive:
<example>
  timeout 3
  password --md5 $1$bw0ez$tljnxxKLfMzmnDVaQWgjP0
</example>

The --md5 parameter was added to instruct <prgn>grub</prgn> to perform the MD5 
authentication process. The provided password is the MD5 encrypted version of 
hackme. Using the MD5 password method is preferable to choosing its clear-text 
counterpart. More information about <prgn>grub</prgn> passwords may be found 
in the <package>grub-doc</package> package.

<sect id="kernel-initramfs-prompt">Disable root prompt on the initramfs

<p>Note: This applies to the default kernels provided for releases after Debian
3.1

<p>Linux 2.6 kernels provide a way to access a root shell while booting which
will be presented during loading the initramfs on error. This is helpful to
permit the administrator to enter a rescue shell with root permissions.  This
shell can be used to manually load modules when autodetection fails.  This
behavior is the default for <prgn>initramfs-tools</prgn> generated initramfs.
The following message will appear:
<example>
  "ALERT!  /dev/sda1 does not exist.  Dropping to a shell!
</example>

<p>In order to remove this behavior you need to set the following boot
argument:<em>panic=0</em>. Add this to the variable <tt>GRUB_CMDLINE_LINUX</tt>
in <file>/etc/default/grub</file> and issue <prgn>update-grub</prgn> or to the
append section of <file>/etc/lilo.conf</file>.

<sect id="kernel-root-prompt">Remove root prompt on the kernel

<p>Note: This does not apply to the kernels provided for Debian 3.1 as the
timeout for the kernel delay has been changed to 0.

<p>Linux 2.4 kernels provide a way to access a root shell while booting which 
will be presented just after loading the cramfs file system. A message will 
appear to permit the administrator to enter an executable shell with root 
permissions, this shell can be used to manually load modules when 
autodetection fails. This behavior is the default for <prgn>initrd</prgn>'s 
<file>linuxrc</file>. The following message will appear:
<example>
  Press ENTER to obtain a shell (waits 5 seconds)
</example>

<p>In order to remove this behavior you need to change 
<file>/etc/mkinitrd/mkinitrd.conf</file> and set:
<example>
  # DELAY  The  number  of seconds the linuxrc script should wait to
  # allow the user to interrupt it before the system is brought up
  DELAY=0
</example>
<p>Then regenerate your ramdisk image. You can do this for example with:
<example>
  # cd /boot
  # mkinitrd -o initrd.img-2.4.18-k7 /lib/modules/2.4.18-k7
</example>
<p>or (preferred):
<example>
  # dpkg-reconfigure -plow kernel-image-2.4.x-yz
</example>


<sect id="restrict-console-login">Restricting console login access 

<p>Some security policies might force administrators to log in to
the system through the console with their user/password and then
become superuser (with <prgn>su</prgn> or <prgn>sudo</prgn>). This
policy is implemented in Debian by editing the
<file>/etc/pam.d/login</file> and the <file>/etc/securetty</file> when
using PAM:

<list>

<item><file>/etc/pam.d/login</file>
<footnote>In older Debian releases you would need to edit
<file>login.defs</file>, and use the CONSOLE variable which defines a file or
list of terminals on which root logins are allowed.</footnote>
enables the pam_securetty.so module. This module, when properly configured will
not ask for a password when the root user tries to login on an insecure
console, rejecting access as this user.

<item><file>securetty</file>
<footnote> The <file>/etc/securetty</file> is a configuration file that belongs
to the <package>login</package> package.</footnote>
by adding/removing the terminals to which
root access will be allowed. If you wish to allow only local console access
then you need <em>console</em>, <em>ttyX</em><footnote>
Or <em>ttyvX</em> in GNU/FreeBSD, and <em>ttyE0</em> in GNU/KNetBSD.
</footnote>
and <em>vc/X</em> (if using <em>devfs</em> devices), you might want to add
also <em>ttySX</em><footnote>
Or <em>comX</em> in GNU/Hurd, <em>cuaaX</em> in GNU/FreeBSD, 
and <em>ttyXX</em> in GNU/KNetBSD.
</footnote>
if you are using
a serial console for local access (where X is an integer, you might want
to have multiple instances. The default configuration for
<em>Wheezy</em>
<footnote>
The default configuration in <em>woody</em> includes 12
local tty and vc consoles, as well as the <em>console</em> device but
does not allow remote logins. In <em>sarge</em> the default 
configuration provides 64 consoles for tty and vc consoles.
</footnote>
includes many tty devices, serial ports, vc consoles as
well as the X server and the <em>console</em> device.
You can safely adjust this if you are not using that many consoles.
You can confirm the virtual consoles and the tty devices 
you have by reviewing <file>/etc/inittab</file>
<footnote> Look for the <em>getty</em> calls.</footnote>
. For more information on terminal devices read the
<url id="http://tldp.org/HOWTO/Text-Terminal-HOWTO-6.html" name="Text-Terminal-HOWTO">.

</list>

<p>When using PAM, other changes to the login process, which might
include restrictions to users and groups at given times, can be
configured in <file>/etc/pam.d/login</file>. An interesting feature
that can be disabled is the possibility to login with null (blank)
passwords. This feature can be limited by removing <em>nullok</em>
from the line:

<example>
  auth       required   pam_unix.so nullok
</example>

<sect id="restrict-reboots">Restricting system reboots through the console

<p>If your system has a keyboard attached to it anyone (yes <em>anyone</em>)
with physical access to the system can reboot the system through it without
login in just pressing the <em>Ctrl+Alt+Delete</em> keyboard combination, also
known as the <em>three finger salute</em>. This might, or might not, adhere to
your security policy.

<p>This is aggravated in environments in which the operating system
is running virtualised. In these environments, the possibility extends to users
that have access to the virtual console (which might be accessed over the
network). Also note that, in these environments, this keyboard combination is
used constantly (to open a login shell in some GUI operating systems) and an
administrator might <em>virtually</em> send it and force a system reboot.

<p>There are two ways to restrict this:

<list>
<item>configure it so that only <em>allowed</em> users can
reboot the system,
<item>disable this feature completely.
</list>

<p>If you want to restrict this, you must check the <file>/etc/inittab</file>
so that the line that includes <tt>ctrlaltdel</tt> calls <prgn>shutdown</prgn>
with the <tt>-a</tt> switch.

<p>The default in Debian includes this switch:

<example>
  ca:12345:ctrlaltdel:/sbin/shutdown -t1 -a -r now
</example>

<p>The <tt>-a</tt> switch, as the <manref section="8" name="shutdown"> manpage
describes,makes it possible to allow <em>some</em> users to shutdown the
system.  For this the file <file>/etc/shutdown.allow</file> must be created and
the administrator has to include there the name of users which can boot the
system. When the <em>three finger salute</em> combination is pressed in a
console the program will check if any of the users listed in the file are
logged in. If none of them is, <prgn>shutdown</prgn> will <em>not</em> reboot
the system.

<p>If you want to disable the Ctrl+Alt+Del combination you just need to comment
the line with the <em>ctrlaltdel</em> definition in the
<file>/etc/inittab</file>.

<p>Remember to run <tt>init q</tt> after making any changes to
the <file>/etc/inittab</file> file for the changes to take effect.</p>
 
</sect>

<sect id="restrict-sysrq">Restricting the use of the Magic SysRq key

<p>The <em>Magic SysRq key</em> is a key combination that allows users
connected to the system console of a Linux kernel to perform some low-level
commands. These low-level commands are sent by pressing simultaneously
<em>Alt+SysRq</em> and a command key. The SysRq key in many keyboards is
labeled as the <em>Print Screen</em> key. 

<p>Since the Etch release, the Magic SysRq key feature is enabled in the Linux
kernel to allow console users certain privileges. You can confirm this by
checking if the <file>/proc/sys/kernel/sysrq</file> exists and reviewing its
value:

<example>
$ cat /proc/sys/kernel/sysrq 
438
</example>

<p>The default value shown above allows all of the SysRq functions except for
the possibility of sending signals to processes. For example, it allow users
connected to the console to remount all systems read-only, reboot the system or
cause a kernel panic. In all the features are enabled, or in older kernels
(earlier than 2.6.12) the value will be just 1.

<p>You should disable this functionality ifaccess to the console is not
restricted to authorised users: the console is connected to a modem line, there
is easy physical access to the system or it is running in a virtualised
environment and other users access the console.  To do this edit the
<file>/etc/sysctl.conf</file> and add the following lines:

<example>
# Disables the magic SysRq key
kernel.sysrq = 0
</example>

<p>For more information, read 
<url id="http://tldp.org/HOWTO/Remote-Serial-Console-HOWTO/security-sysrq.html"
name="security chapter in the Remote Serial Console HOWTO">,
<url id="http://kernel.org/doc/Documentation/sysrq.txt" name="Kernel SysRQ documentation">.
and the <url id="http://en.wikipedia.org/wiki/Magic_SysRq_key" name="Magic_SysRq_key wikipedia entry">.

<sect>Mounting partitions the right way
<p>
When mounting an <tt>Ext</tt> file system (<tt>ext2</tt>, <tt>ext3</tt> or
<tt>ext4</tt>), there are several additional options you can apply to the mount
call or to
<file>/etc/fstab</file>. For instance, this is my fstab entry for the
<file>/tmp</file> partition:

<example>
  /dev/hda7    /tmp    ext2    defaults,nosuid,noexec,nodev    0    2
</example>

<p>
You see the difference in the options sections. The option
<tt>nosuid</tt> ignores the setuid and setgid bits completely, while
<tt>noexec</tt> forbids execution of any program on that mount point,
and <tt>nodev</tt> ignores device files. This sounds great, but it:

<list>
<item>only applies to <tt>ext2</tt> or <tt>ext3</tt> file systems
<item>can be circumvented easily
</list>

<p>The <tt>noexec</tt> option prevents binaries from being executed
directly, but was easily circumvented in earlier versions of the kernel:

<example>
  alex@joker:/tmp# mount | grep tmp
  /dev/hda7 on /tmp type ext2 (rw,noexec,nosuid,nodev)
  alex@joker:/tmp# ./date
  bash: ./date: Permission denied
  alex@joker:/tmp# /lib/ld-linux.so.2 ./date
  Sun Dec  3 17:49:23 CET 2000
</example>

<p>Newer versions of the kernel do however handle the <tt>noexec</tt> flag
properly:

<example>
  angrist:/tmp# mount | grep /tmp
  /dev/hda3 on /tmp type ext3 (rw,noexec,nosuid,nodev)
  angrist:/tmp# ./date
  bash: ./tmp: Permission denied 
  angrist:/tmp# /lib/ld-linux.so.2 ./date 
  ./date: error while loading shared libraries: ./date: failed to map segment 
  from shared object: Operation not permitted
</example>

<p>However, many script kiddies have exploits which try to create and execute 
files in <file>/tmp</file>. If they do not have a clue, they will fall into
this pit. In other words, a user cannot be tricked into executing a trojanized 
binary in <file>/tmp</file> e.g. when <file>/tmp</file> is accidentally added 
into the local PATH.

<p>Also be forewarned, some script might depend on <file>/tmp</file> being
executable. Most notably, Debconf has (had?) some issues regarding
this, for more information see Bug <url
id="http://bugs.debian.org/116448" name="116448">.

<p>
The following is a more thorough example. A note, though: 
<file>/var</file> could be set noexec, but some software 
<footnote>Some of this includes the package manager <package>dpkg</package>
since the installation (post,pre) and removal (post,pre) scripts are
at <file>/var/lib/dpkg/</file> and Smartlist</footnote>
keeps its programs under in <file>/var</file>. 
The same applies to the nosuid option.

<example>
/dev/sda6   /usr          ext3    defaults,ro,nodev       0       2
/dev/sda12  /usr/share    ext3    defaults,ro,nodev,nosuid        0       2
/dev/sda7   /var          ext3    defaults,nodev,usrquota,grpquota 0      2
/dev/sda8   /tmp          ext3    defaults,nodev,nosuid,noexec,usrquota,grpquota    0       2
/dev/sda9   /var/tmp      ext3    defaults,nodev,nosuid,noexec,usrquota,grpquota    0       2
/dev/sda10  /var/log      ext3    defaults,nodev,nosuid,noexec    0       2
/dev/sda11  /var/account  ext3    defaults,nodev,nosuid,noexec    0       2
/dev/sda13  /home         ext3    rw,nosuid,nodev,exec,auto,nouser,async,usrquota,grpquota                0       2
/dev/fd0    /mnt/fd0      ext3    defaults,users,nodev,nosuid,noexec      0       0
/dev/fd0    /mnt/floppy   vfat    defaults,users,nodev,nosuid,noexec      0       0
/dev/hda    /mnt/cdrom    iso9660 ro,users,nodev,nosuid,noexec            0       0
</example>

<sect1>Setting <file>/tmp</file> noexec
<p>Be careful if setting <file>/tmp</file> noexec when you want to install new 
software, since some programs might use it for installation. 
<package>apt</package> is one such program (see 
<url id="http://bugs.debian.org/116448">) if not configured properly
<tt>APT::ExtractTemplates::TempDir</tt> (see 
<manref name="apt-extracttemplates" section="1">). 
You can set this variable in <file>/etc/apt/apt.conf</file> to another 
directory with exec privileges other than <file>/tmp</file>.

<!-- This is a duplicate of the example a few paragraphs up. So why repeat it?
(thomas)
<p>Regarding noexec, please be aware that it might not offer you that much 
security. 
Consider this:
<example>
  $ cp /bin/date /tmp
  $ /tmp/date
  (does not execute due to noexec)
  $/lib/ld-linux.so.2 /tmp/date
  (works since date is not executed directly)
</example>
-->

<sect1>Setting /usr read-only
<p>If you set <file>/usr</file> read-only you will not be able to install new 
packages on your Debian GNU/Linux system. You will have to first remount it 
read-write, install the packages and then remount it read-only. 
<package>apt</package> can be configured to 
run commands before and after installing packages, so you might want to 
configure it properly.

<p>To do this modify <file>/etc/apt/apt.conf</file> and add:
<example>
  DPkg
  {
      Pre-Invoke  { "mount /usr -o remount,rw" };
      Post-Invoke { "mount /usr -o remount,ro" };
  };
</example>

<p>Note that the Post-Invoke may fail with a "/usr busy" error message.
This happens mainly when you are using files during the update that
got updated.  You can find these programs by running
<example>
# lsof +L1
</example>

<p>Stop or restart these programs and run the Post-Invoke manually.
<em>Beware!</em>  This means you'll likely need to restart your X
session (if you're running one) every time you do a major upgrade of
your system.  You might want to reconsider whether a read-only
<file>/usr</file> is suitable for your system. See also this <url
id="http://lists.debian.org/debian-devel/2001/11/threads.html#00212"
name="discussion on debian-devel about read-only /usr">.

<sect>Providing secure user access

<sect1 id="auth-pam">User authentication: PAM

<p>PAM (Pluggable Authentication Modules) allows system administrators
to choose how applications authenticate users. Note that PAM can do
nothing unless an application is compiled with support for PAM. Most
of the applications that are shipped with Debian have this support
built in (Debian did not have PAM support before 2.2). The
current default configuration for any PAM-enabled service is to
emulate UNIX authentication (read
<file>/usr/share/doc/libpam0g/Debian-PAM-MiniPolicy.gz</file> for more
information on how PAM services <em>should</em> work in Debian).

<p>Each application with PAM support provides a configuration file
in <file>/etc/pam.d/</file> which can be used to modify its behavior:

<list>
<item>what backend is used for authentication.
<item>what backend is used for sessions.
<item>how do password checks behave.
</list>

<p>The following description is far from complete, for more information you
might want to read the <url id="http://www.linux-pam.org/Linux-PAM-html/"
name="Linux-PAM Guides"> as a reference. This documentation is available in the
system if you install the <package>libpam-doc</package> at
<file>/usr/share/doc/libpam-doc/html/</file>.

<p>PAM offers you the possibility to go through several authentication steps at
once, without the user's knowledge. You could authenticate against a Berkeley
database and against the normal <file>passwd</file> file,
and the user only logs in if the authentication succeeds in both.
You can restrict a lot with PAM, just as you can open your system
doors very wide. So be careful. A typical configuration line has a control field as its second element. 
<!-- Second in mine (old Debian v2.0 though), check this! (FIXME) (era) -->
Generally it should be set to <tt>requisite</tt>, which
returns a login failure if one module fails.
<!-- Lots of fields in mine are "required", please elaborate? (FIXME) (era) -->

<sect2 id="pam-passwords">Password security in PAM

<p>Review the <file>/etc/pam.d/common-password</file>, included by
<file>/etc/pam.d/passwd</file>
<footnote>In old Debian releases the configuration of the modules
was defined directly in <file>/etc/pam.d/passwd</file>.</footnote>
.  This file is included by other files in <file>/etc/pam.d/</file> to define
the behaviour of password use in subsystems that grant access
to services in the machine, like the console login (<tt>login</tt>), graphical login managers
(such as <tt>gdm</tt> or <tt>lightdm</tt>), and remote login (such as <tt>sshd</tt>).
This definition is

<p>You have to make sure that the pam_unix.so module uses the "sha512" option
to use encrypted passwords. This is the default in Debian Squeeze. 

<p>The line with the definition of the pam_unix module  will look something like:

<example>
  password   [success=1 default=ignore]      pam_unix.so nullok obscure minlen=8 sha512 
</example>

<p>This definition:

<list>

<item>Enforces password encryption when storing passwords, using the SHA-512
hash function (option <em>sha512</em>),

<item>Enables password complexity checks (option <em>obscure</em>) as defined
in the <manref name="pam_unix" section="8"> manpage,

<item>Imposes a minimum password length (option <em>min</em>) of 8.

</list>

<p>You have to ensure that encrypted passwords are used in PAM applications,
since this helps protect against dictionary cracks. Using encryption also makes
it possible to use passwords longer than 8 characters.

<p>Since this module is also used to define how passwords are changed (it
is included by <tt>chpasswd</tt>) you can strengthen the password security in
the system by installing <package>libpam-cracklib</package> and introducing
this definition in the <file>/etc/pam.d/common-password</file> configuration
file:

<example>
  # Be sure to install libpam-cracklib first or you will not be able to log in
  password   required     pam_cracklib.so retry=3 minlen=12 difok=3
  password   [success=1 default=ignore]      pam_unix.so obscure minlen=8 sha512 use_authok
</example>

<p>So, what does this incantation do? The first line loads the
cracklib PAM module, which provides password strength-checking,
prompts for a new password with a minimum size 
<footnote>The <em>minlen</em> option is not entirely straightforward and
is not exactly the number of characters in the password. 
A tradeoff can be defined between complexity and length by
adjusting the "credit" parameters of different character classes.
For more information read the <manref name="pam_cracklib" section="8"> manpage.</footnote>
of 12 characters, and
difference of at least 3 characters from the old password, and allows
3 retries. Cracklib depends on a wordlist package (such as
<package>wenglish</package>, <package>wspanish</package>, 
<package>wbritish</package>, ...), so make sure you install one that is
appropriate for your language or cracklib might not be useful to you at all.

<p>The second line (using the pam_unix.so module) is the default 
configuration in Debian, as described above, save for the <em>use_authok</em> option.
The <em>use_authok</em> option is required if pam_unix.so is stacked after
pam_cracklib.so, and is used to hand over the password from the previous
module. Otherwise, the user would be prompted for the password twice.

<p>For more information about setting up Cracklib, read the  <manref
name="pam_cracklib" section="8"> manpage and the article <url
id="http://www.deer-run.com/~hal/sysadmin/pam_cracklib.html" name="Linux
Password Security with pam_cracklib"> by Hal Pomeranz.

<p>By enabling the cracklib PAM module you setup a policy that forces uses to
use strong passwords. 

<p>Alternatively, you can setup and configure PAM modules
to use double factor authentication 
such as: <package>libpam-barada</package>,
<package>libpam-google-authenticator</package>, <package>libpam-oath</package>,
<package>libpam-otpw</package>, <package>libpam-poldi</package>,
<package>libpam-usb</package> or <package>libpam-yubico</package>. The configuration
of these modules would make it possible to access the system using external
authentication mechanisms such as smartcards, external USB keys, or
One-Time-Passwords generated by external applications running, for example, in
the user's mobile phone.


<p>Please note that these restrictions apply to all users but
<em>not</em> to the password changes done by the root user. The root user will
be able to set up any password (any length or complexity) for personal use or others
regardless of the restrictions defined here.

<sect2 id="pam-rootaccess">User access control in PAM

<p>To make sure that the user root can only log into the system from
local terminals, the following line should be enabled in
<file>/etc/pam.d/login</file>:

<example>
  auth     requisite  pam_securetty.so
</example>

<p>Then you should modify the list of terminals on which direct root login
is allowed in <file>/etc/securetty</file> (as described in <ref
id="restrict-console-login">). Alternatively, you could enable
the <tt>pam_access</tt> module and modify
<file>/etc/security/access.conf</file> which allows for a more general and
fine-tuned access control, but (unfortunately) lacks decent log
messages (logging within PAM is not standardized and is particularly
unrewarding problem to deal with). We'll return to <file>access.conf</file>
a little later.

<sect2 id="pam-limits">User limits in PAM

<p> The following line should be enabled in <file>/etc/pam.d/login</file>
to set up user resource limits.

<example>
  session  required   pam_limits.so
</example>

<p>This restricts the system resources that users are allowed (see
below in <ref id="user-limits">).  For example, you could restrict the
number of concurrent logins (of a given group of users, or
system-wide), number of processes, memory size etc.


<sect2 id="pam-su">Control of su in PAM

<p>If you want to protect <prgn>su</prgn>, so that only some people can use it to
become root on your system, you need to add a new group "wheel" to your
system (that is the cleanest way, since no file has such a group
permission yet). Add root and the other users that should be able to
<prgn>su</prgn> to the root user to this group.  Then add the following line to
<file>/etc/pam.d/su</file>:

<example>
  auth        requisite   pam_wheel.so group=wheel debug
</example>

<p>This makes sure that only people from the group "wheel" can use
<prgn>su</prgn> to become root. Other users will not be able to become
root. In fact they will get a denied message if they try to become
root.

<p>If you want only certain users to authenticate at a PAM service,
this is quite easy to achieve by using files where the users who are
allowed to login (or not) are stored. Imagine you only want to allow
users 'ref' to log in via <prgn>ssh</prgn>. So you put them into
<file>/etc/sshusers-allowed</file> and write the following into
<file>/etc/pam.d/ssh</file>:

<example>
  auth        required    pam_listfile.so item=user sense=allow file=/etc/sshusers-allowed onerr=fail
</example>

<sect2 id="pam-temp">Temporary directories in PAM

<p>Since there have been a number of so called insecure tempfile 
vulnerabilities, thttpd is one example (see 
<url id="http://www.debian.org/security/2005/dsa-883" name="DSA-883-1">),
the <package>libpam-tmpdir</package> is a good package to install.
All you have to do is add the following to 
<file>/etc/pam.d/common-session</file>:

<example>
 session    optional     pam_tmpdir.so
</example>

<p>There has also been a discussion about adding this by default in Debian
configuration, but it s. See <url
id="http://lists.debian.org/debian-devel/2005/11/msg00297.html"> for 
more information.

<sect2 id="pam-undefined">Configuration for undefined PAM applications

<p>Finally, but not least, create <file>/etc/pam.d/other</file> and enter
the following lines:

<example>
  auth     required       pam_securetty.so
  auth     required       pam_unix_auth.so
  auth     required       pam_warn.so
  auth     required       pam_deny.so
  account  required       pam_unix_acct.so
  account  required       pam_warn.so
  account  required       pam_deny.so
  password required       pam_unix_passwd.so
  password required       pam_warn.so
  password required       pam_deny.so
  session  required       pam_unix_session.so
  session  required       pam_warn.so
  session  required       pam_deny.so
</example>

<p>These lines will provide a good default configuration for all
applications that support PAM (access is denied by default).


<sect1 id="user-limits">Limiting resource usage: the <file>limits.conf</file> file

<p>You should really take a serious look into this file. Here you can
define user resource limits. In old releases this configuration file
was <file>/etc/limits.conf</file>, but in newer releases (with PAM)
the <file>/etc/security/limits.conf</file> configuration file should
be used instead.

<p>If you do not restrict resource usage, <em>any</em> user with a
valid shell in your system (or even an intruder who compromised the
system through a service or a daemon going awry) can use up as much
CPU, memory, stack, etc. as the system can provide. This <em>resource
exhaustion</em> problem can be fixed by the use of PAM. 

<p>There is a way to add resource limits to some shells (for example,
<prgn>bash</prgn> has <prgn>ulimit</prgn>, see <manref section="1"
name="bash">), but since not all of them provide the same limits and
since the user can change shells (see <manref section="1"
name="chsh">) it is better to place the limits on the PAM modules as
they will apply regardless of the shell used and will also apply to
PAM modules that are not shell-oriented.

<p>Resource limits are imposed by the kernel, but they need to be
configured through the <file>limits.conf</file> and the PAM configuration
of the different services need to load the appropriate PAM. You can
check which services are enforcing limits by running:

<example>
$ find /etc/pam.d/ \! -name "*.dpkg*" | xargs -- grep limits |grep -v ":#"
</example>

<P>Commonly, <file>login</file>, <file>ssh</file> and the graphic
session managers (<file>gdm</file>, <file>kdm</file> or
<file>xdm</file>) should enforce user limits but you might want to do
this in other PAM configuration files, such as <file>cron</file>, to
prevent system daemons from taking over all system resources.

<p>The specific limits settings you might want to enforce depend on
your system's resources, that's one of the main reasons why no limits
are enforced in the default installation.</p>

<p>For example, the configuration example below enforces a 100 process
limit for all users (to prevent <em>fork bombs</em>) as well as a
limit of 10MB of memory per process and a limit of 10 simultaneous
logins. Users in the <tt>adm</tt> group have higher limits and
can produce core files if they want to (there is only a <em>soft</em>
limit).

<p>
<example>
*              soft    core            0
*              hard    core            0
*              hard    rss             1000
*              hard    memlock         1000
*              hard    nproc           100
*              -       maxlogins       1
*              hard    data            102400
*              hard    fsize           2048
@adm           hard    core            100000
@adm           hard    rss             100000
@adm           soft    nproc           2000
@adm           hard    nproc           3000
@adm           hard    fsize           100000
@adm           -       maxlogins       10
</example>

<p>These would be the limits a default user (including system daemons)
would have:

<example>
$ ulimit -a
core file size        (blocks, -c) 0
data seg size         (kbytes, -d) 102400
file size             (blocks, -f) 2048
max locked memory     (kbytes, -l) 10000
max memory size       (kbytes, -m) 10000
open files                    (-n) 1024
pipe size          (512 bytes, -p) 8
stack size            (kbytes, -s) 8192
cpu time             (seconds, -t) unlimited
max user processes            (-u) 100
virtual memory        (kbytes, -v) unlimited
</example>

<p>And these are the limits for an administrative user:

<example>
$ ulimit -a
core file size        (blocks, -c) 0
data seg size         (kbytes, -d) 102400
file size             (blocks, -f) 100000
max locked memory     (kbytes, -l) 100000
max memory size       (kbytes, -m) 100000
open files                    (-n) 1024
pipe size          (512 bytes, -p) 8
stack size            (kbytes, -s) 8192
cpu time             (seconds, -t) unlimited
max user processes            (-u) 2000
virtual memory        (kbytes, -v) unlimited
</example>


<p>For more information read:
<list>

<item><url
id="http://www.kernel.org/pub/linux/libs/pam/Linux-PAM-html/pam-6.html"
name="PAM reference guide for available modules">

<item><url
id="http://www.samag.com/documents/s=1161/sam0009a/0009a.htm"
name="PAM configuration article">.

<item> <url
id="http://seifried.org/security/os/linux/20020324-securing-linux-step-by-step.html"
name="Seifried's Securing Linux Step by Step"> on the <em>Limiting
users overview</em> section.

<item><url id="http://seifried.org/lasg/users/" name="LASG"> in the 
<em>Limiting and monitoring users</em> section.

</list>

<sect1>User login actions: edit <file>/etc/login.defs</file>
<p>
The next step is to edit the basic configuration and action upon user login.
Note that this file is not part of the PAM configuration, it's a configuration
file honored by <tt>login</tt> and <tt>su</tt> programs,
so it doesn't make sense tuning it for cases where neither of the two
programs are at least indirectly called (the <prgn>getty</prgn> program
which sits on the consoles and offers the initial login prompt 
<em>does</em> invoke <prgn>login</prgn>).

<example>
  FAILLOG_ENAB        yes
</example>

If you enable this variable, failed logins will be logged. It is important to
keep track of them to catch someone who tries a brute force attack.

<example>
  LOG_UNKFAIL_ENAB    no
</example>

<p>If you set this variable to 'yes' it will record unknown usernames if the
login failed.  It is best if you use 'no' (the default) since, otherwise,
user passwords might be inadvertenly logged here (if a user mistypes
and they enter their password as the username). If you set it to 'yes', make
sure the logs have the proper permissions (640 for example, with an appropriate
group setting such as
adm).

<example>
  SYSLOG_SU_ENAB      yes
</example>

<p>This one enables logging of <prgn>su</prgn> attempts to <file>syslog</file>.
Quite important on serious machines but note that this can create privacy
issues as well.

<example>
  SYSLOG_SG_ENAB      yes
</example>

<p>The same as <var>SYSLOG_SU_ENAB</var> but applies to the <prgn>sg</prgn> 
program.

<example>
  ENCRYPT_METHOD  SHA512
</example>

<p>As stated above, encrypted passwords greatly reduce the problem of
dictionary attacks, since you can use longer passwords. This definition has to
be consistent with the value defined in
<file>/etc/pam.d/common-password</file>.

<sect1>User login actions: edit <file>/etc/pam.d/login</file>

<p>You can adjust the login configuration file to implement an stricter policy.
For example, you can change the default configuration and increase the delay
time between login prompts.  The default configuration sets a 3 seconds delay:

<example>
auth       optional   pam_faildelay.so  delay=3000000
</example>

<p>Increasing the <em>delay</em> value  to a higher value to make it harder to
use the terminal to log in using brute force. If a wrong password is
typed in, the possible attacker (or normal user!) has to wait longer
seconds to get a new login prompt, which is quite time consuming when
you test passwords. For example, if you set <em>delay=10000000</em>, users
will have to wait 10 seconds if they type a wrong password.

<p>In this file you can also set the system to present a message to users before
a user logs in. The default is disabled, as shown below:

<example>
# auth       required   pam_issue.so issue=/etc/issue
</example>

<p>If required by your security policy, this file can be used to show a standard
message indicating that access to the system is restricted and user acess is
logged. This kind of disclaimer might be required in some environments and
jurisdictions. To enable it, just include the relevant information in
the <file>/etc/issue</file>
<footnote>The default content of this file provides
information about the operating system and version run by the system, which
you might not want to provide to anonymous users.</footnote>
file and uncomment the line enabling the pam_issue.so module in 
<file>/etc/pam.d/login</file>.

In this file you can also enable additional features which might be 
relevant to apply local security policies such as:

<list>

<item>setting rules for which users can access at which times, by enabling the
<em>pam_time.so</em> module and configuring
<file>/etc/security/time.conf</file> accordingly (disabled by default),

<item>setup login sessions to use user limits as defined in
<file>/etc/security/limits.conf</file> (enabled by default),

<item>present the user with the information of previous login information
(enabled by default),

<item>print a message (<file>/etc/motd</file> and
<file>/run/motd.dynamic</file>) to users after login in (enabled by default),

</list>

<sect1>Restricting ftp: editing <file>/etc/ftpusers</file>
<p>
The <file>/etc/ftpusers</file> file contains a list of users who are
not allowed to log into the host using ftp. Only use this file if you
really want to allow ftp (which is not recommended in general, because
it uses clear-text passwords). If your daemon supports PAM, you can
also use that to allow and deny users for certain services.

<p>FIXME (BUG): Is it a bug that the default <file>ftpusers</file> in Debian 
does <em>not</em> include all the administrative users (in 
<package>base-passwd</package>).

<p>
A convenient way to add all system accounts to the <file>/etc/ftpusers</file>
is to run

<example>
$ awk -F : '{if ($3<1000) print $1}' /etc/passwd > /etc/ftpusers
</example>

<sect1>Using su

<p>
If you really need users to become the super user on your system, e.g. for 
installing packages or adding users, you can use the command <prgn>su</prgn> 
to change your identity. You should try to avoid any login as user root and 
instead use <prgn>su</prgn>.  Actually, the best solution is to remove 
<prgn>su</prgn> and switch to the <prgn>sudo</prgn> mechanism which has
a broader logic and more features than 
<prgn>su</prgn>. However, <prgn>su</prgn> is more common as it is used on many 
other Unices.


<sect1>Using sudo

<p>
<prgn>sudo</prgn> allows the user to execute defined commands under
another user's identity, even as root. If the user is added to
<file>/etc/sudoers</file> and authenticates correctly, the commands defined in
<file>/etc/sudoers</file> get enabled. Violations, such as incorrect passwords or
trying to run a program you don't have permission for, are logged and
mailed to root.

<sect1>Disallow remote administrative access
<p>You should also modify <file>/etc/security/access.conf</file> to
disallow remote logins to administrative accounts. This way users
need to invoke <prgn>su</prgn> (or <prgn>sudo</prgn>)
to use any administrative powers and the appropriate audit trace
will always be generated.

<p>You need to add the following line to
<file>/etc/security/access.conf</file>, the default Debian
configuration file has a sample line commented out:
<example>
   -:wheel:ALL EXCEPT LOCAL
</example>

<p>Remember to enable the <tt>pam_access</tt> module for every
service (or default configuration) in <file>/etc/pam.d/</file> if you
want your changes to <file>/etc/security/access.conf</file> honored.


<sect1 id="user-restrict">Restricting users's access

<p>Sometimes you might think you need to have users created in your
local system in order to provide a given service (pop3 mail service or
ftp). Before doing so, first remember that the PAM implementation in
Debian GNU/Linux allows you to validate users with a wide variety of
external directory services (radius, ldap, etc.) provided by the
libpam packages.

<p>If users need to be created and the system can be accessed remotely
take into account that users will be able to log in to the system. You
can fix this by giving users a null (<file>/dev/null</file>) shell (it
would need to be listed in <file>/etc/shells</file>). If you want to
allow users to access the system but limit their movements, you can
use the <file>/bin/rbash</file>, equivalent to adding the <tt>-r</tt>
option in <prgn>bash</prgn> (<em>RESTRICTED SHELL</em> see <manref name="bash"
section="1">). Please note that even with restricted shell, a user
that access an interactive program (that might allow execution of a
subshell) could be able to bypass the limits of the shell.

<p>Debian currently provides in the unstable release (and might be included in 
the next stable releases) the <file>pam_chroot</file> module (in the <package>
libpam-chroot</package>). An alternative to it is to <prgn>chroot</prgn> the 
service that provides remote logging (<prgn>ssh</prgn>, <prgn>telnet</prgn>).
<footnote><package>libpam-chroot</package> has not been yet thoroughly
tested, it does work for <prgn>login</prgn> but it might not be easy to set up 
the environment for other programs</footnote>

<p>If you wish to restrict <em>when</em> users can access the system you will
have to customize <file>/etc/security/access.conf</file> for your
needs.

<p>Information on how to <prgn>chroot</prgn> users accessing the
system through the <prgn>ssh</prgn> service is described in <ref
id="chroot-ssh-env">.

<sect1>User auditing

<p>If you are really paranoid you might want to add a system-wide
configuration to audit what the users are doing in your system.
This sections presents some tips using diverse utilities you can use.

<sect2>Input and output audit with script

<P>You can use the <prgn>script</prgn> command to audit both what the
users run and what are the results of those commands.
You cannot setup <prgn>script</prgn> as a shell 
(even if you add it to <file>/etc/shells</file>). But you can have the
shell initialization file run the following:

<example>
umask 077
exec script -q -a "/var/log/sessions/$USER"
</example>

<p>Of course, if you do this system wide it means that the shell would
not continue reading personal initialization files (since the shell
gets overwritten by <prgn>script</prgn>). An alternative is to do this
in the user's initialization files (but then the user could remove this,
see the comments about this below)
</p>

<p>You also need to setup the
files in the audit directory (in the example <file>/var/log/sessions/</file>)
so that users can write to it but cannot remove the file. This could be
done, for example, by creating the user session files in advance and
setting them with the <em>append-only</em> flag using <prgn>chattr</prgn>.
</p>

<p>A useful alternative for sysadmins, which includes date information
would be:

<example>
umask 077
exec script -q -a "/var/log/sessions/$USER-`date +%Y%m%d`"
</example>

<sect2>Using the shell history file

<p>If you want to review what does the user type in the shell (but not
what the result of that is) you can setup a system-wide
<file>/etc/profile</file> that configures the
environment so that all commands are saved into a history file.
The system-wide configuration needs to be setup in such a way that users 
cannot remove audit capabilities from their shell. This is somewhat
shell specific so make sure that all users are using a shell that
supports this.</p>

<p>For example, for bash, the <file>/etc/profile</file> 
could be set as follows
<footnote>
Setting HISTSIZE to a very large number can cause issues under some
shells since the history is kept in memory for every user session. You
might be safer if you set this to a high-enough value and backup
user's history files (if you need all of the user's history for 
some reason)
</footnote>
:

<example>
  HISTFILE=~/.bash_history
  HISTSIZE=10000
  HISTFILESIZE=999999
  # Don't let the users enter commands that are ignored
  # in the history file
  HISTIGNORE=""
  HISTCONTROL=""
  readonly HISTFILE
  readonly HISTSIZE
  readonly HISTFILESIZE
  readonly HISTIGNORE
  readonly HISTCONTROL
  export HISTFILE HISTSIZE HISTFILESIZE HISTIGNORE HISTCONTROL
</example>

<p>For this to work, the user can only append information to
<file>.bash_history</file> file. You need <em>also</em> to set the 
<em>append-only</em> option using <prgn>chattr</prgn> program 
for <file>.bash_history</file> for all users.
<footnote>
Without the append-only flag users would be able to empty the 
contents of the history file running <tt> > .bash_history</tt>
</footnote>.

<p>Note that you could introduce the configuration above in 
the user's <file>.profile</file>. But
then you would need to setup permissions properly in such a way that
prevents the user from modifying this file. This includes: having the user's
home directories <em>not</em> belong to the user (since the user would
be able to remove the file otherwise) but at the same time allow the user to read the <file>.profile</file> configuration file and write on the
<file>.bash_history</file>. It would be good to set
the <em>immutable</em> flag (also using <prgn>chattr</prgn>)
for <file>.profile</file> too if you do it this way.

<sect2>Complete user audit with accounting utilities

<p>The previous example is a simple way to configure user auditing
but might be not useful for complex systems or for those in which users 
do not run shells at all (or exclusively). If this is your case,
you need to look at <package>acct</package>, the accounting
utilities. These utilities will log all the commands run by users or processes
in the system, at the expense of disk space.

<p>When activating accounting, all the information on processes and
users is kept under <file>/var/account/</file>, more specifically in
the <file>pacct</file>. The accounting package includes some tools
(<prgn>sa</prgn>, <prgn>ac</prgn> and <prgn>lastcomm</prgn>) to analyse
this data.

<sect2>Other user auditing methods
<p>If you are completely paranoid and want to audit every user's command, you 
could take <prgn>bash</prgn> source code, edit it and have it send all that 
the user typed into another file. Or have <package>ttysnoop</package> 
constantly monitor any new ttys
<footnote>Ttys are spawned for local logins and remote logins through ssh and telnet</footnote>
and dump the output into a file. Other useful 
program is <package>snoopy</package> 
(see also  <url id="http://sourceforge.net/projects/snoopylogger/" name="the project page">)
which is a user-transparent program that 
hooks in as a library providing a wrapper around <var>execve()</var> 
calls, any command executed is logged to <prgn>syslogd</prgn> using the 
<tt>authpriv</tt> facility (usually stored at <file>/var/log/auth.log</file>).

<sect1>Reviewing user profiles

<p>If you want to <em>see</em> what users are actually doing when they 
logon to the system you can use the <file>wtmp</file> database that
includes all login information. This file can be processed with
several utilities, amongst them <prgn>sac</prgn> which can output a
profile on each user showing in which timeframe they usually log on to
the system.

<p>In case you have accounting activated, you can also use the tools
provided by it in order to determine when the users access the
system and what do they execute. 

<sect1>Setting users umasks

<p>Depending on your user policy you might want to change how
information is shared between users, that is, what the default
permissions of new files created by users are. 

<p>Debian's default <tt>umask</tt> setting is <em>022</em> this means
that files (and directories) can be read and accessed by the user's
group and by any other users in the system. This definition is set
in the standard configuration file <file>/etc/profile</file> which 
is used by all shells.

<p>If Debian's default value is too permissive for your system you will have to
change the umask setting for all the shells. More restrictive umask settings
include 027 (no access is allowed to new files for the <em>other</em> group,
i.e. to other users in the system) or 077 (no access is allowed to new files
to the members the user's group). Debian (by default<footnote><p>As defined in 
<file>/etc/adduser.conf</file> (USERGROUPS=yes). You can change this behaviour if
you set this value to no, although it is not recommended</p></footnote>)
creates one group per user so that only the user is included in its group.
Consequently 027 and 077 are equivalent as the user's group contains only the
user.

<p>This change is set by defining a proper <tt>umask</tt> setting for all
users. You can change this by introducing an <prgn>umask</prgn> call
in the shell configuration files: <file>/etc/profile</file> (source by
all Bourne-compatible shells), <file>/etc/csh.cshrc</file>,
<file>/etc/csh.login</file>, <file>/etc/zshrc</file> and probably some
others (depending on the shells you have installed on your system). You
can also change the <var>UMASK</var> setting in <file>/etc/login.defs</file>,
Of all of these the last one that gets loaded by the shell takes precedence.
The order is: the default system configuration for the user's shell (i.e.
<file>/etc/profile</file> and other system-wide configuration files) and then
the user's shell (his <file>~/.profile</file>, <file>~/.bash_profile</file>,
etc...).  Some shells, however, can be executed with a <em>nologin</em> value
which might skip sourcing some of those files. See your shell's manpage
for additional information.

<p>For connections that make use of <prgn>login</prgn> the UMASK definition in
<file>/etc/login.defs</file> is used before any of the others. However, that
value does not apply to user executed programs  that do not use
<prgn>login</prgn> such as those run through <prgn>su</prgn>, <prgn>cron</prgn>
or <prgn>ssh</prgn>.

<p>Don't forget to review and maybe modify the dotfiles under
<file>/etc/skel/</file> since these will be new user's defaults when created
with the <prgn>adduser</prgn> command. Debian default dotfiles do not include
any <prgn>umask</prgn> call but if there is any in the dotfiles newly created
users might a different value.

<p>Note, however that users can modify their own <tt>umask</tt> setting if they
want to, making it more permissive or more restricted, by changing their
own dotfiles.

<p>The <package>libpam-umask</package> package adjusts the users' default
<tt>umask</tt> using PAM.  Add the following, after installing the package, to 
<file>/etc/pam.d/common-session</file>:

<example>
session    optional     pam_umask.so umask=077
</example>

<p>Finally, you should consider changing root's default 022 umask (as defined
in <file>/root/.bashrc</file>) to a more strict umask. That will prevent the
system administrator from inadvertenly dropping sensitive files when working as
root to world-readable directories (such as <file>/tmp</file>) and having
them available for your average user.

<sect1>Limiting what users can see/access

<P>FIXME: Content needed. Describe the consequences of changing packages 
permissions when upgrading (an admin this paranoid should <prgn>chroot</prgn> 
his users BTW) if not using <prgn>dpkg-statoverride</prgn>.

<p>If you need to grant users access to the system with a shell think
about it very carefully. A user can, by default unless in a severely
restricted environment (like a <tt>chroot</tt> jail), retrieve
quite a lot of information from your system including:

<list>

<item>some configuration files in <file>/etc</file>. However, Debian's default
permissions for some sensitive files (which might, for example,
contain passwords), will prevent access to critical information. To
see which files are only accessible by the root user
for example <tt>find /etc -type f -a -perm 600 -a -uid 0</tt> as
superuser.

<item>your installed packages, either by looking at the package
database, at the <file>/usr/share/doc</file> directory or by guessing
by looking at the binaries and libraries installed in your system.

<item>some log files at <file>/var/log</file>. Note also that some
log files are only accessible to root and the <tt>adm</tt> group (try
<tt>find /var/log -type f -a -perm 640</tt>) and some are even only
available to the root user (try <tt>find /var/log -type f -a -perm
600 -a -uid 0</tt>).

</list>


<p>What can a user see in your system? Probably quite a lot of things,
try this (take a deep breath):
<example>
  find / -type f -a -perm +006 2>/dev/null  
  find / -type d -a -perm +007 2>/dev/null  
</example>

<p>The output is the list of files that a user can <em>see</em> and
the accessable directories.

<sect2 id="limit-user-perm">Limiting access to other user's information

<p>If you still grant shell access to users you might want to limit
what information they can view from other users. Users with shell
access have a tendency to create quite a number of files under their
$HOMEs: mailboxes, personal documents, configuration of X/GNOME/KDE
applications... 

<p>In Debian each user is created with one associated group, and
no two users belong to the same group. This is the default behavior:
when an user account is created, a group
of the same name is created too, and the user is assigned to it.
This avoids the concept of a common <em>users</em>
group which might make it more difficult for users to hide information
from other users.

<p>However, users' <var>$HOME</var> directories are created with 0755 
permissions (group-readable and world-readable). The group permissions is not 
an issue since only the user belongs to the group, however the world 
permissions might (or might not) be an issue depending on your local policy.

<p>You can change this behavior so that user creation provides different 
<var>$HOME</var> permissions. To change the behavior for <em>new</em> users 
when they get created, change <em>DIR_MODE</em> in the configuration file 
<file>/etc/adduser.conf</file> to 0750 (no world-readable access).

<p>Users can still share information, but not directly in their 
<var>$HOME</var> directories unless they change its permissions.

<p>Note that disabling world-readable home directories will prevent
users from creating their personal web pages in the <file>~/public_html</file> 
directory, since the web server will not be able to read one component in
the path - namely their <var>$HOME</var> directory.
If you want to permit
users to publish HTML pages in their <file>~/public_html</file>,
then change <em>DIR_MODE</em> to 0751. This will allow the web server
to access the final <file>public_html</file> directory (which itself should
have a mode of 0755) and provide the content published by users.
Of course, we are only talking about a default configuration here; users
can generally tune modes of their own files completely to their liking,
or you could keep content intended for the web in a separate location 
which is not a subdirectory of user's <var>$HOME</var> directory.

<sect1 id="user-pwgen">Generating user passwords

<p>There are many cases when an administrator needs to create many
user accounts and provide passwords for all of them. Of course, the
administrator could easily just set the password to be the same as the
user's account name, but that would not be very sensitive
security-wise. A better approach is to use a password generating
program. Debian provides <package>makepasswd</package>,
<package>apg</package> and <package>pwgen</package> packages which
provide programs (the name is the same as the package) that can be
used for this purpose. <prgn>Makepasswd</prgn> will generate true
random passwords with an emphasis on security over pronounceability
while <prgn>pwgen</prgn> will try to make meaningless but
pronounceable passwords (of course this might depend on your mother
language). <prgn>Apg</prgn> has algorithms to provide for both (there
is a client/server version for this program but it is not included in
the Debian package).

<p><prgn>Passwd</prgn> does not allow non-interactive assignation of
passwords (since it uses direct tty access). If you want to change
passwords when creating a large number of users you can create them
using <prgn>adduser</prgn> with the <tt>--disabled-login</tt> option
and then use <prgn>usermod</prgn> or <prgn>chpasswd</prgn>
<footnote>
<prgn>Chpasswd</prgn> cannot handle MD5 password generation so it needs to be 
given the password in encrypted form before using it, with the <tt>-e</tt>
option.
</footnote>
(both from the <package>passwd</package> package so you already have them
installed). If you want to use a file with all the information to make
users as a batch process you might be better off using
<prgn>newusers</prgn>.

<sect1>Checking user passwords

<p>User passwords can sometimes become the <em>weakest link</em> in the 
security of a given system. This is due to some users choosing weak passwords 
for their accounts (and the more of them that have access to it the greater 
the chances of this happening). Even if you established checks with the 
cracklib PAM module and password limits as described in <ref id="auth-pam"> 
users will still be able to use weak passwords. Since user access might 
include remote shell access (over <prgn>ssh</prgn>, hopefully) it's important 
to make password guessing as hard as possible for the remote attackers, 
especially if they were somehow able to collect important information such
as usernames or even the <file>passwd</file> and <file>shadow</file> files
themselves.

<p>A system administrator must, given a big number of users, check if
the passwords they have are consistent with the local security
policy. How to check? Try to crack them as an attacker would if having
access to the hashed passwords (the <file>/etc/shadow</file> file). 

<p>An administrator can use <package>john</package> or <package>crack</package>
(both are brute force password crackers) together with an appropriate wordlist 
to check users' passwords and take appropriate action when a weak
password is detected.
You can search for Debian GNU packages that contain word lists using 
<prgn>apt-cache search wordlist</prgn>, or visit the classic Internet
wordlist sites such as 
<url id="ftp://ftp.ox.ac.uk/pub/wordlists"> or
<url id="ftp://ftp.cerias.purdue.edu/pub/dict">.

<sect1 id="idle-logoff">Logging off idle users

<p>Idle users are usually a security problem, a user might be idle
maybe because he's out to lunch or because a remote connection
hung and was not re-established. For whatever the reason, idle users
might lead to a compromise:

<list>
<item>because the user's console might be unlocked and can be
accessed by an intruder.  

<item>because an attacker might be able to re-attach to a
closed network connection and send commands to the remote shell (this
is fairly easy if the remote shell is not encrypted as in the case of
<prgn>telnet</prgn>).
</list>

<p>Some remote systems have even been compromised
through an idle (and detached) <prgn>screen</prgn>.

<p>Automatic disconnection of idle users is usually a part of the local 
security policy that must be enforced. There are several ways to do this:

<list>
<item>If <prgn>bash</prgn> is the user shell, a system administrator 
can set a default <tt>TMOUT</tt> value (see <manref section="1" name="bash">) 
which will make the shell automatically log off remote idle users. Note that it 
must be set with the <tt>-o</tt> option or users will be able to 
change (or unset) it.

<item>Install <package>timeoutd</package> and configure
<file>/etc/timeouts</file> according to your local security
policy. The daemon will watch for idle users and time out their shells
accordingly.
<!-- FIXME : Does 'screen' prevent timeoutd from detecting idle time like
I think it does, or it was due to my tricks with ttysnoop. -->

<item>Install <package>autolog</package> and configure it to remove idle users.

</list>

<p>The <prgn>timeoutd</prgn> or <prgn>autolog</prgn> daemons are the
preferred method since, after all, users can change their default shell
or can, after running their default shell, switch to another
(uncontrolled) shell.


<sect id="tcpwrappers">Using tcpwrappers 

<p>TCP wrappers were developed when there were no real packet filters
available and access control was needed. Nevertheless, they're still very 
interesting and useful.
The TCP wrappers allow you to
allow or deny a service for a host or a domain and define a default
allow or deny rule (all performed on the application level).
If you want more information take a look at
<manref name="hosts_access" section="5">.

<p>Many services installed in Debian are either:

<list>
<item>launched through the tcpwrapper service (<file>tcpd</file>)
<item>compiled with libwrapper support built-in.
</list>

<p>On the one hand, for services configured in
<file>/etc/inetd.conf</file> (this includes <prgn>telnet</prgn>, 
<prgn>ftp</prgn>, <prgn>netbios</prgn>, <prgn>swat</prgn>
and <prgn>finger</prgn>) you will see that the configuration file executes
<prgn>/usr/sbin/tcpd</prgn> first. On the other hand, even if a
service is not launched by the <prgn>inetd</prgn> superdaemon,
support for the tcp wrappers rules can be compiled
into it. Services compiled with tcp wrappers in Debian include
<prgn>ssh</prgn>, <prgn>portmap</prgn>, <prgn>in.talk</prgn>,
<prgn>rpc.statd</prgn>, <prgn>rpc.mountd</prgn>, <prgn>gdm</prgn>,
<prgn>oaf</prgn> (the GNOME
activator daemon), <prgn>nessus</prgn> and many others. 

<p>To see which packages use tcpwrappers
<footnote>
<p>On older Debian releases you might need to do this:
<example>
  $ apt-cache showpkg libwrap0 | egrep '^[[:space:]]' | sort -u | \
        sed 's/,libwrap0$//;s/^[[:space:]]\+//'
</example>
</footnote>
try:

<example>
  $ apt-cache rdepends libwrap0
</example>


<p>Take this into account when running <prgn>tcpdchk</prgn>
(a very useful TCP wrappers config file rule and syntax checker).
When you add stand-alone services (that are directly linked with the wrapper
library) into the <file>hosts.deny</file> and <file>hosts.allow</file> files,
<prgn>tcpdchk</prgn> will warn you that it is not able to find
the mentioned services since it only looks for them in
<file>/etc/inetd.conf</file> (the manpage is not totally accurate here).

<p>Now, here comes a small trick, and probably the smallest intrusion 
detection system available. In general, you should have a decent firewall 
policy as a first line, and tcp wrappers as the second line of defense. One 
little trick is to set up a <var>SPAWN</var> <footnote>be sure to use 
uppercase here since <em>spawn</em> will not work</footnote> command in 
<file>/etc/hosts.deny</file> that sends mail to root whenever a denied service
triggers wrappers:

<example>
  ALL: ALL: SPAWN ( \
    echo -e "\n\
    TCP Wrappers\: Connection refused\n\
    By\: $(uname -n)\n\
    Process\: %d (pid %p)\n\
    User\: %u\n\
    Host\: %c\n\
    Date\: $(date)\n\
  " | /usr/bin/mail -s "Connection to %d blocked" root) &
</example>

<p><em>Beware</em>: The above printed example is open to a DoS attack by
making many connections in a short period of time. Many emails mean
a lot of file I/O by sending only a few packets.

<!--
# Could this example be more interesting? 
# It also relates to the next section (jfs)
#
# era: cf hosts_access(5) manual page,
# and why are you not using logger(1) here? (FIXME?)
#
#&lt;example&gt;
#ALL: ALL: SPAWN ( \
#  /usr/local/sbin/send_syslog %u %c %d )
#&lt;example&gt;

#  With send_syslog as:
##!/usr/bin/perl -w
#
#use Sys::Syslog qw(:DEFAULT setlogsock);
#
#$user=shift(@ARGV) || 'unknown';
#$host=shift(@ARGV) || 'unknown';
#$service=shift(@ARGV) || 'unknown';
#setlogsock('unix');
#openlog("alert",'', 'user');
#syslog('warning', 'Connection from %s at %s to %s blocked.', ($user, $host, $service) );
#closelog();
#
#exit 0;
-->

<sect id="log-alerts">The importance of logs and alerts

<p>It is easy to see that the treatment of logs and alerts is an
important issue in a secure system. Suppose a system is perfectly
configured and 99% secure. If the 1% attack occurs, and there are no
security measures in place to, first, detect this and, second, raise
alarms, the system is not secure at all.

<p>Debian GNU/Linux provides some tools to perform log analysis, most notably 
<package>swatch</package>, <footnote>there's a very good article on it written 
by <url id="http://www.spitzner.net/swatch.html" name="Lance Spitzner">
</footnote> <package>logcheck</package> or <package>log-analysis</package> 
(all will need some customisation to remove unnecessary things from the 
report). It might also be useful, if the system is nearby, to have the system 
logs printed on a virtual console. This is useful since you can (from a 
distance) see if the system is behaving properly. Debian's 
<file>/etc/syslog.conf</file> comes with a commented default configuration; to 
enable it uncomment the lines and restart <prgn>syslogd</prgn>
(<tt>/etc/init.d/syslogd restart</tt>):

<example>
  daemon,mail.*;\
        news.=crit;news.=err;news.=notice;\
        *.=debug;*.=info;\
        *.=notice;*.=warn       /dev/tty8
</example>


<p>
To colorize the logs, you could take a look at
<package>colorize</package>, <package>ccze</package> or
<package>glark</package>. There is a lot to log analysis that
cannot be fully covered here, so a good information resource would be books
should as
<url name="Security log management: identifying patterns in the chaos"
id="http://books.google.com/books?id=UyktqN6GnWEC">.
In any case, even automated tools are no match for the best
analysis tool: your brain. 

<!-- FIXME: Add information related to OSSEC, however
     it is currently not packaged for Debian

Information relevant for OSSEC :

- Web page: http://www.ossec.net/
- Ubuntu Guide: http://ubuntuforums.org/showthread.php?t=213445
- ITP: http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=361954
  (Reason it is not currently packaged, as of, dic 2010 is because
  of a need of OpenSSL excemption)
     Point to the book: http://books.google.com/books?id=h37q2q3wvcUC
-->

<!-- FIXME: Check information on SHARP, the 'syslog heuristic analysis
and response program'. The paper is at
id="http://www.csis.gvsu.edu/sharp/". Is it free software? packaged?

URL doesn't exist any more, but its archive on archive.org:
http://web.archive.org/web/20020816100838/http://www.csis.gvsu.edu/sharp/
http://web.archive.org/web/20020816100838/http://www.csis.gvsu.edu/sharp/sharp.ps

No download location is available.
-->

<sect1 id="custom-logcheck">Using and customizing <prgn>logcheck</prgn>

<p>The <prgn>logcheck</prgn> package in Debian is divided into the
three packages <package>logcheck</package> (the main program),
<package>logcheck-database</package> (a database of regular
expressions for the program) and <package>logtail</package> (prints
loglines that have not yet been read). The Debian default (in
<file>/etc/cron.d/logcheck</file>) is that <prgn>logcheck</prgn> is run
every hour and after reboots.

<p>This tool can be quite useful if properly customized to alert the
administrator of unusual system events. <prgn>Logcheck</prgn>
can be fully customized so that it sends mails based on events found
in the logs and worthy of attention. The default
installation includes profiles for ignored events and policy
violations for three different setups (workstation, server and
paranoid). The Debian package includes a configuration file
<file>/etc/logcheck/logcheck.conf</file>, sourced by the program, that
defines which user the checks are sent to. It also provides a way for
packages that provide services to implement new policies in the
directories: <file>/etc/logcheck/cracking.d/_packagename_</file>,
<file>/etc/logcheck/violations.d/_packagename_</file>,
<file>/etc/logcheck/violations.ignore.d/_packagename_</file>,
<file>/etc/logcheck/ignore.d.paranoid/_packagename_</file>,
<file>/etc/logcheck/ignore.d.server/_packagename_</file>, and
<file>/etc/logcheck/ignore.d.workstation/_packagename_</file>. However,
not many packages currently do so. If you have a policy that can be
useful for other users, please send it as a bug report for the
appropriate package (as a <em>wishlist</em> bug). For more information read
<file>/usr/share/doc/logcheck/README.Debian</file>.

<p>The best way to configure <prgn>logcheck</prgn> is to edit its
main configuration file <file>/etc/logcheck/logcheck.conf</file>
after installation. Change the default user (root) to whom reports 
should be mailed. You should set the reportlevel in there, too.
<package>logcheck-database</package> has three report levels of 
increasing verbosity: workstation, server, paranoid.
"server" being the default level, paranoid is only recommended
for high-security machines running as few services as possible
and workstation for relatively sheltered, non-critical machines.
If you wish to add new log files just add them to
<file>/etc/logcheck/logcheck.logfiles</file>. It is tuned for default
syslog install.

<p>Once this is done you might want to check the mails that are sent, for the 
first few days/weeks/months. If you find you are sent messages you do not wish 
to receive, just add the regular expressions (see
<manref name="regex" section="7"> and <manref name="egrep" section="1">) that
correspond to these messages to the
<file>/etc/logcheck/ignore.d.<var>reportlevel</var>/local</file>.
Try to match the whole logline. Details on howto write rules are explained in
<file>/usr/share/doc/logcheck-database/README.logcheck-database.gz</file>.
It's an ongoing tuning process; once the messages that are sent are always
relevant you can consider the tuning finished.  Note that if
<prgn>logcheck</prgn> does not find anything relevant in your system
it will not mail you even if it does run (so you might get a mail only
once a week, if you are lucky).


<sect1>Configuring where alerts are sent

<p>Debian comes with a standard <tt>syslog</tt> configuration (in 
<file>/etc/syslog.conf</file>) that logs messages to the appropriate files 
depending on the system facility.  You should be familiar with this; have a 
look at the <file>syslog.conf</file> file and the documentation if not. If you 
intend to maintain a secure system you should be aware of where log messages 
are sent so they do not go unnoticed.

<p>For example, sending messages to the console also is an interesting
setup useful for many production-level systems. But for many such
systems it is also important to add a new machine that will serve as
loghost (i.e. it receives logs from all other systems).

<p>Root's mail should be considered also, many security controls (like
<package>snort</package>) send alerts to root's mailbox. This 
mailbox usually points to
the first user created in the system (check <file>/etc/aliases</file>).
Take care to send root's mail to some place where it will be read (either
locally or remotely).

<p>There are other role accounts and aliases on your system.  On a
small system, it's probably simplest to make sure that all such
aliases point to the root account, and that mail to root is forwarded
to the system administrator's personal mailbox.

<p>FIXME: It would be interesting to tell how a Debian system can
send/receive SNMP traps related to security problems (jfs). Check:
<package>snmptrapfmt</package>, <package>snmp</package> and
<package>snmpd</package>.


<sect1>Using a loghost

<p>A loghost is a host which collects syslog data remotely over the
network. If one of your machines is cracked, the intruder is not able
to cover the tracks, unless hacking the loghost as well.  So, the
loghost should be especially secure.  Making a machine a loghost is
simple. Just start the <prgn>syslogd</prgn> with <tt>syslogd -r</tt> 
and a new loghost is born. In order to do this permanently in Debian, edit
<file>/etc/default/syslogd</file> and change the line

<!-- FIXME: The following could also be interesting -->
<!-- How to hide the logging server on the network i.e. by not giving -->
<!-- it an IP address and adding a static ARP entry on the hosts using -->
<!-- the remote syslog server (only if on the same hub); if the remote -->
<!-- syslog server would be on a separate network, the default gateway -->
<!-- should be configured accordingly. -->

<example>
SYSLOGD=""
</example>
to 
<example>
SYSLOGD="-r"
</example>

Next, configure the other machines to send data to the loghost. Add
an entry like the following to <file>/etc/syslog.conf</file>:

<example>
  facility.level            @your_loghost
</example>

See the documentation for what to use in place of <em>facility</em>
and <em>level</em> (they should not be entered verbatim like this).
If you want to log everything remotely, just write:

<example>
  *.*                       @your_loghost
</example>

into your <file>syslog.conf</file>. Logging remotely as well as locally 
is the best solution (the attacker might presume to have covered 
his tracks after deleting the local log files). See the <manref name="syslog"
section="3">, <manref name="syslogd" section="8"> and <manref
name="syslog.conf" section="5"> manpages for additional information.


<sect1>Log file permissions

<p>It is not only important to decide how alerts are used, but also
who has read/modify access to the log files (if not
using a remote loghost).  Security alerts which the attacker can
change or disable are not worth much in the event of an intrusion.
Also, you have to take into account that log files might reveal
quite a lot of information about your system to an intruder 
who has access to them.

<!--  It should be explained why after installation this is not
 already done, jfs -->

<p>Some log file permissions are not perfect after the installation (but of 
course this really depends on your local security policy). First 
<file>/var/log/lastlog</file> and <file>/var/log/faillog</file> do not need to 
be readable by normal users. In the <file>lastlog</file> file you can see who 
logged in recently, and in the <file>faillog</file> you see a summary of failed
logins. The author recommends <prgn>chmod 660</prgn> for both. Take a brief 
look at your log files and decide very carefully which log files to make 
readable/writable for a user with a UID other than 0 and a group other than 
'adm' or 'root'. You can easily check this in your system with:

<example>
  #  find /var/log -type f -exec ls -l {} \; | cut -c 17-35 |sort -u
  (see to what users do files in /var/log belong)
  #  find /var/log -type f -exec ls -l {} \; | cut -c 26-34 |sort -u
  (see to what groups do files in /var/log belong)
  # find /var/log -perm +004
  (files which are readable by any user)
  #  find /var/log \! -group root \! -group adm -exec ls -ld {} \;
  (files which belong to groups not root or adm)
</example>

<p>To customize how log files are created you will probably have to
customize the program that generates them. If the log file gets
rotated, however, you can customize the behavior of creation and rotation.

<!-- This is no longer true, check apache's logrotate
<p>
I want to emphasize that the apache log file permissions are really
screwed due to the fact that the apache user owns the apache log
files. If a user gets a shell with a back door in apache, they can
easily remove the log files.
-->

<sect id="kernel-patches">Adding kernel patches

<p>Debian GNU/Linux provides some of the patches for the Linux kernel
that enhance its security. These include:

<list>

<item>
<url id="http://www.lids.org" name="Linux Intrusion Detection">
provided in the <package>kernel-patch-2.4-lids</package> package.
This kernel patch makes the
process of hardening your Linux system easier by allowing you to
restrict, hide and protect processes, even from root. It implements
mandatory access control capabilities.


<item><url id="http://trustees.sourceforge.net/" name="Linux Trustees">,
provided in package <package>trustees</package>. This patch
adds a decent advanced permissions management system to your Linux kernel.
Special objects (called trustees) are bound to every file or directory, and
are stored in kernel memory, which allows fast lookup of all permissions.

<item>NSA Enhanced Linux (in package <package>selinux</package>). Backports
of the SElinux-enabled packages are available at
<url id="http://selinux.alioth.debian.org/">.
More
information available at
<url id="http://wiki.debian.org/SELinux" name="SElinux in Debian Wiki page">,
at 
<url id="http://www.golden-gryphon.com/software/security/selinux.xhtml" 
name="Manoj Srivastava's"> and
<url id="http://www.coker.com.au/selinux/" name="Russell Cookers's"> SElinux
websites.

<item>The <url id="http://people.redhat.com/mingo/exec-shield/"
name="exec-shield patch"> provided in the
<package>kernel-patch-exec-shield</package> package. This patch provides
protection against some buffer overflows (stack smashing attacks).

<item>The <url id="http://www.grsecurity.net/" name="Grsecurity patch">,
provided by the <package>kernel-patch-2.4-grsecurity</package> and
<package>kernel-patch-grsecurity2</package> packages
<footnote>
Notice that this patch conflicts with patches already included
in Debian's 2.4 kernel source package. You will need to
use the stock vanilla kernel. You can do this with the following steps:
<example>
# apt-get install kernel-source-2.4.22 kernel-patch-debian-2.4.22
# tar xjf /usr/src/kernel-source-2.4.22.tar.bz2
# cd kernel-source-2.4.22
# /usr/src/kernel-patches/all/2.4.22/unpatch/debian
</example>
<p>For more
information see <url id="http://bugs.debian.org/194225"
name="#194225">, <url id="http://bugs.debian.org/199519"
name="#199519">, <url id="http://bugs.debian.org/206458"
name="#206458">, <url id="http://bugs.debian.org/203759"
name="#203759">, <url id="http://bugs.debian.org/204424"
name="#204424">, <url id="http://bugs.debian.org/210762"
name="#210762">, <url id="http://bugs.debian.org/211213"
name="#211213">, and the <url
id="http://lists.debian.org/debian-devel/2003/debian-devel-200309/msg01133.html"
name="discussion at debian-devel">
</footnote>
implements Mandatory Access
Control through RBAC, provides buffer overflow protection through PaX, 
ACLs, network randomness (to make OS fingerprinting more difficult) and <url
id="http://www.grsecurity.net/features.php" name="many more
features">.

<item>The <package>kernel-patch-adamantix</package> provides the patches
developed for <url id="http://www.adamantix.org/" name="Adamantix">,
a Debian-based distribution. This kernel patch for the 2.4.x kernel
releases introduces some security features such as a non-executable stack
through the use of 
<url id="http://pageexec.virtualave.net/" name="PaX"> and mandatory
access control based on <url id="http://www.rsbac.org/" name="RSBAC" >.
Other features include: 
<url name="the Random PID patch" id="http://www.vanheusden.com/Linux/sp/">,
AES encrypted loop device, MPPE support and an IPSEC v2.6 backport.


<item><package>cryptoloop-source</package>. This patches allows you to
use the functions of the kernel crypto API 
to create encrypted filesystems using the loopback device.

<item>IPSEC kernel support (in package
<package>linux-patch-openswan</package>). If you want to use the
IPsec protocol with Linux, you need this patch. You can create VPNs
with this quite easily, even to Windows machines, as IPsec is a common
standard. IPsec capabilities have been added to the 2.5 development
kernel, so this feature will be present by default in the future Linux
Kernel 2.6. Homepage: <url id="http://www.openswan.org">. 

<em>FIXME</em>: The latest 2.4 kernels provided in Debian include a backport of
the IPSEC code from 2.5. Comment on this.

</list>

<p>The following security kernel patches are only available for old
kernel versions in woody and are deprecated:

<list>
<item><url id="http://acl.bestbits.at/" name="POSIX Access Control Lists">
(ACLs) for Linux provided in the package 
<package>kernel-patch-acl</package>. This kernel patch adds access
control lists, an advanced method for restricting access to files. It
allows you to control fine-grain access to files and directory. 

<item>The <url name="Openwall" id="http://www.openwall.com/linux/">
linux kernel patch by Solar Designer, provided in the 
<package>kernel-patch-2.2.18-openwall</package> package.
This is a useful set of kernel restrictions, like restricted
links, FIFOs in <file>/tmp</file>, a restricted <file>/proc</file>
file system, special file descriptor handling, non-executable user
stack area and other features. Note: This package applies to the 2.2
release, no packages are available for the 2.4 release patches provided
by Solar.

<item><package>kernel-patch-int</package>. This patch also adds
cryptographic capabilities to the Linux kernel, and was useful with
Debian releases up to Potato. It doesn't work with Woody, and if you
are using Sarge or a newer version, you should use a more recent
kernel which includes these features already.

</list>

<!-- FIXME: Make the entries coherent: should the package names be links to the
relevant package pages? -->

<p>However, some patches have not been provided in Debian yet. If you
feel that some of these should be included please ask for it at the
<url name="Work Needing and Prospective Packages"
id="http://www.debian.org/devel/wnpp/">.

<sect>Protecting against buffer overflows

<p><em>Buffer overflow</em> is the name of a common attack to software
<footnote>So common, in fact, that they have been the basis of 20% of the
reported security vulnerabilities every year, as determined by 
<url id="http://icat.nist.gov/icat.cfm?function=statistics"
name="statistics from ICAT's vulnerability database"></footnote>
which makes use of insufficient boundary checking (a 
programming error, most commonly in the C language) in order to execute
machine code through
program inputs. These attacks, against server software which listen
to connections remotely and against local software which grant higher
privileges to users (<tt>setuid</tt> or <tt>setgid</tt>) can result in the 
compromise of any given system.

<p>There are mainly four methods to protect against buffer overflows:

<list>

<item>patch the kernel to prevent stack execution. You can use either:
Exec-shield, OpenWall or PaX (included in the Grsecurity and Adamantix
patches).

<item>fix the source code by using tools to find fragments of it that
might introduce this vulnerability.

<item>recompile the source code to introduce proper checks that
prevent overflows, using the <url
id="http://www.research.ibm.com/trl/projects/security/ssp/" name="Stack
Smashing Protector (SSP)"> patch for GCC (which is used by <url
id="http://www.adamantix.org" name="Adamantix">)

</list>

<p>Debian GNU/Linux, as of the 3.0 release, provides software to
introduce all of these methods except for the protection on source
code compilation (but this has been requested in <url
id="http://bugs.debian.org/213994" name="Bug #213994">).

<p>Notice that even if Debian provided a compiler which featured
stack/buffer overflow protection all packages would need to be
recompiled in order to introduce this feature. This is, in fact, what
the Adamantix distribution does (among other features). The effect of this 
new feature on the stability of software is yet to be determined
(some programs or some processor architectures might break due to it).

<p>In any case, be aware that even these workarounds might not
prevent buffer overflows since there are ways to circumvent these, as
described in phrack's magazine <url name="issue 58"
id="http://packetstorm.linuxsecurity.com/mag/phrack/phrack58.tar.gz">
or in CORE's Advisory
<url id="http://online.securityfocus.com/archive/1/269246"
name="Multiple vulnerabilities in stack smashing protection technologies">.

<p>If you want to test out your buffer overflow protection once you
have implemented it (regardless of the method) you might want
to install the <package>paxtest</package> and run the tests it provides.

<sect1>Kernel patch protection for buffer overflows

<p>Kernel patches related to buffer overflows include the Openwall
patch provides protection against buffer overflows in 2.2 linux
kernels. For 2.4 or newer kernels, you need to use the Exec-shield
implementation, or the PaX implementation (provided in the 
grsecurity patch, <package>kernel-patch-2.4-grsecurity</package>,
and in the Adamantix patch, <package>kernel-patch-adamantix</package>).
For more information on using these patches read the the section <ref
id="kernel-patches">.

<sect1>Testing programs for overflows

<p>The use of tools to detect buffer overflows requires, in any case,
of programming experience in order to fix (and recompile) the
code. Debian provides, for example: <package>bfbtester</package> (a
buffer overflow tester that brute-forces binaries through command line
and environment overflows)<!-- FIXME: Where is it? and <package>njamd</package>-->. Other packages
of interest would also be <package>rats</package>, <package>pscan</package>,
<package>flawfinder</package> and <package>splint</package>.


<sect>Secure file transfers 

<p>During normal system administration one usually needs to transfer
files in and out from the installed system. Copying files in a secure
manner from a host to another can be achieved by using the
<package>ssh</package> server package. Another possibility is the use
of <package>ftpd-ssl</package>, a ftp server which uses the <em>Secure
Socket Layer</em> to encrypt the transmissions.

<p>Any of these methods need special clients. Debian does
provide client software, such as <prgn>scp</prgn> from the 
<package>ssh</package> package, which works like <prgn>rcp</prgn> but is
encrypted completely, so the <em>bad guys</em> cannot even find out WHAT you
copy. There is also a <package>ftp-ssl</package> package for
the equivalent server. You can find clients for these software even
for other operating systems (non-UNIX), <prgn>putty</prgn> and
<prgn>winscp</prgn> provide secure copy implementations for any
version of Microsoft's operating system.

<p>Note that using <prgn>scp</prgn> provides access to the users to
all the file system unless <prgn>chroot</prgn>'ed as described in <ref
id="ssh-chroot">. FTP access can be <prgn>chroot</prgn>'ed, probably easier
depending on you chosen daemon, as described in <ref
id="ftp-secure">. If you are worried about users browsing your local
files and want to have encrypted communication you can either use an
ftp daemon with SSL support or combine clear-text ftp and a VPN setup
(see <ref id="vpn">).

<sect>File system limits and control

<sect1>Using quotas

<p>
Having a good quota policy is important, as it keeps users from
filling up the hard disk(s).
<p>
You can use two different quota systems: user quota and group
quota. As you probably figured out, user quota limits the amount of
space a user can take up, group quota does the equivalent for
groups. Keep this in mind when you're working out quota sizes.

<p>There are a few important points to think about in setting up a
quota system:

<list>
<item>Keep the quotas small enough, so users do not eat up your disk
space.

<item>Keep the quotas big enough, so users do not complain or their mail quota
keeps them from accepting mail over a longer period.

<item>Use quotas on all user-writable areas, on <file>/home</file> as well 
as on <file>/tmp</file>.
</list>

<p>Every partition or directory to which users have full write access should
be quota enabled. Calculate and assign a workable quota size for those 
partitions and directories which combines usability and security.

<p>So, now you want to use quotas. First of all you need to check
whether you enabled quota support in your kernel. If not, you will
need to recompile it. After this, control whether the package 
<package>quota</package> is installed. If not you will need this one as well.

<!-- FIXME: How to check for quota support? What to tweak when recompiling? -->

<p>
Enabling quota for the respective file systems is as easy as modifying
the <tt>defaults</tt> setting to <tt>defaults,usrquota</tt> in your
<file>/etc/fstab</file> file. If you need group quota, substitute
<tt>usrquota</tt> to <tt>grpquota</tt>.  You can also use them both.
Then create empty quota.user and quota.group files in the roots of the
file systems you want to use quotas on (e.g.  <tt>touch
/home/quota.user /home/quota.group</tt> for a <file>/home</file> file system).

<p>
Restart <prgn>quota</prgn> by doing <tt>/etc/init.d/quota stop;/etc/init.d/quota
start</tt>. Now quota should be running, and quota sizes can be set.

<p>
Editing quotas for a specific user can be done by
<tt>edquota -u &lt;user&gt;</tt>. Group quotas can be modified with
<tt>edquota -g
&lt;group&gt;</tt>. Then set the soft and hard quota and/or inode quotas 
as needed.

<p>
For more information about quotas, read the quota man page, and the quota
mini-howto (<file>/usr/share/doc/HOWTO/en-html/mini/Quota.html</file>).
You may also want to look at <file>pam_limits.so</file>.

<sect1 id="ext2attr">The ext2 filesystem specific attributes (chattr/lsattr) 
<!-- section last edited by Frédéric Schütz <schutz@mathgen.ch> -->

<p>
In addition to the usual Unix permissions, the ext2 and ext3
filesystems offer a set of specific attributes that give you more
control over the files on your system. Unlike the basic permissions,
these attributes are not displayed by the usual <prgn>ls -l</prgn>
command or changed using <prgn>chmod</prgn>, and you need two other
utilities, <prgn>lsattr</prgn> and <prgn>chattr</prgn> (in package
<package>e2fsprogs</package>) to manage them. Note that this means
that these attributes will usually not be saved when you backup
your system, so if you change any of them, it may be worth
saving the successive <prgn>chattr</prgn> commands in a script so that
you can set them again later if you have to restore a backup.

<p>
Among all available attributes, the two that are most important for
increasing security are referenced by the letters 'i' and 'a', and
they can only be set (or removed) by the superuser:

<list>
<item>The 'i' attribute ('immutable'): a file with this attribute can
neither be modified nor deleted or renamed and no link can be created
to it, even by the superuser.

<item>The 'a' attribute ('append'): this attribute has the same effect
that the immutable attribute, except that you can still open the file
in append mode. This means that you can still add more content to it
but it is impossible to modify previous content. This attribute is
especially useful for the log files stored in <file>/var/log/</file>,
though you should consider that they get moved sometimes due to the
log rotation scripts.
</list>

<p>
These attributes can also be set for directories, in which case
everyone is denied the right to modify the contents of a directory
list (e.g. rename or remove a file, ...). When applied to a directory,
the append attribute only allows file creation.

<p>
It is easy to see how the 'a' attribute improves security, by giving
to programs that are not running as the superuser the ability to add
data to a file without modifying its previous content. On the other
hand, the 'i' attribute seems less interesting: after all, the
superuser can already use the basic Unix permissions to restrict
access to a file, and an intruder that would get access to the
superuser account could always use the <prgn>chattr</prgn> program to
remove the attribute. Such an intruder may first be confused when noticing not being able to remove a file, but you should not assume blindness - after all, the intruder got into your system! Some manuals
(including a previous version of this document) suggest to simply
remove the <prgn>chattr</prgn> and <prgn>lsattr</prgn> programs from
the system to increase security, but this kind of strategy, also known
as "security by obscurity", is to be absolutely avoided, since it
provides a false sense of security.

<p>
A secure way to solve this problem is to use the capabilities of the Linux
kernel, as described in <ref id="proactive">. The capability of
interest here is called <tt>CAP_LINUX_IMMUTABLE</tt>: if you remove it
from the capabilities bounding set (using for example the command
<tt>lcap CAP_LINUX_IMMUTABLE</tt>) it won't be possible to change any
'a' or 'i' attribute on your system anymore, even by the superuser ! A
complete strategy could be as follows:

<enumlist>
  <item> Set the attributes 'a' and 'i' on any file you want;
  <item> Add the command <tt>lcap CAP_LINUX_IMMUTABLE</tt> (as well as
         <tt>lcap CAP_SYS_MODULE</tt>, as suggested in <ref id="proactive">)
         to one of the startup scripts;
<!-- Is there anything interesting in :
http://lists.debian.org/debian-security/2001/debian-security-200107/msg00024.html -->
  <item> Set the 'i' attribute on this script and other startup files, as
         well as on the <prgn>lcap</prgn> binary itself;
  <item> Execute the above command manually (or reboot your system to
         make sure everything works as planned).
</enumlist>

<p>
Now that the capability has been removed from the system, an intruder
cannot change any attribute on the protected files, and thus cannot
change or remove the files. If the machine is forced to reboot (which
is the only way to restore the capabilities bounding set), it will
easily be detected, and the capability will be removed again as soon
as the system restarts anyway. The only way to change a protected file
would be to boot the system in single-user mode or using another
bootdisk, two operations that require physical access to the machine !

<!-- Add a note about the fact that it is not widely used -->

<sect1 id="check-integ">Checking file system integrity

<p>Are you sure <file>/bin/login</file> on your hard drive is still the binary 
you installed there some months ago? What if it is a hacked version, which
stores the entered password in a hidden file or mails it in clear-text version 
all over the Internet?

<p>
The only method to have some kind of protection is to check your files
every hour/day/month (I prefer daily) by comparing the actual and the
old md5sum of this file. Two files cannot have the same md5sum (the
MD5 digest is 128 bits, so the chance that two different files will
have the same md5sum is roughly one in 3.4e3803), so you're on the
safe site here, unless someone has also hacked the algorithm that
creates md5sums on that machine. This is, well, extremely difficult
and very unlikely. You really should consider this auditing of your
binaries as very important, since it is an easy way to recognize
changes at your binaries.

<p>Common tools used for this are 
<package>sxid</package>, <package>aide</package> (Advanced Intrusion Detection 
Environment), <package>tripwire</package>, 
<package>integrit</package> and <package>samhain</package>.
Installing <prgn>debsums</prgn> will also help you to check the file system
integrity, by comparing the md5sums of every file against the md5sums
used in the Debian package archive. But beware: those files can easily
be changed by an attacker and not all packages provide md5sums listings for 
the binaries they provided. For more information please read
<ref id="periodic-integrity"> and <ref id="snapshot">.

<p>You might want to use <prgn>locate</prgn> to
index the whole filesystem, if so, consider the implications of that.
The Debian <package>findutils</package> package contains
<prgn>locate</prgn> which runs as user 
nobody, and so it only indexes files which are visible to everybody.
However, if you change it's behaviour you will make all file locations
visible to all users. If you want to index all the filesystem
(not the bits that the user nobody can see) you can replace 
<prgn>locate</prgn> with the package <package>slocate</package>. 
slocate is labeled as a security enhanced version of GNU locate, but
it actually provides additional file-locating functionality.
When using <prgn>slocate</prgn>, the user only sees the actually accessible files and you can exclude any files or directories on the
system. The <package>slocate</package> package runs its update process with
higher privledges than locate, and indexes every file.  Users are
then able to quickly search for every file which they are
able to see.  <prgn>slocate</prgn> doesn't let them see new files;
it filters the output based on your UID. 

<p>You might want to use <package>bsign</package> or <package>elfsign</package>.
<package>elfsign</package> provides an utility to add a digital signature to
an ELF binary and a second utility to verify that signature. The current
implementation uses PKI to sign the checksum of the binary. The benefits of
doing this are that it enables one to determine if a binary has been
modified and who created it. <package>bsign</package> uses GPG,
<package>elfsign</package> uses PKI (X.509) certificates (OpenSSL).

<sect1>Setting up setuid check

<p>
The Debian <package>checksecurity</package> package
provides a <prgn>cron</prgn> job that runs daily in
<file>/etc/cron.daily/checksecurity</file>
<footnote>In previous releases, checksecurity was integrated into
cron and the file was <file>/etc/cron.daily/standard</file></footnote>.
This <prgn>cron</prgn> job will run the
<prgn>/usr/sbin/checksecurity</prgn> script that will store
information of this changes.

<p>The default behavior does not send this information to the superuser
but, instead keeps daily copies of the changes in
<file>/var/log/setuid.changes</file>. You should set the
MAILTO variable (in <file>/etc/checksecurity.conf</file>) to 'root' to
have this information mailed to the superuser. See <manref
name="checksecurity" section="8"> for more configuration info.

<sect id="network-secure">Securing network access

<p>FIXME: More (Debian-specific) content needed.

<sect1 id="kernel-conf">Configuring kernel network features

<p>Many features of the kernel can be modified while running by
echoing something into the <file>/proc</file> file system or by using
<prgn>sysctl</prgn>. By entering <tt>/sbin/sysctl -A</tt> you can see
what you can configure and what the options are, and it can be
modified running <tt>/sbin/sysctl -w variable=value</tt> (see <manref
section="8" name="sysctl">). Only in rare cases do you need to edit
something here, but you can increase security that way as well. For
example:

<!-- FIXME: Should the prefix on all of these be /proc/sys/? era -->

<example>
net/ipv4/icmp_echo_ignore_broadcasts = 1
</example>

<p>This is a <em>Windows emulator</em> because it acts like Windows on
broadcast ping if this option is set to 1. That is, ICMP echo requests
sent to the broadcast address will be ignored. Otherwise, it does
nothing.

<p>If you want to prevent you system from answering ICMP echo requests,
just enable this configuration option:

<example>
net/ipv4/icmp_echo_ignore_all = 1
</example>

<p>To log packets with impossible addresses (due to wrong routes) on your
network use:

<example>
/proc/sys/net/ipv4/conf/all/log_martians = 1
</example>

<p>For more information on what things can be done with
<file>/proc/sys/net/ipv4/*</file> read
<file>/usr/src/linux/Documentation/filesystems/proc.txt</file>. All
the options are described thoroughly under
<file>/usr/src/linux/Documentation/networking/ip-sysctl.txt</file>
<footnote>In Debian the <package>kernel-source-<var>version</var></package> packages
copy the sources to <file>/usr/src/kernel-source-<var>version</var>.tar.bz2</file>,
just substitute <var>version</var> to whatever kernel version sources you
have installed</footnote>.

<sect1 id="tcp-syncookies">Configuring syncookies


<p>This option is a double-edged sword. On the one hand it protects
your system against syn packet flooding; on the other hand it violates
defined standards (RFCs).

<!-- What does this mean? (jfs)
This option is quite dumb as it floods the
other side like it floods you, so the other side is also busy. 
-->

<example>
net/ipv4/tcp_syncookies = 1
</example>

<p>If you want to change this option each time the kernel is
working you need to change it in <tt>/etc/network/options</tt> by
setting <tt>syncookies=yes</tt>. This will take effect when ever
<tt>/etc/init.d/networking</tt> is run (which is typically done at boot time)
while the following will have a one-time effect until the reboot:

<example>
echo 1 > /proc/sys/net/ipv4/tcp_syncookies 
</example>

<p>This option will only be available if the kernel is compiled with
the <tt>CONFIG_SYNCOOKIES</tt>. All Debian kernels are compiled with
this option builtin but you can verify it running:

<example>
$ sysctl -A |grep syncookies
net/ipv4/tcp_syncookies = 1
</example>

<p>For more information  on TCP syncookies read
<url id="http://cr.yp.to/syncookies.html">.

<sect1 id="net-harden">Securing the network on boot-time

<p>When setting configuration options for the kernel networking you
need configure it so that it's loaded every time the system is
restarted. The following example enables many of the previous options
as well as other useful options.

<p>There are actually two ways to configure your network at boot
time. You can configure <file>/etc/sysctl.conf</file> (see: <manref
section="5" name="sysctl.conf">) or introduce a script that is called
when the interface is enabled. The first option will be applied to all
interfaces, whileas the second option allows you to configure this on
a per-interface basis.

<p>An example of a <file>/etc/sysctl.conf</file> configuration
that will secure some network options at the kernel level is shown below. Notice the comment in it, <file>/etc/network/options</file> might override some values if they contradict those in this file when the <file>/etc/init.d/networking</file> is run (which is later than <file>procps</file> on the startup sequence).

<example>
#
# /etc/sysctl.conf - Configuration file for setting system variables
# See sysctl.conf (5) for information. Also see the files under
# Documentation/sysctl/, Documentation/filesystems/proc.txt, and
# Documentation/networking/ip-sysctl.txt in the kernel sources 
# (/usr/src/kernel-$version if you have a kernel-package installed)
# for more information of the values that can be defined here.

#
# Be warned that /etc/init.d/procps is executed to set the following
# variables.  However, after that, /etc/init.d/networking sets some
# network options with builtin values.  These values may be overridden
# using /etc/network/options.
#
#kernel.domainname = example.com

# Additional settings - adapted from the script contributed
# by Dariusz Puchala (see below)
# Ignore ICMP broadcasts
net/ipv4/icmp_echo_ignore_broadcasts = 1
#
# Ignore bogus ICMP errors
net/ipv4/icmp_ignore_bogus_error_responses = 1
# 
# Do not accept ICMP redirects (prevent MITM attacks)
net/ipv4/conf/all/accept_redirects = 0
# _or_
# Accept ICMP redirects only for gateways listed in our default
# gateway list (enabled by default)
# net/ipv4/conf/all/secure_redirects = 1
#
# Do not send ICMP redirects (we are not a router)
net/ipv4/conf/all/send_redirects = 0
#
# Do not forward IP packets (we are not a router)
# Note: Make sure that /etc/network/options has 'ip_forward=no'
net/ipv4/conf/all/forwarding = 0
#
# Enable TCP Syn Cookies
# Note: Make sure that /etc/network/options has 'syncookies=yes'
net/ipv4/tcp_syncookies = 1
#
# Log Martian Packets
net/ipv4/conf/all/log_martians = 1
#
# Turn on Source Address Verification in all interfaces to
# prevent some spoofing attacks
# Note: Make sure that /etc/network/options has 'spoofprotect=yes'
net/ipv4/conf/all/rp_filter = 1
#
# Do not accept IP source route packets (we are not a router)
net/ipv4/conf/all/accept_source_route = 0
</example>

<p>To use the script you need to first create the script, for
example, in <file>/etc/network/interface-secure</file> (the name is
given as an example) and call it from
<file>/etc/network/interfaces</file> like this:

<example>
auto eth0
iface eth0 inet static
        address xxx.xxx.xxx.xxx
        netmask 255.255.255.xxx
        broadcast xxx.xxx.xxx.xxx
        gateway xxx.xxx.xxx.xxx
        pre-up /etc/network/interface-secure
</example>

<p>In this example, before the interface eth0 is enabled the script
will be called to secure all network interfaces as shown below.

<example>
#!/bin/sh -e
# Script-name: /etc/network/interface-secure
#
# Modifies some default behavior in order to secure against 
# some TCP/IP spoofing & attacks for all interfaces.
#
# Contributed by Dariusz Puchalak.
#
echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts 
                                           # Broadcast echo protection enabled.
echo 0 > /proc/sys/net/ipv4/conf/all/forwarding
                                           # IP forwarding disabled.
echo 1 > /proc/sys/net/ipv4/tcp_syncookies # TCP syn cookies protection enabled.
echo 1 >/proc/sys/net/ipv4/conf/all/log_martians # Log strange packets.
# (this includes spoofed packets, source routed packets, redirect packets)
# but be careful with this on heavy loaded web servers.
echo 1 > /proc/sys/net/ipv4/icmp_ignore_bogus_error_responses 
                                           # Bad error message protection enabled.

# IP spoofing protection.
echo 1 > /proc/sys/net/ipv4/conf/all/rp_filter

# Disable ICMP redirect acceptance.
echo 0 > /proc/sys/net/ipv4/conf/all/accept_redirects
echo 0 > /proc/sys/net/ipv4/conf/all/send_redirects

# Disable source routed packets.
echo 0 > /proc/sys/net/ipv4/conf/all/accept_source_route

exit 0
</example>

<p>Notice that you can actually have per-interface scripts that will
enable different network options for different interfaces (if you have
more than one), just change the pre-up line to:

<example>
pre-up /etc/network/interface-secure $IFACE
</example>

<p>And use a script which will only apply changes to a specific
interface, not to all of the interfaces available. Notice that some
networking options can only be enabled globally, however. A sample
script is this one:

<example>
#!/bin/sh -e
# Script-name: /etc/network/interface-secure
#
# Modifies some default behavior in order to secure against 
# some TCP/IP spoofing & attacks for a given interface.
#
# Contributed by Dariusz Puchalak.
#

IFACE=$1
if [ -z "$IFACE" ] ; then
   echo "$0: Must give an interface name as argument!"
   echo "Usage: $0 &lt;interface&gt;"
   exit 1
fi

if [ ! -e /proc/sys/net/ipv4/conf/$IFACE/ ]; then
   echo "$0: Interface $IFACE does not exit (cannot find /proc/sys/net/ipv4/conf/)"
   exit 1
fi

echo 0 > /proc/sys/net/ipv4/conf/$IFACE/forwarding  # IP forwarding disabled.
echo 1 >/proc/sys/net/ipv4/conf/$IFACE/log_martians # Log strange packets.
# (this includes spoofed packets, source routed packets, redirect packets)
# but be careful with this on heavy loaded web servers.

# IP spoofing protection.
echo 1 > /proc/sys/net/ipv4/conf/$IFACE/rp_filter

# Disable ICMP redirect acceptance.
echo 0 > /proc/sys/net/ipv4/conf/$IFACE/accept_redirects
echo 0 > /proc/sys/net/ipv4/conf/$IFACE/send_redirects

# Disable source routed packets.
echo 0 > /proc/sys/net/ipv4/conf/$IFACE/accept_source_route

exit 0
</example>


<p>An alternative solution is to create an <tt>init.d</tt> script and
have it run on bootup (using <prgn>update-rc.d</prgn> to create the
appropriate <tt>rc.d</tt> links).

<sect1 id="kernel-fw">Configuring firewall features 

<p>In order to have firewall capabilities, either to protect the local
system or others <em>behind</em> it, the kernel needs to be compiled
with firewall capabilities. The standard Debian 2.2 kernel (Linux 2.2)
provides the packet filter <prgn>ipchains</prgn> firewall, Debian 3.0
standard kernel (Linux 2.4) provides the <em>stateful</em> packet
filter <prgn>iptables</prgn> (netfilter) firewall.

<p>In any case, it is pretty easy to use a kernel different from the
one provided by Debian. You can find pre-compiled kernels as packages
you can easily install in the Debian system. You can also download the
kernel sources using the <package>kernel-source-<var>X</var></package> and build
custom kernel packages using <prgn>make-kpkg</prgn> from the
<package>kernel-package</package> package.

<p>Setting up firewalls in Debian is discussed more thoroughly in <ref
id="firewall-setup">.


<sect1 id="limit-bindaddr">Disabling weak-end hosts issues

<!-- FIXME I read this and I dont get what's the point? -->

<p>Systems with more than one interface on different networks
can have services configured so that they will bind only to 
a given IP address. This usually prevents access to services when requested
through any other address. However, this does not mean (although
it is a common misconception) that the service is
bound to a given <em>hardware</em> address (interface card).
<footnote>
To reproduce this (example provided by Felix von Leitner on the
Bugtraq mailing list):
<example>
   host a (eth0 connected to eth0 of host b):
     ifconfig eth0 10.0.0.1
     ifconfig eth1 23.0.0.1
     tcpserver -RHl localhost 23.0.0.1 8000 echo fnord

   host b:
     ifconfig eth0 10.0.0.2
     route add 23.0.0.1 gw 10.0.0.1
     telnet 23.0.0.1 8000
</example>
<p>It seems, however, not to work with services bound to
127.0.0.1, you might need to write the tests using raw sockets.</p>
</footnote>

<p>This is not an ARP issue and it's not an RFC violation (it's 
called <em>weak end host</em> in 
<url id="ftp://ftp.isi.edu/in-notes/rfc1122.txt" name="RFC1122">, 
section 3.3.4.2). 
Remember, IP addresses have nothing to do with physical interfaces.

<p>On 2.2 (and previous) kernels this can be fixed with:
<example>
# echo 1 > /proc/sys/net/ipv4/conf/all/hidden
# echo 1 > /proc/sys/net/ipv4/conf/eth0/hidden
# echo 1 > /proc/sys/net/ipv4/conf/eth1/hidden
.....
</example>
<p>On later kernels this can be fixed either with:
<list>
<item>iptables rules.
<item>properly configured routing.
<footnote>
The fact that this behavior can be changed through routing
was described by Matthew G. Marsh in the Bugtraq thread:
<example>
eth0 = 1.1.1.1/24
eth1 = 2.2.2.2/24

ip rule add from 1.1.1.1/32 dev lo table 1 prio 15000
ip rule add from 2.2.2.2/32 dev lo table 2 prio 16000

ip route add default dev eth0 table 1
ip route add default dev eth1 table 2
</example>
</footnote>
<item>kernel patching.
<footnote>
There are some patches available for this behavior as
described in Bugtraq's thread at
<url id="http://www.linuxvirtualserver.org/~julian/#hidden">
and <url id="http://www.fefe.de/linux-eth-forwarding.diff">.
</footnote>
</list>
<p>Along this text there will be many occasions in which it
is shown how to configure some services (sshd server, apache, printer
service...) in order to have them listening on any given
address, the reader should take into account that, without 
the fixes given here, the fix would not prevent accesses from 
within the same (local) network.
<footnote>
An attacker might have many problems pulling the access through
after configuring the IP-address binding while not being on the same
broadcast domain (same network) as the attacked host. If the attack
goes through a router it might be quite difficult for the answers
to return somewhere.
</footnote>

<p>FIXME: Comments on Bugtraq indicate there is a Linux
specific method to bind to a given interface.

<p>FIXME: Submit a bug against netbase so that the routing fix
is standard behavior in Debian?

<sect1>Protecting against ARP attacks

<p>When you don't trust the other boxes on your LAN (which should
always be the case, because it's the safest attitude) you should
protect yourself from the various existing ARP attacks.

<p>As you know the ARP protocol is used to link IP addresses to MAC
addresses (see <url name="RFC826"
id="ftp://ftp.isi.edu/in-notes/rfc826.txt"> for all the
details). Every time you send a packet to an IP address an ARP
resolution is done (first by looking into the local ARP cache then if
the IP isn't present in the cache by broadcasting an ARP query) to
find the target's hardware address.  All the ARP attacks aim to fool
your box into thinking that box B's IP address is associated to the
intruder's box's MAC address; Then every packet that you want to send
to the IP associated to box B will be send to the intruder's box...

<p>
Those attacks (ARP cache poisoning, ARP spoofing...) allow the attacker
to sniff the traffic even on switched networks, to easily hijack
connections, to disconnect any host from the network... ARP attacks
are powerful and simple to implement, and several tools exists, such as
<prgn>arpspoof</prgn> from the <package>dsniff</package> package or
<url name="arpoison" id="http://arpoison.sourceforge.net/">.

<p>However, there is always a solution:

<list>

<item>Use a static ARP cache. You can set up "static" entries in your
ARP cache with:

<example>
  arp -s host_name hdwr_addr 
</example> 

<p>By setting static entries for each important host in your network
you ensure that nobody will create/modify a (fake) entry for these
hosts (static entries don't expire and can't be modified) and spoofed
ARP replies will be ignored.


<item>Detect suspicious ARP traffic. You can use
<package>arpwatch</package>, <package>karpski</package> or more
general IDS that can also detect suspicious ARP traffic
(<package>snort</package>, <url name="prelude"
id="http://www.prelude-ids.org">...).

<item>Implement IP traffic filtering validating the MAC address.
</list>


<sect id="snapshot">Taking a snapshot of the system

<p>Before putting the system into production system you could take a
snapshot of the whole system. This snapshot could be used in the event
of a compromise (see <ref id="after-compromise">). You should remake
this upgrade whenever the system is upgraded, especially if you upgrade
to a new Debian release.

<p>For this you can use a writable removable-media that can be set up
read-only, this could be a floppy disk (read protected after use), a
CD on a CD-ROM unit (you could use a rewritable CD-ROM so you could
even keep backups of md5sums in different dates), or a USB disk or MMC
card (if your system can access those and they can be write protected).

<p>The following script creates such a snapshot:

<example>
#!/bin/bash
/bin/mount /dev/fd0 /mnt/floppy
trap "/bin/umount /dev/fd0" 0 1 2 3 9 13 15
if [ ! -f /usr/bin/md5sum ] ; then
	echo "Cannot find md5sum. Aborting."
	exit 1
fi
/bin/cp /usr/bin/md5sum /mnt/floppy
echo "Calculating md5 database"
>/mnt/floppy/md5checksums.txt
for dir in /bin/ /sbin/ /usr/bin/ /usr/sbin/ /lib/ /usr/lib/
do
   find $dir -type f | xargs /usr/bin/md5sum >>/mnt/floppy/md5checksums-lib.txt
done
echo "post installation md5 database calculated"
if [ ! -f /usr/bin/sha1sum ] ; then
	echo "Cannot find sha1sum"
        echo "WARNING: Only md5 database will be stored"
else
	/bin/cp /usr/bin/sha1sum /mnt/floppy
	echo "Calculating SHA-1 database"
	>/mnt/floppy/sha1checksums.txt
	for dir in /bin/ /sbin/ /usr/bin/ /usr/sbin/ /lib/ /usr/lib/
	do
	   find $dir -type f | xargs /usr/bin/sha1sum >>/mnt/floppy/sha1checksums-lib.txt
	done
	echo "post installation sha1 database calculated"
fi
exit 0
</example>

<p>Note that the md5sum binary (and sha1sum, if available) is placed on the 
floppy drive so it can
be used later on to check the binaries of the system (just in case it
gets trojaned). However, if you want to make sure that you are running
a legitimate binary, you might want to either compile a static copy
of the md5sum binary and use that one (to prevent a trojaned libc library
from interfering with the binary) or to use the snapshot of md5sums only from 
a clean environment such as a rescue CD-ROM or a Live-CD (to prevent
a trojaned kernel from interfering). I cannot stress this enough:
if you are on a compromised system you cannot trust its output, see
<ref id="after-compromise">.

<p>The snapshot does not include the files under
<file>/var/lib/dpkg/info</file> which includes the MD5 hashes of
installed packages (in files ending with <file>.md5sums</file>). You
could copy this information along too, however you should notice:

<list>
<item>the md5sums files include the md5sum of all files 
provided by the Debian packages, not just system binaries.
As a consequence, that database is bigger (5 Mb versus
600 Kb in a Debian GNU/Linux system with a graphical system and around
2.5 Gb of software installed) and will not fit in small removable
media (like a single floppy disk, but would probably fit in a removable
USB memory).

<item>not all Debian packages provide md5sums for the files installed
since it is not (currently) mandated policy. Notice, however,
that you can generate the md5sums for all packages using 
<package>debsums</package> after you've finished the system installation:
<example>
# debsums --generate=missing,keep
</example>

</list>

<p>Once the snapshot is done you should make sure to set the medium
read-only. You can then store it for backup or place it in the drive
and use it to drive a <prgn>cron</prgn> check nightly comparing the original
md5sums against those on the snapshot.

<p>If you do not want to setup a manual check you can always use
any of the integrity systems available that will do this and more,
for more information please read <ref id="periodic-integrity">.

<sect>Other recommendations

<!-- TODO: Remove this? -->

<sect1>Do not use software depending on svgalib

<p>
SVGAlib is very nice for console lovers like me, but in the past it
has been proven several times that it is very insecure. Exploits
against <prgn>zgv</prgn> were released, and it was simple to become
root. Try to prevent using SVGAlib programs wherever possible.  

<!-- FIXME: Move this to policy section if there ever is one? -->

