÷ÅÒÓÉÑ ÄÌÑ ÐÅÞÁÔÉ

áÒÈÉ× ÄÏËÕÍÅÎÔÁÃÉÉ ÎÁ OpenNet.ru / òÁÚÄÅÌ "òÕËÏ×ÏÄÓÔ×Á ÐÏ FreeBSD ÎÁ ÁÎÇÌÉÊÓËÏÍ" (íÎÏÇÏÓÔÒÁÎÉÞÎÁÑ ×ÅÒÓÉÑ)

èÏÒÏÛÅÅ ÒÕËÏ×ÏÄÓÔ×Ï × 4 ÞÁÓÔÑÈ, × ËÏÔÏÒÏÍ ÓÏÂÒÁÎÙ ÎÁÉÂÏÌÅÅ ÐÏÌÅÚÎÙÅ Ó×ÅÄÅÎÉÑ ÐÏ ÎÁÓÔÒÏÊËÅ FreeBSD É ÒÅÛÅÎÉÉ ÚÁÄÁÞ ÓÉÓÔÅÍÎÏÇÏ ÁÄÍÉÎÉÓÔÒÉÒÏ×ÁÎÉÑ.

  • 1 - Services and Updating (original) - ÐÒÏ×ÅÒËÁ É ×ËÌÀÞÅÎÉÅ ÓÅÔÅ×ÙÈ ÓÅÒ×ÉÓÏ×, ÏÂÎÏ×ÌÅÎÉÅ FreeBSD É ÐÏÒÔÏ× ÐÏ CVSup;
  • 2 - System Security and User Management (original) - ÔÀÎÉÎÇ ÓÉÓÔÅÍÙ ÞÅÒÅÚ sysctl, ÒÁÂÏÔÁ Ó securelevel, Õ×ÅÌÉÞÅÎÉÅ ÂÅÚÏÐÁÓÎÏÓÔÉ, ÏÐÔÉÍÉÚÁÃÉÑ ÓÅÔÅ×ÏÊ ÐÏÄÓÉÓÔÅÍÙ, ÕÐÒÁ×ÌÅÎÉÅ ÁËËÁÕÎÔÁÍÉ ÐÏÌØÚÏ×ÁÔÅÌÅÊ, ÕÓÔÁÎÏ×ËÁ Ë×ÏÔ, chroot É jail;
  • 3 - Services and Firewalling (original) - ÎÁÓÔÒÏÊËÁ sshd, ×ÅÄÅÎÉÅ ÌÏÇÏ× ÞÅÒÅÚ syslogd, cron, ipfw É natd;
  • 4 - Tools and Security awareness (original

    Server FreeBSD Part 1 - Services and Updating

    Dec 04 2003, 10:25 (UTC+0) syncro writes: This paper results like many other papers on the Internet. In this article we wish to make a FreeBSD machine configured as well as possible to resist all kinds of threats. It is kind of a compilation of knowledge, which we need. Security is a process not a product; this is why we try in this document to approach a broad panel of subjects and uses. We will be basing this paper on the 4.x-Stable FreeBSD branch. This paper will also be split up into several sections, which will be posted throughout the next couple weeks. I'm also taking into consideration you are very familiar with the FreeBSD operating system.

    The topics we will be covering are in today’s paper are:

    1. Intro
    1.1. Services
    1.2. CVSup
    1.3. Updating your system


    1. Intro

    I'm hoping by now you have successfully installed FreeBSD correctly, and that you have arrived to a stable connection to the Internet. If you have not I suggest doing a search on on how to overcome your obstacles. In this chapter we will concentrate on the basic system configuration of FreeBSD, the first measures in which you will apply from a point of view of safety.


    1.1. Services

    Inetd service is super a daemon which makes it possible to launch several network services as well as part of their configuration like ftpd, smptd or telnetd. The file of configuration for inetd is preserved in /etc/inetd.conf. Here is an extract:

    ftp stream TCP nowait root/usr/libexec/ftpd ftpd - L
    # Shell stream TCP nowait root/usr/libexec/rshd rshd


    In general, one places a comment ('#') in front of the line on the services we do not wish to load. If we do not wish to run any of these services inetd may be disabled though your rc.conf. If you wish to disable inetd you also give up the option for TCP Wrappers used by default in FreeBSD. Normally our first step is to determine what services are listening on a port. There's 2 good ways to do this, by using either netstat or the sockstat utility, both part of the base FreeBSD installation.

    ($:~)=> netstat -a | grep 'listen'

    Active Internet connections (servers and established)
    Proto Recv-Q Send-Q Local Address           Foreign Address         State
    tcp4       0      0 *:ssh                   *:*                     LISTEN
    tcp4       0      0 *:ftp                   *:*                     LISTEN
    tcp4       0      0 *:smtp                  *:*                     LISTEN
    udp4       0      0 *:portmap               *:*                     LISTEN


    Or my personal favorite is the sockstat command

    ($:~)=> sockstat -46

    The -46 Tells sockstat to display open sockets on both IPv4 and IPv6 network stacks.

    As you see we probably do not want all of these services. But if your machine is going to become a waiter with multiple services, I recommend that you follow our solution. In short, all the network services you wish to use in the future will turn in the shape of a stand alone daemon, by doing it this way it lets the daemons increase safety but also simplifying the configuration and the speed of response of the services by eliminating the inetd service. To make sure that inetd does not launch on the next boot we add 1 simple line to our /etc/rc.conf file.

    ($:~)=> vi /etc/rc.conf

    inetd_enable="NO"

    If you wish to use the inetd service you would use a line similar to this:

    inetd_enable="YES"
    inetd_flags="-WW"

    With inetd set to YES it will be launched upon every boot up. The options -Ww tells inetd to carry out the capacity of filtering of the internal services and external TCP via TCP Wrappers, which we will not be using in the course of this article. So go ahead and set inetd_enable="NO" and comment out the inetd_flags line. Next we also want to disable the portmapper service. Portmapper is an extremely practical tool within the framework of services such as RPC and NFS. But it also presents a incalculable number of vulnerabilities. So while still inside the rc.conf file we add the following line:

    portmap_enable="NO"

    Now we should probably kill the current inetd service running. By adding the line to the rc.conf we tell the system that we don’t want to load it upon startups, but it does not tell it to kill the current running process.

    ($:~)=> killall inetd

    NOTE: It is very important to know that your rc.conf file is used to configure the programs or scripts and starting daemons upon startup of your system.


    1.2 CVSup

    One of the biggest strengths of FreeBSD is the ability to update the whole OS from source code; this makes updating the OS an easy task. It can save FreeBSD administrator a lot of time tracking down bug fixes and patches. Now there's a couple ways to get cvsup installed. And there's also 2 cvsup's depending which one you want. You have cvsup (this one has a gui for xwindows) or you have cvsup-without-gui (this is for a system w/ out xwindows) but for this article I’m going to use the no-gui one. One way you can install cvsup is with the packaging system. We will go into detail about the packaging system and ports tree later at a later time.

    ($:~)=> pkg_add -r cvsup-without-gui

    Now if the package system is not your cup of tea you can also use the ports tree. If you’ve never used the ports tree before this is what makes FreeBSD such a great operating system. So if you installed the ports collection you can

    ($:~)=> cd /usr/ports/net/cvsup-without-gui ; make install clean

    So now we go onto method 3 of how to install this.

    ($:~)=> /stand/sysinstall

    Welcome back to the installer app. Normally I try to stay away from automated things like this to do my bidding. But I’m not fully going to go into the packaging system yet.

  • Choose the 4th Option labeled Configure
  • Choose the 2nd Option labeled Packages
  • Choose the 1st Option labeled CD-ROM

    Now pop in your FreeBSD cd1 in the cd-rom and select your cd-rom from the menu

    Scroll on down to net and select cvsup, once your done installing cvsup we can continue to update our sources. You can also install from the FreeBSD ftp server instead of using the old outdated binaries from the cd-rom.

    Create configuration file for CVSup

    CVSup can update all the source code provided by FreeBSD or just download and update ones that the user specifies. A configuration file provided at run time controls all of these. I'm not going to go in-depth on cvsup if you want more information about it I suggest you read the handbook. Create a file in your /root directory called cvs-supfile. This file will contain the information required for updating our system.

    ($:~)=> vi /usr/local/etc/cvs-supfile

    The file contents should be similar as below:

    *default host=cvsup11.FreeBSD.org
    *default base=/usr
    *default prefix=/usr
    *default release=cvs
    *default delete use-rel-suffix
    *default compress

    src-all tag=RELENG_4_8
    ports-all tag=.
    doc-all tag=.


    Please remember to find your fastest cvsup server and change the release tags to the appropriate values. Now save and exit.

    Congratulations you have a cvs-supfile.

    Branch CVS Tags

    A revision tag refers to either a particular line of FreeBSD development, or a specific point in time. The first type are called ``branch tags'', the second type are called ``release tags''.

    Branch Tags:

    RELENG_5_1 - The release branch for FreeBSD-5.1, used only for security advisories and other seriously critical fixes.

    Other branch tags would be:
    RELENG_5_0, RELENG_4, RELENG_4_9, RELENG_4_8, RELENG_4_7, RELENG_4_6, RELENG_4_5, RELENG_4_4, RELENG_4_3, RELENG_3, RELENG_2_2, etc..

    Release Tags

    These tags correspond to the FreeBSD src/ tree (and ports/, doc/, and www/ trees) at a specific point in time, when a particular version of FreeBSD was released.

    RELENG_4_9_0_RELEASE - FreeBSD 4.9

    Other release tags would be:
    RELENG_5_1_0_RELEASE, RELENG_4_8_0_RELEASE, RELENG_5_0_0_RELEASE, RELENG_4_7_0_RELEASE, RELENG_4_6_2_RELEASE,

    RELENG_4_6_1_RELEASE, etc.

    Refusing Ports and souces and docs.

    The refuse file essentially tells CVSup that it should not take every single file from a collection; in other words, it tells

    the client to refuse certain files from the server. The refuse file can be found (or, if you do not yet have one, should be placed) in base/sup/. Base is defined in your supfile; by default, base is /usr/local/etc/cvsup, which means that by default the refuse file is /usr/local/etc/cvsup/sup/refuse. So if you used the cvsup above the refuse file should be held in /usr/sup/refuse. The refuse file has a very simple format; it simply contains the names of files or directories that you do not wish to download. For example, if you cannot speak any languages other than English and some German, and you do not feel the need to use the German applications (or applications for any other languages, except for English), you can put the following in your

    refuse file:

    ports/chinese
    ports/french
    ports/german
    ports/hebrew
    ports/hungarian
    ports/japanese
    ports/korean
    ports/polish
    ports/portuguese
    ports/russian
    ports/ukrainian
    ports/vietnamese
    doc/da_*
    doc/de_*
    doc/el_*
    doc/es_*
    doc/fr_*
    doc/it_*
    doc/ja_*
    doc/nl_*
    doc/no_*
    doc/pl_*
    doc/pt_*
    doc/ru_*
    doc/sr_*
    doc/zh_*

    Next we want to make the updating process eay by putting a couple options in the /etc/make.conf

    ($:~)=> vi /etc/make.conf


    INSTALL=install -C -S -s

    PPP_NOSUID=        true
    ENABLE_SUID_SSH=    true
    ENABLE_SUID_NEWGRP=    true

    NO_FORTRAN=    true    # do not build g77 and related libraries
    NO_I4B=        true    # do not build isdn4bsd package
    NO_IPFILTER=    true    # do not build IP Filter package
    NO_KERBEROS=    true    # do not build and install Kerberos 5 (KTH Heimdal)
    NO_OBJC=    true    # do not build Objective C support
    NO_SENDMAIL=    true    # do not build sendmail and related programs
    NOGAMES=    true    # do not build games (games/ subdir)

    COMPAT1X=    no
    COMPAT20=    yes
    COMPAT21=    yes
    COMPAT22=    yes
    COMPAT3X=    yes

    MAKE_RSAINTL=    yes        # RSA (public key exchange)
    USA_RESIDENT=    yes

    SUP_UPDATE=    yes
    SUP=        /usr/local/bin/cvsup
    SUPFLAGS=    -g -L 2
    SUPFILE=    /usr/local/etc/cvs-supfile


    You may also refer to /etc/default/make.conf for other options you may wish to pass. Now with those variables in place lets test it out and update our sources and ports tree.

    ($:~)=> cd /usr/src && make update

    1.3. Updating your system

    We harness ourselves now with the configuration and the compilation of the kernel. For the later configurations and optimal performances, we recommend to you to select the following options in your file of configuration kernel located in the repertory /sys/i386/conf. In order to always be able to retrogress with a functional configuration, we will publish a copy of GENERIC, from which we will compile.

    ($:~)=> cd /usr/src/sys/i386/conf
    ($:~)=> cp GENERIC NEWKERN
    ($:~)=> vi NEWKERN

    Here are some good options to add into the kernel we will be building:


    options     INET
    options     INET6
    options     IPSEC
    options     IPSEC_ESP

    options     IPFIREWALL
    options     IPFIREWALL_VERBOSE
    options     IPFIREWALL_VERBOSE_LIMIT=30
    options     IPFIREWALL_FORWARD
    options     IPSTEALTH
    options     BRIDGE
    options     IPDIVERT
    options     DUMMYNET
    #options    IPFIREWALL_DEFAULT_TO_ACCEPT
    options     ACCEPT_FILTER_DATA
    options     ACCEPT_FILTER_HTTP

    options     NETGRAPH
    options     NETGRAPH_ONE2MANY
    options     NETGRAPH_PPPOE
    options     NETGRAPH_HOLE
    options     NETGRAPH_ECHO
    options     NETGRAPH_TEE
    options     NETGRAPH_TTY
    options     NETGRAPH_ASYNC
    options     NETGRAPH_INTERFACE

    options     TCP_DROP_SYNFIN
    options     ICMP_BANDLIM
    options     RANDOM_IP_ID
    options     SC_DISABLE_DDBKEY
    options     SC_DISABLE_REBOOT
    options     SC_NO_HISTORY
    options     NO_LKM
    options     NO_KLD

    options     QUOTA
    options     SOFTUPDATES
    options     UFS_DIRHASH
    options     COMPAT_LINUX
    options     DDB
    options     DEVICE_POLLING

    maxusers    0
    options     HZ=1000
    options     NMBCLUSTERS=32768

    pseudo-device    snp    4
    # high because of Nessus
    pseudo-device    bpf    20
    # high because of IPSec
    pseudo-device    gif    10
    pseudo-device    faith    1
    pseudo-device    stf    1


    In the order listed above we are selecting support for IPv6, IPv6, IPSEC and ESP. Then we activate the support for IPFW (Which you can decide if you wish to use IPFilter or PF instead) with the sending of messages to syslog limited to 30 times for the same event. Forwarding is also activated as well as the hidden forwarding (passing a package without decreasing it's TTL), just like the diver sockets making it possible to modify the transit of a package in the kernel. And finally support of dummynet, the basic traffic shaper of the system. we activate then accept the filters which accelerates the process of admission of certain types of connections (like HTTP) by placing them directly in the kernel.

    After that, we activate the troop of nodes of the NetGraph subsystem which allows complex handling the network level using nodes inheriting the characteristics of their type (hooks possible, treatment of the traffic to each hook, interpretation of the messages of control...) which can be chained through hooks to constitute a continuation of edges: a graph. More information and descriptions of the nodes in the manpage netgraph(4).

    We connect with some safety measures network, initially, like the rejection of certain forged packages (SYN/FIN) allowing the OS recognition, the limitation, via sysctl, of emission of packages ICMP in order not to be used as reflector at the time of a Back, and the random generation of IP ID to reduce the scanning appropriateness’s. Then physical safety with the deactivation of the sequences keyboard of debugging and restarting, as well as the deactivation of the back scrolling for the virtual terminals. Lastly, safety system with the deactivation of the LKM; and even of the KLD if you apply the patch according to .http://people.freebsd.org/~cjc/kld_stable.patch.

    Following the activation of the disc quotas, code of Linux compatibility via the emulation of certain system calls and the debugger kernel DDB. We check also the activation of SoftUpdates, method of writing and asynchronous reading solving the problems involved in the metadata and to their loss. The approach of Linux is the journalizing (concept inherited the data base), which consists in writing the updates of metadata with their dependences in a part distinct from the filing system: the newspaper. When the metadata is ready, they are actually written. The filing system of FreeBSD named UFS uses an approach different (inspired by CVS) in which the operations from writing or reading are placed in a queue divided into a buffer of waiting and a buffer of checking of the dependences. If a block belongs to a loop of dependences, it is rejected into the buffer of waiting. This approach will allow moreover in the future of the restarting following a crash with an fsck functioning in background task. Always on the level system, you will appreciate the device polling allowing improving the performances kernel by limiting the interruptions and thus the context switch and the call to a manager of interruption.

    NOTE: finally that the numbers maximum of users is placed at 0 so that it is calculated at the time of the boot according to the physical memory available. These variables as well as the number of clusters of the filing system are used to calculate the allowance of unquestionable resources memory. The frequency of clock is then placed at 1000 Hz to increase the accuracy of the device polling (and also to limit the burst if you use ALTQ). Come finally the pseudo-devices snoop and bpf for the respective monitoring from the tty and the Ethernet screens, and GIF, faith and stf for the tunneling v6/v4.

    Certain options will be already present; we do nothing but check them. You can also safely to put in comment the support procfs and NFS, which can create possible vulnerabilities in the system. To examine the whole of the kernel options available, refer to file LINT in same the directory as GENERIC.

    By the sequence of following orders, we build successively kernel NEWKERN then install we it and finally let us protect by using the flags immutables while cleaning the system from the files generated by the install.

    ($:~)=> cd /usr/obj ; chflags -R noschg * ; rm -rf *
    ($:~)=> cd /usr/src
    ($:~)=> make cleandir ; make cleandir
    ($:~)=> make buildworld
    ($:~)=> make buildkernel KERNCONF=NEWKERN
    ($:~)=> make installkernel KERNCONF=NEWKERN
    ($:~)=> make installworld

    We apply a script mergemaster, very practical since it carries out a comparison between the old files of configuration and those by defect of the installation. All that in order to update the configuration of the new system and to avoid us starting again a tiresome work.

    ($:~)=> cd /usr/src/usr.sbin/mergemaster
    ($:~)=> ./mergemaster -s -v -w 150 -D /etc/
    ($:~)=> reboot

    Defer to the handbook in the event of problems:
    .http://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/makeworld.html.


    Server FreeBSD Part 2 - System Security and User Management

    Dec 04 2003, 21:35 (UTC+0) syncroThis is paper 2 of 4 of my server series. The first paper Server FreeBSD Part 1 - Services and Updating talked about basic updates of your system. Now we get a little more complex in a leadup twords the final paper. Thanks bork for letting me post this here. Also please excuse my grammer. My English is not too good.

    The topics we will be covering are in today’s paper are:

    2. System Tuning
    2.1. sysctl
    2.1.1. securelevel and chflags
    2.1.2. performance
    2.2. User management
    2.2.1. adduser / rmuser / chpass / watch
    2.2.2. Quotas and login.conf
    2.2.3. Jail
    2.3. File integrity


    2. System Tuning

    Now that our system is like new and one cannot update anything any more, it is time to start on some basic security and system policys. For that we initially will see what we can do by defect with the basic system in order to increase the safety of our system and to limit exposure to attacks.

    2.1. sysctl

    Sysctl is an extremely practical tool within FreeBSD since it will allow us of verify or to handle the state of the kernel. Information is stored and posted through a Management Information Base or MIB according to the same model as SNMP For example to post a list of the various variables of state kernel, it is enough for you to carry out simple

    ($:~)=> sysctl -a

    same manner that you would use a ls. Note: that you can limit the entry of the MIB if you just know it after the option in order to post only it. According to the principle of the MIB, you can reduce posting by limit a field of the MIB For example to post all the entries in connection with IP

    ($:~)=> sysctl net.inet.ip.*

    Also note that certain variables are not modifiable and that certain entries of the MIB are in the form of tables used on the occasion by PS, netsat or systat. Finally to obtain a list of the variables sysctl which you can modify, consult the page of handbook of sysctl.

    2.1.1. securelevel and chflags

    One of the functionalities of FreeBSD consists of the establishment of secure level within the system. There are thus 5 levels of security within FreeBSD which cannot be decreased without starting again init. They can however be increased by a process root via the MIB sysctl, and this same in the course of execution.

    To define the securelevel set up by init, modify the following lines in rc.conf:

    kern_securelevel_enable="YES"
    kern_securelevel="N"

    N represents the entirety here corresponding to the one of the 5 possible entrys. Replace it by the level which is appropriate to you. Then if you wish to raise it once your system initialized, modify the following entry sysctl:

    ($:~)=> sysctl -w kern.securelevel=N

    In addition to limitations registered in the code kernel, therefore unchangeable, suitable for each one of them, each level also defines the possible operations on files flags, attributes of files making it possible to improve the safety provided by the traditional UNIX permissions. Below, 5 levels and their limitations:

  • -1 which founds the insecure mode (0) in a permanent way. It is the default value.
  • 0 indicate the insecure mode in which the files flags ' immutable' and ' system suspend only' can be withdrawn and where one can carry out operations of read/write on all. with for only restriction the already founded rights, for example, in the fstab.
  • 1 indicates we are in secure mode in which the flags ' system immutable' and ' system suspend only' cannot be decontaminated. The access to /dev/mem and /dev/kmem is interdict in writing and the KLD cannot any more be charged or discharged.
  • 2 founds the highly secure mode which is strictly the same one as the secure mode with the difference close as the only operations from now on carried out on the discs are the assembly and demote changes.
  • 3 means the introduction of the network secure mode which is similar to the preceding level with in more impossibility of modifying the rules ipfw or the configuration of the traffic shaper based on ipfw dummynet.

    For a workstation, the use becomes problematic as of the securelevel 1. For example, XFree86 can require the access to /dev/mem whereas that is prohibited to him. The following levels are adapted to waiters, and the last is more particularly intended for a footbridge. Note the level 2, very restrictive, which forces the access of the discs in read-only. This level, even a waiter is likely to be seen disturbed by the securelevel, even more if it requires compilations or regular modifications of configuration. Note that the level protects very well from the majority of the backdoors based on modules kernel. It could however be judiciously to replace or add the option kernel NO_LKM.

    To parameterize the files flags on your files according to these levels, you will have to use the order chflags. The flags available are listed here after.

  • arch, only usable by root, transforms the archival file.
  • opaque, makes the file "opaque" to certain reading (useful against the reading by other applications) and modifiable only by the owner or the root.
  • nodump, makes it possible to prohibit a backup file via the utility dump. Modifiable only by the owner or the root.
  • sappnd, founds the flag system suspends-only only modifiable by the root in securelevel higher than 0. Suspends means that one can only add data and not to withdraw some.
  • schg place the flag system immutable which, as its name indicates it, is supposed to prevent any event. Modifiable by the root only in level 0.
  • sunlnk makes it possible to prohibit the removal of a file, knowing that this option can only by the root
  • uappnd, uchg and uunlnk are during respective of sappnd, schg and sunlnk. The difference lies in the fact that, in addition to the root, the owner of the file also has the right to modify the files flags.

    Syntax could for example be as follows:

    ($:~)=> chflags -RH schg /bin
    ($:~)=> chflags -RH schg /sbin
    ($:~)=> chflags -RH schg /usr/libexec
    ($:~)=> chflags -RH schg /usr/lib
    ($:~)=> chflags -RH schg /usr/share/lib
    ($:~)=> chflags -RH schg /boot
    ($:~)=> chflags -RH sappnd /var/log/*
    ($:~)=> chflags schg /kernel

    Note that by carrying out a man chflags, you will discover the few options - in particular recursivity - what proposes this order. To withdraw a file flag they are the same options with the prefix No such as nosappnd. The files flags are interessants to be placed on certain precise sensitive files or then straightforwardly on a repertory of which you wish ensure of the integrity and who will be seldom modified. In the example, R and H make it possible to follow the bonds symbolic systems and this recursivement, the order being applied to whole repertories the binary ones.

    Last detail which does not have great a deal to see with sysctl but which imports much in the management of the rights and the files. You have the leisure to modify the fstab in order to assemble your various partitions with certain options. Under FreeBSD, instead of creating only one single partition root /, the system creates simultaneously a partition /usr and /var. You can define in your fstab for the whole of your filing systems:

    -rights of writing with the option rw for read-Write, or ro for read-only.
    -rights of execution with the option noexec.
    -privileges granted with the option nosuid.

    ($:~)=> ee /etc/fstab


    #device     mountpoint    fs    options           dump    pass
    /dev/ad0s2b    none        swap    sw              0    0
    /dev/ad0s2a    /        ufs    rw              2    2
    /dev/ad0s2f    /usr        ufs    rw,nodev          2    2
    /dev/ad0s2c    /home        ufs    rw,nosuid,nodev,userquota 2    1
    /dev/ad0s2e    /var        ufs    rw,noexec,nosuid,nodev      2    2
    /dev/acd0c    /cdrom        cd9660    ro,noauto          0


    We limit here the execution in /var in order to prevent that an intruder tries to place the binary ones there and we limit the presence of binary suid or devices in the other major repertories.

    Note in the passing which the software updates that we set up in our configuration kernel do not activate via the fstab but thanks to the utility tunefs which modifies directly, and in manner persistent, the heading of the filing system. For activating these software updates indeed, follow the following line:

    ($:~)=> tunefs -n enable /usr
    ($:~)=> tunefs -n enable /home

    Then replace enable by sayable decontaminating this option.

    2.1.3. Performance

    Sysctl can also bring an invaluable help in the configuration system and network to us at ends of high performances. It thus will enable us to activate certain capacities network which supports perfectly the pile TCP/IP the BSD - which is that known as while certainly passing most stable, most powerful and most standard of the piles TCP/IP - but which are not activated by defect.

    The first interesting entry is the option log_in_vain which goes logger through a simple entry in the file of corresponding log of syslogd, any attempt at access to a service even if no service is with listening on the port of the attempt at access. This can allow us in a secured environment, combined preference with a tool for analysis of log such as logcheck or ASAX, report of the attempts at network mapping even if we have a minimum of services available and who more is a firewall. However I will point out 2 difficulties: first of all log_in_vain logist actually only packages with flags SYN, which is not enough for really detecting a scan. And in addition, in a "hot" environment like a machine being used as footbridge or a waiter within a DMZ, the use of log_in_vain can capture a quantity of log enough impressionante and able to occupy an analyst or an administrator without tools for analysis during weeks. But within a network of out and already secured or on a critical machine, this capacity of log can be interesting. To activate it, it is enough for you to seize

    ($:~)=> sysctl -w net.inet.tcp.log_in_vain=1
    ($:~)=> sysctl -w net.inet.udp.log_in_vain=1

    The following easy ways are interesting if your machine must be used as footbridge, of filter or load to balance for other machines. The following order makes it possible to you to activate forwarding IP and thus to transform our machine into gateway what will prove to be useful for the division of connection or the deployment of a jail. You can associate the entry fastforwarding to him which activates a system of mask of the roads leading to external addresses with the local area network. The interest is to circumvent in this manner the inspection by layer IP to obtain a direct passage of the screens between levels 2 of the interfaces of the footbridge. In the case of a end host, activate check_interface rather than forwarding in order to check that the packages arriving on an interface has an address IP corresponding to the interface.

    ($:~)=> sysctl -w net.inet.ip.forwarding=1
    ($:~)=> sysctl -w net.inet.fastforwarding=1
    ($:~)=> sysctl -w net.inet.ip.check_interface=1

    The following entries are particularly useful within the framework of a waiter which necessity a high availability or a great reliability. Indeed, we will bring to our machine the support extensions TCP for high performances. These extensions are decries in the RFC 1323 that I recommend to you to study. They consist of 3 extensions. The first is the field Window Scale which is a factor applied to the field Window Size and useful on the Broad Conceited person Network (LFN) in order to optimize the data flow on these large reseaux and to bring a better control by multiplying Window Size. We find then 2 options extremely useful in the case of use of load balancing by providing information to the algorithms of distribution of load. The Round-Trip Time Measurement (RTTM) and Protection Against Wrapper Sequence Numbers (PAWS) base all the 2 on the addition of an option of timestamp to segments TCP With simple checks of timestamp one can thus calculate time to go return between 2 ACK and thus to optimize flow or to modify the road. One can also prevent hijacking, overlapping and especially of the rejeu by carrying out a double checking on the number of sequence and the timestamp. These options come to be added following algorithms NewReno, evolution of the Reno pile, making it possible to detect and to correct a congestion in the network while exploiting the loss of packages, the times and the sizes of window TCP single the bemol is that these options function of course only between machines supporting them all the 2 in a similar way, but they do not seem to be very much used - note that the branch 4.x supports the RFC 1323 per defect since the release 4.4 - and finally you could risk disagreements vis-a-vis some firewalls or plugins of standardization of traffic if they do not recognize these options. However we decide to approach it in this article in order to facilitate its diffusion and let us apply we it to our system by asset of conscience! You will find then an entry recent which forces FreeBSD to calculate, for each connection TCP, the quantity of data in the course of transmission in the network (starting from the product delay*bw), in order to limit the sending of capable packages to involve a no relevant overload of the routers and/or switch’s present on the road. This configuration then brings closer the behavior FreeBSD of the continuation of algorithms TCP Vegas. We have then as to increase the sizes owing to lack of our buffers of sending and reception (as well for TCP as for UDP), which have a direct influence on field TCP window size. Because of possible influence of these values on the time, it is recommended to try out several values, while following for example the rule wnd = bw/8 * RTT For example, we voluntarily limited the size of the buffers for UDP which does not have a mechanism of detection and avoidance of congestion and is thus more sensitive there. We also allotted values different to the buffers from sending and reception for TCP, the speed of download being often higher than that of upload (think of the lines xDSL). To finish, the two last entries sysctl indicate not to generate packages with the option road source, nor of the accepters, this option IP facilitating the spoofing already evoked while making reassemble strictly packages IP by the way used with the outward journey.

    For all that, it is enough for you to carry out the following orders:

    ($:~)=> sysctl -w net.inet.tcp.rfc1323=1
    ($:~)=> sysctl -w net.inet.tcp.newreno=1
    ($:~)=> sysctl -w net.inet.tcp.inflight_enable=1
    ($:~)=> sysctl -w net.inet.tcp.inflight_min=6144
    ($:~)=> sysctl -w net.inet.tcp.sendspace=32768
    ($:~)=> sysctl -w net.inet.tcp.recvspace=65535
    ($:~)=> sysctl -w net.inet.udp.sendspace=32768
    ($:~)=> sysctl -w net.inet.udp.recvspace=32768
    ($:~)=> sysctl -w net.inet.udp.maxdgram=28672
    ($:~)=> sysctl -w net.inet.ip.sourceroute=0
    ($:~)=> sysctl -w net.inet.ip.accept_sourceroute=0

    Then, we activate the implementation of the RFC 1948 applying the recommendation of Steve Bellovin to the random generation of ISN according to the equation ISN = M + F(localhost, localport, remotehost, remoteport) where M is a timestamp. However, the safety of this recommendation rests primarily on the randomness of the secret key and the power of the algorithm of hashage. Indeed, the study of Michal Zalewski (http://razor.bindview.com/publish/papers/tcpseq.html), concerning the use of attractile strange at ends of construction of spoofing sets answering the problem of prediction of ISN TCP in a blind way, showed that with the freedom left by the recommendation only generate a secret key only with starting and with the re-use of the IPv4 addresses, it is possible for a waiter with length uptime that an attacker can create attractile strange enough broad to be ensured of a good rate of success by using same IP address source. In spite of the absence of mathematical demonstrations for this study, we activate the regeneration of secrecy with a 3600 seconds interval. Will know that the phase of regeneration breaks the mechanisms of recycling TIME_WAIT, allowing to purge before 240 second lawful connections TCP in the course of closing (state TIME_WAIT), thus allocating resources a little longer. On a purely personal basis I also wonder which manner project CBOSS reconciled the integration of the syncookies in FreeBSD starting from the release 4.5 with the respect of the RFC 1948. We point out finally the various entries relating to the mechanisms of syncookies and syncache strongly limiting the risks related to the SYN flood while improving normal operation.

    ($:~)=> sysctl -w net.inet.tcp.strict_rfc1948=1
    ($:~)=> sysctl -w net.inet.tcp.isn_reseed_interval=1800
    ($:~)=> sysctl -w net.inet.tcp.syncookies=1
    ($:~)=> sysctl -w net.inet.tcp.syncache.hashsize=512
    ($:~)=> sysctl -w net.inet.tcp.syncache.cachelimit=15359
    ($:~)=> sysctl -w net.inet.tcp.syncache.bucketlimit=30
    ($:~)=> sysctl -w net.inet.tcp.syncache.rexmtlimit=3

    We decide to us proteger face now has certain attempts at Back as well as various techniques of network mapping. Using the following lines, you will be able thus in particular to modify the value of TTL per defect, which can be used to identify OS, or to prohibit the answers to the driving ICMP mask reply with a possible cartography network, but also to the ICMP broadcast, very often source of smurf or Back by amplification, and to put the maximum limit of packages ICMP in response to 200 a second. For TCP, we activate the delayed acknowledgments, restreingnant the slope of the system to send ACK for each received segment. This makes it possible to avoid Silly Window Syndrome (SWS) which tends to reduce the window size and thus to ensure a better effectiveness (see RFC 813, 896 and 2581). We also activate the keepalive one, segments TCP allowing checking if a transmission TCP always really active and is not preserved in an artificial state (following a SYN flood or Naptha, for example). Then activation comes from the blackholes consisting in preventing your system from being scanned while not answering neither by a RST for TCP nor by an ICMP port unreachable for UDP the packages sent on a closed port and thus to transform your system into "black hole". The last line is applicable only on the final hosts since it induces the checking on each arrival of packages that its TO address corresponds at an address of the interface of reception.

    ($:~)=> sysctl -w net.inet.ip.ttl=128
    ($:~)=> sysctl -w net.inet.icmp.maskrepl=0
    ($:~)=> sysctl -w net.inet.icmp.bmcastecho=0
    ($:~)=> sysctl -w net.inet.icmp.icmplim=200
    ($:~)=> sysctl -w net.inet.tcp.delayed_ack=1
    ($:~)=> sysctl -w net.inet.tcp.always_keepalive=1
    ($:~)=> sysctl -w net.inet.tcp.blackhole=2
    ($:~)=> sysctl -w net.inet.udp.blackhole=1
    ($:~)=> sysctl -w net.inet.ip.check_interface=1

    Always in protections against the Backs but this time side resources rather than network. The following entries of the MIB go initially permettrent us to limit the number of processes per user and the files number (including file descriptor and IPC) which it can open. We increase also the size of the tail of connections of par with the maximum number of sockets (2 times the maximum of connection roughly). Just as the size maximum of the buffers for sockets (empirically 8 times size of { recv, send}space). Lastly, we also increase the maximum number of files. All these values appear high, but they are actually used only for the resource allocation.

    ($:~)=> sysctl -w kern.maxprocperuid=512
    ($:~)=> sysctl -w kern.maxfilesperproc=1024
    ($:~)=> sysctl -w kern.ipc.somaxconn=4096
    ($:~)=> sysctl -w kern.ipc.maxsockbuf=262144
    ($:~)=> sysctl -w kern.maxfiles=16384

    In addition we also have some easy ways in order to avoid the attempts at mask poisoning by accelerating the time of cooling of the table of routing and table ARP.

    ($:~)=> sysctl -w net.inet.ip.rtexpire=60
    ($:~)=> sysctl -w net.inet.ip.rtminexpire=10
    ($:~)=> sysctl -w net.link.ether.inet.max_age=1200

    Let us stop with some modifications related to the system to be modified:

    ($:~)=> sysctl -w vfs.vmiodirenable=1
    ($:~)=> sysctl -w kern.coredump=1
    ($:~)=> sysctl -w kern.corefile=%N.sexfault
    ($:~)=> sysctl -w kern.ps_showallprocs=0

    The first entry makes it possible to improve the treatment in particular on broad volumes of files. It relates to the UNIX files which will be hidden in the buffer hides rather than directly on the disc exploiting thus fully the virtual memory FreeBSD in addition already very powerful. Then we decide to activate the savecore application which makes it possible to preserve a trace of the core dump associated a kernel with an aim of study after a crash for example in order to in determiner the causes. Lastly, we make so that the users see only their own processes and that only the root can see the unit.

    Note that we also have some configurable functionality by means of the loader. If you have a disc IDE, the following order allows of active the mask in writing

    ($:~)=> loader set hw.ata.wc=1

    If you have discs IBM DPTA or DTLA, you can use in the place the entry hw.ata.tags but with your risks and dangers since it is still experimental. These modifications must be reflected on/boot/loader.conf. Same manner, the options sysctl which will want to find with each demarrage must be in the file/etc/sysctl.conf in the form ' entrée=parametre '.

    Below our sysctl.conf final.


    net.inet.tcp.rfc1323=1
    net.inet.tcp.newreno=1
    net.inet.tcp.inflight_enable=1
    net.inet.tcp.inflight_min=6144
    net.inet.tcp.sendspace=32768
    net.inet.tcp.recvspace=65535
    net.inet.tcp.log_in_vain=1
    net.inet.tcp.always_keepalive=1
    net.inet.tcp.blackhole=2
    net.inet.tcp.delayed_ack=1
    net.inet.tcp.strict_rfc1948=1
    net.inet.tcp.isn_reseed_interval=1800
    net.inet.tcp.syncookies=1
    net.inet.tcp.syncache.hashsize=512
    net.inet.tcp.syncache.cachelimit=15359
    net.inet.tcp.syncache.bucketlimit=30
    net.inet.tcp.syncache.rexmtlimit=3
    net.inet.icmp.maskrepl=0
    net.inet.icmp.bmcastecho=0
    net.inet.icmp.icmplim=300
    net.inet.udp.sendspace=32768
    net.inet.udp.recvspace=32768
    net.inet.udp.maxdgram=28672
    net.inet.udp.blackhole=1
    net.inet.udp.log_in_vain=1
    net.inet.ip.ttl=128
    net.inet.ip.forwarding=1 # ou check_interface=1
    net.inet.ip.sourceroute=0
    net.inet.ip.accept_sourceroute=0
    net.inet.ip.rtexpire=60
    net.inet.ip.rtminexpire=10
    net.link.ether.inet.max_age=1200
    vfs.vmiodirenable=1
    kern.coredump=1
    kern.corefile=%N.sexfault
    kern.ps_showallprocs=0
    kern.maxprocperuid=512
    kern.maxfilesperproc=1024
    kern.maxfiles=16384
    kern.ipc.somaxconn=4096
    kern.ipc.maxsockbuf=262144


    2.2. User Management

    In a system with multi users, each local or distant user must have a personal use allowing to converse the environment of each one in the state desire as well as a clearer management of the activity of the system. In margin of the traditional accounts user we strongly recommend creer to you several accounts known as ' systeme' intend has executer with a minimum of risk of compromising or exploitation of compromised account, the significant services network which you will desirez to set up. Among more interessant on which to apply this practice, one finds waiters DNS, the Web servers or waiters smtp and pop3/imap4. Note also the presence of the account nobody corresponding has the user system no privileged credits, but the more there are services which use nobody, the more this account acquires privileges.

    Note that the multiple chapters on sysctl, the configuration kernel, the management of the users or the installation of a jail, we think of being able to exempt to us of an additional chapter on the basic orders which are chroot, chmod and chown accompanied by a fast explanation on the privileges. Thus do not seek information on these orders in our columns.

    Note in addition that the use of the account root gold of the operations limitees of maintenance is strongly deconseille for reasons of safety. Each handling of the root can entrainer of the significant consequences for the integrite of the system or if the account is compromised, then all the machine passes under control of the intruder. In short, it is preferable to also constitute an account user pertaining him to the group wheel and having the capacity of executer orders in root by sudo which enables us to remain under an account user and to carry out specific operations necessitant of the rights root or to intervene in on other accounts if need be. For example we can publish the index of our Web server on the account www system by using the option - U which makes it possible to specify the user of which one wishes to endorse the rights

    ($:~)=> sudo -u eberkut vi ~eberkut/CNS/FreeBSD.txt

    Of course this freedom of handling can be dangerous this is why we have need to publish and configure/etc/sudoers in order to limit the accesses. The scheme of/etc/sudoers is as follows: you can define alias for one or more users, or one or more orders then you define the authorizations according to diagram WHO WHERE=WHAT.


    # options
    Defaults      syslog=auth, mail_no_user, lecture, insults,
                  syslog_badpri=alert, rootpw, passwd_timeout=3, authenticate
    Defaults:FULLTIMERS    !lecture

    # alias utilisateurs > root
    User_Alias     FULLTIMERS = eberkut
    User_Alias     PARTTIMERS = bindmaster,webmaster

    Run_alias    OP = root,named,www

    # alias commandes
    Cmnd_Alias    DEBUG = /usr/bin/mt,/usr/sbin/dump,/usr/sbin/restore,
                          /usr/sbin/dd,/usr/bin/gdb,/usr/bin/ktrace,
                          /usr/bin/kdump,/usr/bin/file,/usr/bin/truss,
                          /usr/bin/ldd,/usr/bin/objdump,/usr/bin/strings,
                          /usr/bin/nm,/usr/bin/size,/usr/bin/kill
    Cmnd_Alias    KILL = /usr/sbin/shutdown,/usr/sbin/halt,/usr/sbin/reboot
    Cmnd_Alias    SHELLS = /usr/bin/sh,/usr/bin/csh,/usr/local/bin/zsh,
                           /usr/bin/ssh,/usr/X11R6/bin/startx
    Cmnd_Alias    USER = /usr/bin/su,/usr/sbin/adduser, /usr/sbin/rmuser,
                         /usr/bin/chsh
    Cmnd_Alias    NET = /usr/sbin/ppp,/usr/sbin/ifconfig,/usr/sbin/ipfw
    Cmnd_Alias    DAEMON = /usr/sbin/named,/usr/local/apache,/usr/bin/sshd
    Cmnd_Alias    RIGHTS = /usr/sbin/chroot,/usr/sbin/jail,/usr/sbin/chown,
                           /usr/bin/chmod
    Cmnd_Alias    CDROM = /sbin/umount /cdrom, /sbin/mount_cd9660 /dev/acd0c /cdrom

    # directives
    root          ALL = (ALL) ALL
    FULLTIMERS    ALL = NOPASSWD: DEBUG, KILL, SHELLS, RIGHTS, USER, NET, DAEMON
    PARTTIMERS    ALL = DEBUG, NET, (OP) NOPASSWD: DAEMON
    ALL           ALL = NOPASSWD: CDROM


    Sudo is based on timestamp between the differences orders entered to ensure a minimum of security while placing a timeout. For updater your timestamp without executer of orders, you can type sudo - v and to kill it definitively, sudo - K.

    2.2.1. adduser / rmuser / chpass / watch

    adduser is a tool extremement useful which enables us to add new users in a very simple way. It allows in an operation of gerer the necessary whole of actions A the creation of a new account user. A simple order carries out a configuration not does not have an account this including the creation of the entrees necessary in/etc/passwd and/etc/group, the creation of the repertoire of the user and the copy of the files required by defect until A a notification of welcome.

    We owe creer first of all the file of configuration adduser by

    ($:~)=> adduser -s -config_create

    Then we lancons the creation of the user.

    ($:~)=> adduser -v
    Use option ``-silent'' if you don't want to see all warnings and questions.
    Check /etc/shells
    Check /etc/master.passwd
    Check /etc/group
    Enter your default shell: csh date no sh tcsh zsh [sh]: sh
    Your default shell is: sh -> /usr/local/bin/sh
    Enter your default HOME partition: [/home]:
    Copy dotfiles from: /usr/share/skel no [/usr/share/skel]:
    Send message from file: /etc/adduser.message no
    [/etc/adduser.message]: no
    Do not send message
    Use passwords (y/n) [y]: y

    Write your changes to /etc/adduser.conf? (y/n) [n]: y

    Ok, let's go.
    Don't worry about mistakes. I will give you the chance later to correct any
    input.
    Enter username [a-z0-9_-]: eberkut
    Enter full name []: eberkut
    Enter shell csh date no sh tcsh zsh [zsh]:
    Enter home directory (full path) [/home/eberkut]:
    Uid [1000]:
    Enter login class []: root
    Login group wheel [wheel]:
    Login group is ``eberkut''. Invite eberkut into other groups: guest no
    [no]:
    Enter password []:
    Enter password again []:

    Name: eberkut
    Password: ********
    Fullname: eberkut
    Uid: 1000
    Gid: 1000
    Class: root
    Groups: wheel
    HOME: /home/eberkut
    Shell: /usr/local/bin/zsh
    OK? (y/n) [y]: y
    Added user ``eberkut''
    Copy files from /usr/share/skel to /home/eberkut
    Add another user? (y/n) [y]: n
    Goodbye!

    Note that you can easily notice that we use add here to use for the premiere time since we needed creer the file of configuration then adduser has request to us his default values. Moreover for more simplicity we were in verbose mode (- v). In the future you will not have that information of the user has to enter and you will be able to carry out this operation in mode silent (- S).

    Adduser possede a program brother, rmuser, which will allow us symmetric manner has adduser, to remove in only one operation a user and all dependences that that supposes. Rmuser carries out thus the suppression of the entree user in the file of passwords, sound repertoire (in/home), of its mail on standby (in/var/mail), of its temporary files (in/tmp), and its entree in/etc/group even the suppression of the group if it becomes empty. But rmuser also erases the entrees of the user in the crontab or kill all the processes in progress pertaining has the user in question.

    ($:~)=> rmuser eberkut
    Matching password entry:
    eberkut:*:1000:1000::0:0:eberkut:/home/eberkut:/usr/local/bin/zsh
    Is this the entry you wish to remove? y
    Remove user's home directory (/home/eberkut)? y
    Updating password file, updating databases, done.
    Updating group file: trusted done.
    Removing user's incoming mail file /var/mail/jru: done.
    Removing files belonging to eberkut from /tmp: done.
    Removing files belonging to eberkut from /var/tmp: done.
    Removing files belonging to eberkut from /var/tmp/vi.recover: done.

    Lastly, chpass is another marvelous tool moreover enabling us to facilitate management user largely. He makes it possible to modify basic information of a user such as his password, his Shell or of more personal information. Only the root and the user he can modify information with chpass. Chpass functions in the same way as edquota, it be-A-statement which it will open an editor making it possible to modify our configuration.

    ($:~)=> chpass eberkut
    ($:~)=>Changing user database information for eberkut.
    Login: eberkut
    Password: ********
    Uid [#]: 1000
    Gid [# or name]: 1000
    Change [month day year]:
    Expire [month day year]:
    Class:
    Home directory: /home/eberkut
    Shell: /usr/local/bin/zsh
    Full Name: eberkut
    Office Location:
    Office Phone:
    Home Phone:
    Other information:

    When you wish to set up a service, in addition to making it function in stand alone like explaining previously, and if it requires certain rights, then to assign a specific user to him can allow to limit partially with additional mechanisms like jail or chroot the damage caused by an intrusion via this service. This remark is true also for BIND which with the good options remains root only a few moments or for Apache which turns in nobody - and its scripts also what can give vulnerabilities in the event of misconfiguration.

    Lastly, when a user comes to loguer and that you noticed his share an illegitimate or intrusive behavior, the options for the snoop device which we placed at the time of the configuration kernel will enable us to take position in order to observe and to even write on the tty of a user. For that we will use the tool watch. We create initially the periphériques ones

    ($:~)=> cd /dev
    ($:~)=> ./MAKEDEV snp0
    ($:~)=> ./MAKEDEV snp1
    ($:~)=> ./MAKEDEV snp2
    ($:~)=> ./MAKEDEV snp3

    Then we can launch watch. Before that we check the active users on the system in order to specify the tty device to be supervised. We place the option T to obtain a timestamp at the beginning of the observation, N to prevent the user from changing attached tty and the option W to allow to write within the supervised tty.

    ($:~)=> who
    ($:~)=> watch -tnW ttyp1

    2.2.2. quotas and limits

    The quotas are an option of FreeBSD which allowing you to limit the quantity of disk space or the number of files to which the right a user or all the users of the same group has, on a filing system given. In a system with multi users with accesses distant, this method prevents that only one user does not consume all the disk space.

    The quotas having to be active manually within the file of configuration of the kernel and thus necessitant a recompiling, we have recommends to you of verifier the presence of the option quotas like several others to the beginning of this text. Once this stage passee, you must activate once more the quotas manually this time within the file/etc/rc.conf. For that let us publish we it and let us add the line to it

    enable_quotas="YES"

    For an increased control, you also have a second option but which will launch a program - quotacheck - which can slow down the demarrage of your machine considerably. However safety preceding, we recommend to you to publish the line

    check_quotas="YES"

    You must finally publish the file/etc/fstab to bring into service the quotas filing system per filing system. It is there that you say if you want quotas of use of the discs by user, group or both, for each filing system.

    To bring into service quotas by user, add the option userquota to the zone of options of the entry of/etc/fstab for the filing system on which you want quotas. For example:

    /dev/ad0s1c    /home    ufs    rw,nosuid,userquota    2    2

    For quotas by user one uses userquota and for quotas by groups, one will use groupquota. To apply quotas at the same time has the user and with his group, one will combine the 2 orders precedents as we did for our file. It does not remain you any more but with redemarrer in order to activate the taking into account of quota and the generation of the files/etc/quota.user and/etc/quota/group.

    The quotas can be founded on a system according to several criteria. First of all in addition to being able to apply quotas by user and/or groups, you have the possibility of applying these limitations according to various formats either in terms of disk space, the blocks, or in term of files, the inodes. In addition, it is necessary to add degrees in the limitations: strict or flexible. The first follow the rules of quotas to the letter, but when a user reaches his quota, it can nothing any more add. The second degree of limitation offers to the user a time - valid during one week per defect - allowing him making it possible not not to be suddenly limited in its work by a too strict quota and to add or (especially) to withdraw files during this time. However if it did not return on a normal level once the run out time, the limitation becomes strict and it can nothing any more add until A what it goes down again below its limitations.

    To publish our quotas, we will use the order edquota which will open an editor (VI per defect):

    ($:~)=> edquota

    Quotas for user eberkut:
    /usr/home/eberkut: blocks in use: 0, limits (soft = 80, hard = 100)
               inodes in use: 0, limits (soft = 40, hard = 60)
    /usr/var: blocks in use: 0, limits (soft = 80, hard = 90)
              inodes in use: 0, limits (soft = 60, hard = 80)


    To be simplified the attribution of quotas, one can apply a prototype quota to a beach of uid by the intermediaire of the option - p of edquota once the quotas definis a premiere time

    ($:~)=> edquota -p eberkut 1000-10000

    The order quota can be utilize in order to know the quotas and the use of the disk space of a user and/or a group. As for the majority of the other orders relating to the user newses, only the root can go to consult the quotas of all accounts and all groups.

    ($:~)=> quota -u eberkut

    Finally "last goal not least", FreeBSD has a file called login.conf which enables us to define certain capacities and especially operational limit of resources. The classes of login.conf are generally divided into 3 types which must arise in a form similar to the entries sysctl, i.e. nom=valor which can always be in seconds for time and B, KB, mb, GB, Tb for the size. Note also some Boolean:

    O limits of resources
  • - cputime in seconds to limit time CPU (not percentage). Option - T of limits
  • - filesize to limit the size maximum of a file (overwrity by the quotas). Option - F of limits
  • - datasize, stacksize and coredumpsize on the same diagram for the data, the stack or the files of coredump. Options - D, - S and - C of limits
  • - operational limits of memory memoryuse, memorylocked. Options - m and - L
  • - a maximum number of processes maxproc. Option - U of limits
  • - a number of files opened by process openfiles. Option - N of limits
  • - sbzise for the size maximum of the socketbuffer. Option - B of limits

    O of the variables of environment
  • - Lang, to specify $LANG, the variable of language
  • - manpath, for the access path by defect to the manpages
  • - nologin is the access path to your file nologin posted right before finishing a session
  • - requirehome, true or false, make it possible to requerir a repertory home validates for loguer
  • - setenv, makes it possible to specify a list of variables of environment separated by commas
  • - Shell, makes it possible to specify Shell to carry out in the place that to specify in the file passwd
  • - term, determines the type of terminal
  • - umask specifies the value of the mask of creation of file (ex: 022 = 755)
  • - welcome definite the file containing the welcome message

    O the variables of authentification
  • - minpasswordlen definite the minimal length of a password
  • - passwd_format specifies the format of encryption for the passwords (of or md5)
  • - mixpasswordcase force the user to use capital letters or figures in its password
  • - times.allow and times.deny make it possible to specify a list of schedules during which the logins are authorized or prohibited
  • - ttys.allow and ttys.deny make it possible to specify a list of tty usable by this class
  • - passwd_format allows to specify the algorithm used for the storage of the password. By defect this field is with ' des' which is relatively weak. You can put it at ' md5 ' and more recently at ' blf' to use Blowfish.

    O limiting of accounts
  • - accounted, activates the accounting for the users of this class
  • - daytime definite the maximum time of login per day - expireperiod, makes it possible to determine a limit of expiry on behalf of the class then graceexpire makes it possible to leave a deferment just as gracetime for times of login
  • - host.accounted and host.exempt makes it possible to list the hosts since which the accounting is or not activated. In the same way for ttys.accounted and ttys.exempt for the tty
  • - idletime, definite the time of inactivity before an automatic logout
  • - passwordtime makes it possible to define a limit of expiry for the passwords
  • - sessiontime specifies the maximum time allocated by session - sessionlimit specifies the maximum number of concurrent sessions
  • - warnexpire, warnpassword and warntime make it possible to define one moment to warn the user before expiry of the account, the password or the time of login allocated

    Above our login.conf final.

    ($:~)=> ee /etc/login.conf


    default:
        :copyright=/etc/COPYRIGHT:
        :welcome=/etc/motd:
        :setenv=MAIL=/var/mail/$,BLOCKSIZE=K,FTP_PASSIVE_MODE=YES:
        :path=/sbin /bin /usr/sbin /usr/bin /usr/games
         /usr/local/sbin /usr/local/bin /usr/X11R6/bin ~/bin:
        :nologin=/var/run/nologin:
        :cputime=unlimited:
        :datasize=unlimited:
        :stacksize=unlimited:
        :memorylocked=unlimited:
        :memoryuse=unlimited:
        :filesize=unlimited:
        :coredumpsize=unlimited:
        :openfiles=unlimited:
        :maxproc=unlimited:
        :sbsize=1048576:
        :priority=0:
        :umask=022:
        :idletime=3600s:
        :minpasswordlen=8:
        :mixpasswordcase=true:
        :passwd_format=blf:
        :passwordtime=30d:
        :warnpasswordtime=2d:


    # the field Tc enables us to return a user or a group to a definite class
    #.  You can overwriter of the limits of default by adding them with
    # new classifies.  Adduser enables you to add a user to a class.

    staff:
        :tc=default
        :password_time=unlimited
        :cputime=1h30m:
        :filesize=unlimited:
        :datasize=20M:
        :stacksize=10M:
        :coredumpsize=10M:
        :memoryuse=30M:
        :memorylocked=10M:
        :maxproc=32:
        :openfiles=24:
        :requirehome@:


    We can use the order limits here in order to adjust these limits of resources for a class of user class_login defined in login.conf

    ($:~)=> limits -e -C classe_login -B -m 20m

    To apply your capabilities login.conf, we use cap_mkdb.

    ($:~)=> cap_mkdb /etc/login.conf

    2.2.3. jail

    Jail is a very powerful mechanism which, as its name indicates it, makes it possible to refine the privileges and the management of the users according to a principle, similar to chroot, of imprisonment of the processes. Jail goes however much further since it proposes the reproduction of a complete environment inside an environment relative. The function jail() is based on a reinforced version of chroot().

    To build a jail can prove very useful to confine a user or service to which one makes no confidence or which is likely to threaten the integrity and the stability of the system. For that jail offers completely operational virtual a FreeBSD environment with its own files of configuration or management of the users, the whole attached to alias a IP Moreover, one process once in the jail is as behind an ice without dye, it evolves/moves freely but cannot see beyond its environment while the host of the jail can all observe and supervise. Thus, a process in the jail cannot leave there, and you can delegate accounts root within each jail. On the assumption of an attack, the intruder will obtain for example initially a local access by a distant exploit, then an access root by a local exploit but would be seen confining with its jail (theoretically, jail being based on chroot(), nothing are sure).

    Jail is posed here in precursor of the more recent concept of honeypot, and can be used very well like such to encourage and supervise intrusions with a limited risk of total compromising of the machine, while preserving logs and information at the shelter. To preserve its integrity, jail restraint possible actions compared to a complete environment. It is thus prohibited to modify the kernel (which remains single for the whole of the system) and to charge of the modules kernel, to modify the configuration network, to assemble filing systems, to create devices, to use raw sockets, to modify the MIB sysctl or the securelevels. All that is not directly related to the operation of the jail is prohibited. We can however use as usual privileged ports, modifiers the permissions of the files and users inside the jail, etc in order to really cloner a traditional environment.

    The effective installation of a jail is carried out using the following sequence of orders:

    ($:~)=> ifconfig fxp0 alias $jail_IP_alias netmask 255.255.255.0
    ($:~)=> mkdir -p /jail/jailone
    ($:~)=> cd /usr/src
    ($:~)=> export JONE=/jail/jailone
    ($:~)=> make world DESTDIR=$JONE
    ($:~)=> cd /etc
    ($:~)=> make distribution DESTDIR=$JONE NO_MAKEDEV=yes
    ($:~)=> cd $JONE/dev
    ($:~)=> ./MAKEDEV jail
    ($:~)=> ln -sf null /boot/kernel/
    ($:~)=> touch ../etc/fstab

    We allot an address alias IP to our jail then we create the repertory/jail/jailone in which will be to confine our virtual environment. The order make then makes it possible to build a complete system with for destination the jailone, including binary, files of configuration and tree structure of the devices. Note at the end the bond symbolic system towards the kernel, as well as the creation of an fstab vacuum to ensure itself of the correct operation of certain programs.

    The jails are not yet persistent, it is thus necessary to configure your rc.conf principal to preserve the configuration ifconfig at each reboot:

    ifconfig_fxp0="alias $jail_IP_alias netmask 255.255.255.0"

    Then it will be necessary to copy the following line within rc.local to return the jail persistent between two restarting:

    ($:~)=> jail /jail/jailone/ $hostname $jail_IP_alias /bin/sh

    If you envisage using cron or syslog, we recommend to you to entirely recreate your file of configuration by adapting the entries to the jail.

    For the use of cron, we recommend to you to entirely recreate your file of configuration with your own entries. In addition all the files copied are it after complete configuration of the environment host, which means that these files were chmoded, thus think of making in the same way with crontab, httpd.conf and named.conf

    By using adduser and chpass as sight previously, we do not have any more but to change the password root of the jail, then to create a user by service which we wish to confine. We will take as named example and httpd. If you wish to authorize the access to your jail with preexistent users, it you will be supposed to copy spwd.db. For that we will recopy only information which interests us:

    ($:~)=> fgrep $username /etc/passwd > $JONE/etc/passwd
    ($:~)=> fgrep $username /etc/master.passwd > $JONE/etc/master.passwd
    ($:~)=> cd $JONE/etc/ && pwd_mkdb -d master.passwd

    For a securisation of the system, in margin of file of configuration useful that we already copied, you can use the functionalities of chmod, or even the chflags, to modify the permissions on the confined correspondents of the repertories/bin,/sbin,/usr/lib,/usr/share/lib in order to avoid any modification or compromising.

    We can also add with the sysctl.conf environment host certain variables concerning the jails. Note that now that we set up a jail, we will referring ourselves with the jail like the environment jail and the normal machine as with the environment host. The following entries sysctl make it possible to decide if the jail has the right to change its own domain name, to use IPC standards System V for the communication inter process enabling him to communicate and thus to deteriorate processes apart from the jail, and finally to limit or not the access to more types socket and not subjected to the restrictions jail:

    ($:~)=> sysctl -w jail.set_hostname_allowed=0
    ($:~)=> sysctl -w jail.socket_unixiproute_only=1
    ($:~)=> sysctl -w jail.sysvipc_allowed=0

    If you wish to configure a significant number of jail, as it will be the case if you to confine each service or site lodged indépendemment, for at the same time more safety and also to limit the size occupied by the jail, you can use pseudo-devices vn exploiting the driver vnode which makes it possible to treat a file like a device. When you decided maximum size by jail, use ' truncate' to create a file of this size (here 1 Go):

    ($:~)=> truncate 1G jailfile

    Then, for mounter these files like partitions on which to install your jail, use ' vnconfig' to transform the preceding file into a device (here vn0c). If no file is specified, vnconfig will use the swap to create the device. You will be able then to specify the size with the option - S followed by the size (in KB, Mo, go and to), and to fill it of it of zeros with - T, thus supplanting the use of truncate:

    ($:~)=> vnconfig -e vn0c jailfile

    or, to remove the recourse to truncate:

    ($:~)=> vnconfig -S 1g -T vn0c

    You can then assemble it and dismount as usual. You will have to insert these new peripherals in vote fstab in order to assemble them to starting as a partition jail (peripheric a vn by jail). The interest is the great flexibility since you can easily increase or reduce the size of the file used to emulate quotas. For retransformer your device vn in file, carry out:

    ($:~)=> vnconfig -u /dev/vn0c

    If you ridges to turn several services in your jails, it can happen that a fault of safety is discovered, requiring the patching of this service. Thanks to the virtualization of the jail, you could use NFS between this one and the environment host. There is however a simpler solution consisting in using mount_null which makes it possible to duplicate part of a filing system so that it is seen by a different way. As patcher and recompiler require the access to/usr/src, you preserve your safety while assembling this way in read-only from the point of view of the jail.

    ($:~)=> mount_null -o ro /usr/src $JONE/usr/src

    It does not remain you any more whereas to apply the patch and to recompiler normally your binary userland.

    To note all the same that it is recommended to use the user named since whom bind - which will be placed a few moments with the rights root to recover the files descriptor before returning to more reasonable privileges - will be used. With BIND it is also strongly recommended to use a key of authentification TSIG between your waiters DNS, to limit the AXFR or transfer of zone to sure waiters DNS secondary or to modify the response to the request host - L chaos version.bind which can give to the attacker information on the version of BIND and thus possible remote possible buffer overflow.

    If you use Apache as a httpd, do not forget to publish httpd.conf in order to specify as owner the www user in order not to have resorts to nobody which more it will be used, more it will gain drois. Also take care not to overload the system and, more particularly, not to reach too much facilemenent the number of maximum process per user (in such a case if the traffic is legitimate pass in root jail to adapt the parameter by sysctl).

    If you are anxious of an unspecified dependence with chroot(), and seek more precise capacities of configuration, you can turn to the reimplementation partial of Robert Watson: jailNG. This one provides several improvements as regards the configuration and the management of the jail. It is enough for you to recover the patch on http://www.watson.org/~robert/jailng/ and to apply it in the following way:

    ($:~)=> cd /usr/src && patch -p1 < jailng.1.diff

    It does not remain any more but with recompiler your kernel. The use is carried out then via ' jailctl' having 3 orders at the present time:

    - ' jailctl create' or ' destroy' which takes in argument the name of the jail and makes it possible to create or remove a jail
    - ' jailctl join fascinating in argument the name of the jail to be joined, the way to be confined with the option - C, and finally an order, such as the launching of Shell.

    The rights of each jail could be to manage more finely thanks to entries sysctl specific, form jail.jail_name.entry_name, for each one of them. These new entries are as follows:

    ($:~)=> sysctl jail.jail_name.set_hostname_permitted=0
    ($:~)=> sysctl jail.jail_name.sysvipc_permitted=1
    ($:~)=> sysctl jail.jail_name.socket_ipv4_permitted=1
    ($:~)=> sysctl jail.jail_name.socket_unix_permitted=1
    ($:~)=> sysctl jail.jail_name.socket_route_permitted=1
    ($:~)=> sysctl jail.jail_name.socket_other_permitted=0
    ($:~)=> sysctl jail.jail_name.ipv4addr=192.168.1.1

    The jails can - or not - thus modify their hostname, the processes in their centre can use the IPC SysV, sockets INET, the sockets UNIX, the sockets road, any other type of socket, and finally you can parameterize address IP of the jail.

    A small remark but of weight after this encensement: the jailNG project is already old and nowhere does not show any more any sign of activity for a long time. The code is thus likely to cause many problems, and the new functionalities are long in coming, undoubtedly since Robert Watson, from now on member of the core TEAM, is with the head of the solid mass TrustedBSD project, aiming at the implementation of the standard POSIX.1e starting from FreeBSD 5.x, and one of the instigator of the project CBOSS which chapeaute several open developments source in the field of safety. FreeBSD 5.0 has all the same some thin improvements like the configuration of securelevel independent for each jail.

    2.3. file integrity

    The preceding chapter approaching a kind of system in the system, it leaves a little the logical path and step by step this article. Thus do not forget to take account of the following easy ways in the configuration of your environments jail in addition to vote environment host. We are interested here in the integrity of the files and in particular by the permissions and privileges granted within the framework of the use or the management of certain files.

    A major danger of the safety of the files is represented by bits SUID. This bit placed on a file makes it possible to use it with the same rights as the owner of the file what can appear dangerous if the owner is the root. But first of all, we seek marked files SUID and SGID (similar to SUID but on a group scale) with find

    ($:~)=> find / -perm 02000 -o -perm 04000 print

    We obtain a list of all the file or repertoires with bit SUID or SGID. Among all celà, there are executables that we do not want inevitably to leave with the range of no matter whom or although we do not intend to use. The selection to be carried out among file SUID is left with your discretion according to your use. However, it is strongly recommended not to leave Shell procedures in SUID especially pertaining to the root, this possibly being able to involve the illegitimate execution of orders.

    To carry out our modifications, we use the utility chmod which enables us to modify the permissions allocated with a file. To calculate the modes which we wish to apply to such file, we base ourselves on the diagram of permissions according to:

    4000 bit SUID (SetUserID one execution) about which we already spoke
    2000 bit SGID (Set-Group-ID-one-execution) which we also approached
    1000 sticky bit, under freebsd this functions only on the repertories and makes it possible to the user to remove or re-elect only the files of which they are owners
    0400 allows the reading by owner
    0200 allows the writing by owner
    0100 allows the execution of a file by the owner and research within a repertoire
    0040 allows the reading by the members of the group
    0020 allows the writing by the members of the group
    0010 allows the execution of a file by the members of the group and seeks it within a repertoire
    0004 allows the reading by all other users 0002 allows the writing by all other users
    0001 allows the execution of a file by all the other users and research within a repertory

    When you make a ls, they are omnipresent the srwx-rwx-rwx. You will find more precise details on the permissions and the use of chmod by a man 1 chmod.

    We can first of all decide to limit the modifications made to some of our files of configuration. We thus allow the reading and the writing by the owner, the reading by the group and any right to the remainder of the users

    ($:~)=> chmod 600 /etc/fstab
    ($:~)=> chmod 600 /etc/rc.*
    ($:~)=> chmod 600 /etc/syslog.conf /etc/newsyslog.conf
    ($:~)=> chmod 600 /etc/ppp/ppp.conf
    ($:~)=> chmod 600 /etc/ssh/sshd_config
    ($:~)=> chmod 600 /etc/racoon.conf /etc/ipsec.conf
    ($:~)=> chmod 600 /etc/passwd
    ($:~)=> chmod -RH 640 /etc/nessus/

    Note that we can combine these operations with something of more drastic if we have a rather high securelevel. Thus, if you seldom recompilez or update you can also apply the order chflags studied higher to the repertories and files of your choice by taking guard to the later problems in the event of compilation or of configuration. Also profit are error messages of chmod to check your bits SUID/SGID and the déselectionner on the binary sensitive ones.

    We then will worry we about the integrity of our files and our system. For that we first of all will be used we as mtree. Mtree can be regarded as an inspector of integrity integrated system in the same style as ASSISTANCE or TripWire. It will enable us to generate a specification of our file system against which to compare our system regularly in order to detect possible illegitimate modifications. To generate our specification we enter the following order

    ($:~)=> mtree -s 31337 -K cksum -K sha1digest -K uname -x -c -p /your/path >
            /etc/mtree/file.spec


    The option S makes it possible to obtain a single checksum for all the files to which one applied the keyword ' cksum' and requires a figure in keyword (to be preserved at the shelter). The option K specifies a keyword to apply which will be stored in the specification and compared later knowing than by defect one has the keywords flags (for the files flags), gid (for the group), mode (for the permissions into octal), nlink (for the hardware link), size (for the size), link (for the bonds symbolic systems), time (for the last timestamp of modification), and uid (for the owner) to which we add cksum to obtain a checksum according to the diagram of the order cksum(1), sha1digest to obtain a signature using the agorithme with single direction Sha-1 to obtain the owner in the form of name. Then option X makes it possible not to jump the points of mountage, C makes it possible to leave information on the standard output and p specifies the way. What will give us in practice


    ($:~)=> mtree -s 31337 -K cksum -K sha1digest -K uname -x -c -p /bin >
            /etc/mtree/bin.spec
    ($:~)=> mtree -s 31337 -K cksum -K sha1digest -K uname -x -c -p /sbin >
            /etc/mtree/sbin.spec
    ($:~)=> mtree -s 31337 -K cksum -K sha1digest -K uname -x -c -p /usr/libexec
            > /etc/mtree/libexec.spec
    ($:~)=> mtree -s 31337 -K cksum -K sha1digest -K uname -x -c -p /usr/lib >
            /etc/mtree/lib.spec
    ($:~)=> mtree -s 31337 -K cksum -K sha1digest -K uname -x -c -p
            /usr/share/lib > /etc/mtree/sharelib.spec
    ($:~)=> mtree -s 31337 -K cksum -K sha1digest -K uname -x -c -p /boot >
            /etc/mtree/boot.spec


    Then to compare our specifications and to communicate the results with the root with a minimum of identation, we do not have any more but to carry out

    ($:~)=> mtree -x -i -f file.spec | mail -s 'mtree results' root

    A good idea is to launch the first orders once after each recompiling of the system and the checking once per week or as soon as you have a doubt about the integrity of your system. All that of course by the intermediaire of cron.

    You will be able to find several improvements dedicated to the use of mtree as a tool for checking of integrity - in particular its use via/etc/periodic/security - to .http://people.freebsd.org/~fanf/FreeBSD/.

    A last very useful tool that we will use to ensure us of the integrity of our system will be KSEC for Kernel Security Checker. KSEC does not make party of the official distribution FreeBSD and is not either in the ports. KSEC is the adaption with FreeBSD of the tool of safety Linux KSTAT (Kernel Security Therapy Anti Trolls) by s0ftpr0ject. To get one to you or the other, return to .http://www.s0ftpj.org/en/site.html. These tools function according to a highly paranoiac design of the system and thus decides to take their information only kernel by using bookshop KVM and by limiting the operations on the syscall ioctl(). It thus will use to us to detect the presence of backdoors in the system in their most frightening form, the modules kernel. KSEC is so thorough that it can be used to us as replacement with ifconfig for the reading. Indeed, by directly observing the structures ifnet or the files descriptor bpf, it can detect if an interface is or not in promiscuous revealing mode of a sniffer and to even provide information and statistics on the traffic or the state of the interfaces. These checks can be carried out through the following operations for the interface fxp0 -- to specify ' all' for all the interfaces available:

    ($:~)=> ksec -i fxp0

    But KSEC also will use to us to detect a deterioration of our integrity system by checking if the addresses indicated in our syscall table are indeed the same ones as announced by/dev/kmem. The modification of the syscall table is a very widespread method in the design of lkm backdoors but which becomes a little old and can be seen replacing by methods of hijacking syscall, pointers towards the syscall table or even of a patching of/dev/kmem to avoid this type of detection. It is on the latter point that the securelevel by preventing any modification of/dev/kmem is judicious. It can also carry out various operations of checking of integrity of the protocols or integrity of the files linkés between them. It any more but does not remain us to carry out a compilation of these options in order to obtain a full report of integrity system

    ($:~)=> ksec -i interface -b -k -p

    In addition we recommend to you to test in case of doubts following mtree reports/ratios and ksec, to carry out an ultimate checking using chkrootkit which him is based primarily on known signatures announcing of the trojanized files but also provides a small series of tests in a style similar to KSEC but less kernel-dependant. See http://www.chkrootkit.org and the ports security for more information.

    Server FreeBSD Part 3 - Services and Firewalling

    > syncro writes: This is paper 3 of 4 of my server series.

    The topics we will be covering are in today’s paper are:

    2.5. Secure shell
    2.6. syslog
    2.7. cron
    2.8. ipfw and natd


    2.5. secure shell

    SSH means Secure Shell. With origin SSH is a replacement of the Berkeley R * orders such as rsh, rlogin or CCP considered as far from sure. SSH uses to make safe the transmission a tunnel crypté between the 2 machines. SSH quickly exceeded all waitings and it became a replacement interesting for telnet or ftp when they are necessary for regular users having an account on the machine in their offering an access method remotely highly protected and supported very well. In particular OpenSSH is a free and re-coded version protocol SSH and provides a customer and a waiter for many Unix platforms. It is him whom we now will use for the configuration of SSH.

    First of all we will publish the file of configuration of the daemon sshd.

    ($:~)=> ee /etc/ssh/sshd_config


    # This is ssh server systemwide configuration file.

    Port 22

    # avoid SSHv1 subjected to several vulnerabilities
    Protocol 2,1

    # when you copy this file for your jail to use think of putting
    # here alias your jail.

    ListenAddress 127.0.0.1, public_IP, jail_IP

    HostKey /etc/ssh/ssh_host_key
    HostKey /etc/ssh/ssh_host_rsa_key
    HostKey /etc/ssh/ssh_host_dsa_key
    ServerKeyBits 768
    LoginGraceTime 60
    KeyRegenerationInterval 3600
    RhostsAuthentication no
    RSAAuthentication yes
    PubkeyAuthentication yes

    # preferred order of the authentification and encryption algorithms
    Ciphers blowfish-cbc,aes256-cbc,aes192-cbc,aes128-cbc,3des-cbc,cast128-cbc,arcfour
    MACs    hmac-sha1,hmac-md5,hmac-ripemd160,hmac-sha1-96,hmac-md5-96

    # sending of a message after an interval given
    # and deconnexion after several sendings
    KeepAlive yes
    ClientAliveInterval 30
    ClientAliveCountMax 5

    # to avoid the imitations flooding A of the repeated attempts at connection,
    # we install a kind of quotas on the level of the management of connections.  
    # 10 for the number of connections not auhentifiees, 40 for the percentage of
    # refusal after the first number reached, and 50 meaning that at the end of 50
    # tentative any connection not authentifiee is refusee.
    MaxStartups 10:40:50

    # here we eliminate the vulnerabilites dregs with the files ~/.rhosts and
    # ~/.shosts and has their relations of confidence.
    IgnoreRhosts yes

    # verifier permissions and ownership of the files and of/home before accepting
    # a login
    StrictModes yes

    X11Forwarding no
    X11DisplayOffset 10
    PrintMotd yes

    # Syslog
    SyslogFacility AUTH
    LogLevel DEBUG

    # Below us privilegions the use of cles RSA and DSA for
    # authentification instead of the password
    PasswordAuthentication no

    # if you choississez to put the preceding option has yes, add that below
    # to prohibit passwords empty
    # PermitEmptyPasswords No

    # decontaminates the authentification s/key
    SkeyAuthentication No
    KbdInteractiveAuthentication yes
    ChallengeResponseAuthentication No

    # these blocks are relative has authentification Kerberos
    # KerberosAuthentication No
    # KerberosOrLocalPasswd yes
    # AFSTokenPassing No
    # KerberosTicketCleanup No
    # Kerberos TGT Passing does only work with the AFS kaserver
    # KerberosTgtPassing yes

    PermitRootLogin no
    CheckMail yes
    UseLogin yes

    # we do not recommend it because of its relative experimentalite but this
    # line allows you the case echeant to use sftp.  
    # Subsystem sftp/usr/libexec/sftp-server




    It does not remain us now than has to publish the file rc.conf once again in order to make sure that sshd will launch out well to the demarrage. We thus transform the line sshd_enable="NO "into sshd_enable="YES" and also adjoinions we to him the line sshd_flags="-4 "in order to limit the use has IPv4 connections. To generate your keys it will then be enough for you to carry out ssh-keygen; although this one is of out and already used by rc.network with sshd_enable.

    You will be able to finally decide not to offer of Shell to your distant users. This can be to carry out using chpass or of chsh while specifying like Shell/sbin/nologin.

    ($:~)=> chsh -s /sbin/nologin user

    2.6. logging

    We now will lean we on facilitate that us FreeBSD in the logging of the various activities system and user offers. We more particularly will study the system accounting, the system logging and the analysis of these logs by means automate.

    Under FreeBSD, we have the possibility of activating the system accounting which makes it possible to us to record and to recapitulate the orders carried out and allows us to store information detailed on the resources system used, their distribution between the users, and to supervise the system. With this intention, we have accton and of its. Accton makes it possible to activate or of desactiver the system accounting

    ($:~)=> accton /var/account/acct

    We specifions here a file towards which redirects give them accounting will be, for desactiver it is enough to executer the same order without the file in argument. To consult give them accounting it is enough to executer its with a classification by user

    ($:~)=> sa -u

    We thus obtain detaillées statistics of the system activity by users. You can also serve to you as the option rc.conf accounting_enable="YES "with the same effect.

    We also have has our provision the syslog family. First of all we have syslogd which enables us to record the error messages and other messages systems in the repertoire/var/log. To activate it, we once again publish rc.conf to add the following entrees to it

    syslogd_enable="YES"
    syslogd_flags="-ss -m 0"

    We have moreover adds flags making so that the daemon syslog functions in secure mode without possibility of log or transmission since the exterior. Then for afiner the recording of the messages, we will publish/etc/syslog.conf. Syslog.conf possede a whole syntax particuliere:

    O The blocks of directives are classes by program
    O the directives are form facility.level followed destination of the messages which can as well be a file as a user or a peripheral.

    Different the facility is:
  • - AUTH, brings back the messages of the comprising system of authorization of the programs such as login, known or getty
  • - AUTHPRIV, is similar A AUTH but makes it possible to limit the reading of the file of log
  • - CRON, relates to the daemon cron approaches low
  • - DAEMON, relates to the daemon system which does not beneficient a field facility dedié
  • - ftp, refers to the daemon ftpd and tftpd - KERN, brings back the messages generes by the kernel in kerneland by process kernel
  • - LPR, is relative A all the peripheriques ones and tools for impression such as lpr, lpc, lpd - MALL, allows loguer the relative messages with NEWS, similar A MALL but for Usenet
  • - SECURITY, concerns under systems of safety such as IPF or ipfw
  • - SYSLOG, relates to the messages generés by syslogd itself
  • - TO USE Messages generated by random to use processes. This is the default facility to identify yew none is specified.
  • - UUCP, designe the facility referring itself has the pile Unix-to-Unix Copy Program
  • - local0 with local7, desigent variable facility which can be used punctually by certain softwares
  • - * asterisque the represente here the whole of the entrees precedentes

    Follow-ups of the field level:
  • - EMERG, alert general, generally diffused with all the users
  • - ALERT, designe an alarm necessitant an immediate attention/correction
  • - CRIT, critical conditions such as problems the peripheriques ones
  • - ERR, relating to the error messages - WARNING, relating to the messages of basic alarms
  • - NOTE, designe an event not forcing in connection with an error but which can require a management particuliere
  • - INFORMATION, genere of simple messages for information purposes
  • - DEBUG, is referred has messages making it possible to look further into the comprehension of the operation of a software and thus possibly of the debugger in the event of problem
  • - NONE, allows desactiver this field

    We can also use operators of comparison like < (smaller than), = (equal), and > (larger than) in order to preciser several levels of logging for same a facility.


    # facility            destination
    *.=<notice            /var/log/messages
    *.=<crit            root

    auth,authpriv.*         /var/log/authlog
    cron.info            /var/log/cron
    mail.info            /var/log/maillog
    kern.*                /var/log/kernel
    security.*            /var/log/security
    security.=<err            /dev/console

    !ppp
    *.*                /var/log/ppp.log
    !ipfw
    *.*                /var/log/ipfw.log
    !sudo
    *.*                /var/log/sudo.log
    !racoon
    *.*                /var/log/racoon.log
    !nessusd
    *.*                /var/log/nessus.log
    !argus
    *.*                /var/log/argus.log

    # configuration syslog to be added in the jail
    #!apache
    #*.*                /var/log/access_log
    #!bind
    #*.*                /var/log/named


    To prevenir the exponential increase in the files of logs set up higher, we have has our provision newsyslog which allows creer a new file of log and to even file it (Z for gzip or J for bzip2), of specifier how much additional files of log are authorize (count), from which size (size in KB) or how long (time) to file - what can as well be a intervale as a date, or rights of its files (mode). We can thus obtain a logical filing on the level of space and time and more easily gérable by the administrator. Note that the hour of filing is encodée according to the format ISO 8601 which gives us:

    ccyymmddThhmmss
    20010915 000000 or,
    September 15, 2001 at midnight. This format which can be to simplify by withdrawing the superfluous fields.

    Finally you have the possibility of specifying a way to obtain the PID of a particular daemon as well as the possibility of sending a signal to him (HUP by defect) allowing to avoid the conflicts around the file of log.


    # logfilename        [owner:group]    mode  count  size time flags
    /var/log/maillog            440   10     *    @T00  J
    /var/log/messages            440   15     100  *     J
    /var/account/acct            440   15     *    @T00  J
    /var/log/cron                440   10     40   *     J
    /var/log/ppp.log            440   10     40   *     J
    /var/log/nessus.log            440   10     40      *     J
    /var/log/alias.log            440   10     40   *     J
    /var/log/authlog    root:wheel    400   10     20   @T00  J
    /var/log/security    root:wheel    400   10     20   @T00  J
    /var/log/ipfw.log    root:wheel    400   10     20   @T00  J
    /var/log/sudo.log    root:wheel    400   10     20   @T00  J
    /var/log/racoon.log    root:wheel    440   10     20   *     J
    #/var/log/access_log    www:wheel     1440  10     40   *     J
    #/var/log/named     named:wheel    1440  10     40   *     J
    /var/log/wtmp                440   15     *    @01T01 B


    An easy way interessante to be put in practice but little used consists of a synchronization NTP NTP means Network Time Protocol and allows has a machine customer to even synchronize her clock on a waiter of layer N him being synchronized on a waiter of higher layer or directly on a waiter of reference. The customer can as well decider synchronize himself has a waiter of reference directly. It is this pyramidal architecture which caracterise NTP Maintaining what can come well to make NTP in the system requirements of logging? And well in the future very near the correlation to log has the search for attacks or of information on attacks detectees by NESTS will be made manner centralisee and within this framework, an effective correlation must be based on a reliable timestamp and universal A a portion of network concernee. In addition the critical applications like waiters DNS or the waiters of services SMTP/NNTP providing a temporal reference has a user must be has the hour. To configure our machine customer, the configuration is extremement simple under FreeBSD. It is enough for us to publish rc.conf and to place the 2 following lines there

    ntpdate_enable="YES"
    ntpdate_flags="ntp-sop.inria.fr"

    Lastly, there is a tool that does not make party of the system itself but which can prove largely useful in the monitoring and the audit of the network and the traffic, it is about Argus, one To that the Record Generation and Utilization System. Argus is a program userland acting in a way similar to a sniffer by capturing the traffic passing on an interface network and generating reports/ratios of audit. For the capture of the traffic, Argus is based on TCPdump and the libpcap. Concerning this tool, you will find a howto interesting on http://minithins.net or .http://www.hsc.fr/ressources/breves/argus_fr.html.en.

    In addition, all these configurations considerably will increase the data to be analyzed and auditer. This is why we recommend to you to test and compare several tools for analysis of logs among which:
    O ASAX, ftp://ftp.info.fundp.ac.be/pub/projects/asax
    O Abacus Logcheck, http://www.psionic.com/abacus/logcheck
    O SWATCH, http://www.oit.ucsb.edu/~eta/swatch/
    O logsurfer, http://www.cert.dfn.de/eng/logsurf/

    2.7. cron

    Cron is one of the most traditional Unix tools and most useful which are since it will enable us to launch a precise task on a precise date. Cron moreover is launched as of starting then turns automatically in daemon mode and reveille every minute to check if it has a task to carry out in the minute to come and, while passing, note any modification of the crontab. The crontab represente the file since which cron will seek information, the orders which it must carry out. Cron will seek this crontab in/var/cron/tab then/etc/crontab.

    We publish rc.conf first of all in order to ensure us that cron launches out well. We check and if need be add the following line:

    cron_enable="YES"

    Then, to add new entries to cron, it is enough for us to publish the crontab. However, even if the crontab follows an obvious logic, it requires a certain syntax.

    mm[0-59 ] hh[0-23 ] jour_du_mois[0-31 ] mois[1-12 ] jour_de_la_semaine[0-7 ]

    This syntax being accompanied by some quite practical options such as the indefinition (*), the lists (1,2,3,4) or the frequency is within one champ(0-23/2) or in a general way thanks to the options:

    @reboot, for launching 3rd each starting
    @yearly or
    @annually, for an annual launching
    @monthly, a monthly launching
    @weekly, a weekly launching
    @daily or
    @midnight, for a daily launching and
    @hourly, a launching every hour.

    ($:~)=> ee/etc/crontab



    # you have the possibility of specifier with which Shell executer the orders
    SHELL=/bin/sh
    # this option makes it possible to indicate has cron which to prevenir in the event of problem
    MAILTO=root
    #
    # update of the plugins Nessus each week
    @weekly            nessus-update-plugins
    # checking of integrite mtree every week
    @weekly         mtree -x -i -f bin.spec | mail -s 'mtree /bin \
                results' root
    @weekly         mtree -x -i -f sbin.spec | mail -s 'mtree /sbin \
                results' root
    @weekly         mtree -x -i -f libexec.spec | mail -s 'mtree \
                /usr/libexec results' root
    @weekly         mtree -x -i -f lib.spec | mail -s 'mtree /usr/lib \
                results' root
    @weekly         mtree -x -i -f sharelib.spec | mail -s 'mtree \
                /usr/share/lib results' root
    @weekly         mtree -x -i -f boot.spec | mail -s 'mtree /boot \
                results' root
    # accompanied by a checking of the services by lsof
    @weekly         lsof -niU
    # and of a checking KSEC
    @daily ksec -i interface -b -k -p
    # update ports tree only for the environment host
    @monthly        make update PORTSFILE
    # newsyslog
    @hourly         newsyslog
    # ntpdate daily if you have significant uptimes
    @daily            ntpdate ntp-sop.inria.fr
    # launching of racoon to starting
    @reboot         racoon -f /etc/racoon.conf


    Here is, a useful crontab and maintenance in less!

    2.8. ipfw and natd

    In this chapter we will approach a mechanism of safety extremely used nowadays, namely the firewalling. The firewalling can result in several aspects going of the packet filtering sober but effective to the complexes but useful proxies applicatifs. In order to illustrate our remarks and to apply the firewalling to our system, us utiliseronts ipfw delivered with FreeBSD and which we activated thanks to some options kernel with the whole beginning of our configuration. Many people are let allure by IPFilter. The generally advanced reason is its behavior known as stateful which must make it possible to follow a connection in order to carry out a better filtering on the whole of this connection. However ipfirewall is integrated directly into FreeBSD what already ensures us of good performances the level network. In addition, the option keep-state of ipfw implying the automatic creation of a state table allowing the follow-up of flows for the filtering of packages. The state table and the rules ipfw which go with, create for each package that ' match' a rule a new dynamic rule making it possible to follow - certainly in manner less meddles that IPFilter - and to authorize connection. With this intention, ipfw uses in particular for the OSI 4 a mechanism known as of lifetime which makes it possible to preserve an active dynamic rule on standby of a new package which will start again the decrementation of this lifetime. If the lifetime arrives at zero without new package, then the dynamic rule disappears and the packages are refused. The following entries sysctl enable you to specify the duration of the lifetime correspondent in each state TCP, UDP and others. Then you can configure the size of the table hashage intended for the dynamic rules of your ruleset, this modification taking effect only after a flush. Lastly, the last entry follows upon the application of a patch (http://people.freebsd.org/~cjc/ipfw_verbose_stable.patch) making it possible to further increase the verbosity of ipfw while adding to posting in the logs of the fields DiffServ, IP ID and TTL (in addition to the traditional addresses and ports source and destination), the fields ack number, sequence number and TCP flags.

    ($:~)=> sysctl -w net.inet.ip.fw.dyn_ack_lifetime=300
    ($:~)=> sysctl -w net.inet.ip.fw.dyn_syn_lifetime=20
    ($:~)=> sysctl -w net.inet.ip.fw.dyn_fin_lifetime=10
    ($:~)=> sysctl -w net.inet.ip.fw.dyn_rst_lifetime=5
    ($:~)=> sysctl -w net.inet.ip.fw.dyn_udp_lifetime=15
    ($:~)=> sysctl -w net.inet.ip.fw.dyn_short_lifetime=30
    ($:~)=> sysctl -w net.inet.ip.fw.dyn_max=1000
    ($:~)=> sysctl -w net.inet.ip.fw.verbose=2

    Although they are not approached here even, will know that IPF lays out of similar entries once installed, under net.inet.ipf. *.

    To see the currently observed rules and in particular the dynamic rules, enter:

    ($:~)=> ipfw show

    Also do not forget to publish rc.conf in order to add to it the lines concerning the firewalling such as firewall_enable="YES ", firewall_quiet="YES ", firewall_logging="YES "and firewall_type="simple". To insert rules in the ruleset, you can either publish the simple section of/etc/rc.firewall, or to use the order ipfw according to the following diagram

    ipfw command action from to

    - the orders can be ' add' to add a rule, ' delete' individually to remove a rule and ' flush' for the totality of the rules, like ' show' or ' list' to have the current rules. Each rule must have a single number to avoid confusion and the rules are classified according to the order of the matching.

    - the actions can be ' allow' to let pass a package, deny it to silently refuse and ' reject' to send an ICMP host unreachable (spécifiable error with the actions ' unreach' and ' reset '), ' check-state' in order to check a correspondence with the dynamic rules, or ' fwd' followed IP and possibly of the port if you have IP routables. We also have the possibility of logger - as single or additional action with the preceding ones - with ' log' to which you can add ' logamount' for overwriter option IPFIREWALL_VERBOSE_LIMIT.

    - the protocols can be ' all' or ' ip' to make correspond all the protocols, or the name or number of the protocol wished in accordance with/etc/protocols.

    - We can then specify the source after the field ' from ', the destination after the field ' to' as well as the ports right after the address source or of destination. Also note the presence of ' me' allowing to recover the IP of our firewall since ifconfig what proves very useful in the event of dynamic configuration. Lastly, for the ports or the addresses, IPFW supports from now on the logical operators.

    - the key words ifspec allowing us to work on the interfaces. We can for example specify the matching packages only in ingress with ' in' and egress with ' out ', or the interfaces checked with ' via' followed interface, recv to check only the interface of reception and xmit to check only the interface of sending.

    - For the stateful inspection, ' keep-state' announces a dynamic follow-up for this filter, ' setup' matche the packages with flag SYN only, ' etablished' relates to the packages with flags ACK or RST. But you can also specify ' ipoptions' (lssr, ssrr, rr, ts) or ' tcpoptions' (mss, window, DC, sack, ts) as well as ' tcpflags' (fine, syn, rst, psh, ack and urg) or ' icmptypes' (0, 3, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18). Lastly, the key word ' limit' was introduced recently (4.5-release) to make it possible to limit the number of simultaneous connections per association for a filter, this by specifying the address and/or the port source, the address and/or the wearing of destination then the limit of connections. Will know finally that you can on the level of the firewall itself filter the users via the options ' uid' and ' gid' followed by their value.


    To obtain the totality of the fields and in particular a description of the use of dummynet like basic traffic shapper, defer to the page of man of ipfw. But in this field we recommendons you really ALTQ developed within the framework of the project KAME (and thus regularly mergé) in particular implementing disciplines CBQ, WFQ/SFQ or HFSC as well as algorithms RED and its alternatives RIO or Blue and finally extensions ECN, RSVP (with CBQ and HFSC) as well as a support for the DiffServ model. More information on the site of ALTQ, .http://www.csl.sony.co.jp/person/kjc/software.html#ALTQ. The final integration of ALTQ to the hand tree FreeBSD is in hand for the release 5.0

    Note to finish some with the orders ipfw which there exists interesting a patch since FreeBSD 4.3 known as lifetime which makes it possible to impose a timeout on a transmission via a rule of the firewall which will block it once this timeout reached. This patch not being integrated into the basic system, we will not be delayed on its use. You will be able to find all information necessary to the installation of the patch and the use of new the keyword with .http://www.aarongifford.com/computers/ipfwpatch.html.

    When you launch your machine with the options activating the firewall for the first time, approximately 200 basic rules are automatically generated. We thus start by purging our rules:

    ($:~)=> ipfw flush

    In the beginning of the ruleset, we define some variables as the order ipfw with the option - Q for a discrete output, the mask of our internal network, the address of our jail, and our interfaces of entry and exit.

    Us kids then on the interface of entry all packages with for source a reservée address not routable or the address of our internal network, and we journalize these cases express spoofing. These addresses are indexed on the site of the IANA and in the RFC 1918.

    Then we make diverge the traffic to pass by natd for the translation of addresses and ports towards our private addresses. This rule is followed checking of each package against the state table to know if it belongs or not to an already accepted connection. We can then reject all the packages in established state TCP or fragments IP since they will be ensured not to belong to a connection in progress.

    Then we authorize certain communications as DNS of which we will have taken again the addresses in/etc/revolv.conf, followed administration of the machine via SSH, and finally we authorize Racoon, Argus and Nessus to be communicated. For the customers behind the firewall, we also authorize at exit connections ftp, smtp, ssh, HTTP, pop3, NTP, IMAP like https, ircs, pop3s.

    Then restrictions ICMP used as well in scanning in Back come. We let pass since the exterior the echo reply, destination unreachable, time exceeded, parameter problem, and timestamp reply. Towards the exterior, we authorize the echo request, time exceeded (fragment reassembly) and the timestamp request. With this, we have the minimum to ensure the path discovery, the checking of connectivity and detection

    To now apply a filtering of packages to the services provides by a jail, we make as if it were a filtering on the environment host, only we substitute for it alias private jail which we filter while passing by the interface of loopback lo0.

    During the creation of your rules, made attention with the order in which place them to you in your ruleset, with the interfaces to which they should be applied and with their destination. As specified by the implementations notes of ipfw(8), the number of times where a package is inspected varies: of once for the packages having an end locally and for the bridgés packages, with 2 times for the packages whose 2 ends are local or for the forwardés packages. The only manner of changing this behavior is through sysctl:

    ($:~)=> sysctl -w net.inet.ip.fw.one_pass=1

    But be extremely careful in this case at the time of the writing of these rules not to let enter any package builds especially after analysis of the rules. To take into account all this information, it is to check that a package will be well inspected and at the good place.

    To finish, we refuse any other traffic that that expressement to authorize and for more sureté. See below the final file/etc/rc.firewall.


    # variables ...
    fwcmd="ipfw -q"
    net="192.168.0.0"
    mask="255.255.255.0"
    jail="192.168.0.2"
    intif="fxp0"
    extif="fxp1"

    ${fwcmd} -f flush

    # reserved addresses
    ${fwcmd} add 201 deny log all from 192.168.0.0/16,172.16.0.0/12,10.0.0.0/8,
      127.0.0.0/8,0.0.0.0/8,169.254.0.0/16,192.0.2.0/24,204.152.64.0/23,
      224.0.0.0/3,${net}:${mask} to any in via ${extif}

    # divert towards natd
    ${fwcmd} add 300 divert 8668 all from any to any in via ${extinf}

    # checking compared to the state table
    ${fwcmd} add 400 check-state
    ${fwcmd} add 401 deny tcp from any to any in established
    ${fwcmd} add 402 deny ip from any to any in frag

    # communication DNS, SSH, Racoon, Argus and Nessus
    ${fwcmd} add 403 allow udp from ${net}:${mask} to primary_DNS 53 in keep-state
    ${fwcmd} add 404 allow tcp from any to me 22 keep-state setup limit src-addr 5
    ${fwcmd} add 405 allow udp from any 500 to any keep-state
    ${fwcmd} add 406 allow udp from any to any 500 keep-state
    ${fwcmd} add 407 allow tcp from any to any 561,3001 keep-state limit dst-addr 2

    # communications towards traditional waiters
    ${fwcmd} add 408 allow tcp from ${net}:${mask} to any
      20,21,22,25,80,110,123,143,443,994,995,6667 keep-state setup

    # limitations ICMP (ping, Van Jacobson' S traceroute...)
    ${fwcmd} add 500 allow icmp from any to ${net}:${mask} in icmptypes 0,3,11,12,13,14
    ${fwcmd} add 501 allow icmp from ${net}:${mask} to any out icmptypes 1,8,11
    ${fwcmd} add 502 allow udp from ${net}:${mask} to any in 33400-33500
    ${fwcmd} add 503 deny log icmp from any to any

    # redirection services jail
    ${fwcmd} add 602 allow udp from any to ${jail} 53 in keep-state via lo0
    ${fwcmd} add 603 allow tcp from any to ${jail} 80,443 in keep-state setup via lo0

    # Restrictive stanza:  everything not explicitely allowed is forbidden.
    ${fwcmd} add 900 deny log all from any to any
    ${fwcmd} add 901 deny log all from any to ${jail} via lo0


    So that these rules are observed, you owe either redemarrer, or to start again init which will initialize these rules.

    ($:~)=> kill -HUP init

    The NAT for Network Translation Adress is a mechanism in the beginning created for stage with the shortage of IP addresses available. It makes it possible to use a gateway which for each communication will redirect the transmissions between external addresses routables and addresses intern not routables by rewriting the corresponding headings and by storing information of correspondences in a hash table. Thus we use only one IP routable which is that of gateway NAT. The NAT is a mechanism of division of connection interesting but it will not make the deal in the event of load balancing since its method of queueing is based on Weighted Round Robin which serves in turn each tail on standby, but the NAT by WRR treats the priority according to the implementation DiffServ Assured Forwarding thus rejecting the packages low priority under strong constraints. Moreover the flow of congestion of the NAT is rather low, even more if you use natd which is userland involving a copy since the kernel towards the userland. Prefer ipnat/ipf modulates kernel for better performances of it.

    The other couple being ipfw/natd, we now will see a basic configuration of natd in order to relay the requests of our host towards our jail or any other machine being behind our FreeBSD.

    To start, we publish the file rc.conf to add the following lines to it

    gateway_enable="YES"
    natd_enable="YES"
    natd_interface="fxp0"
    natd_flags="-f /etc/natd.rules"

    Thus natd will be launched to each starting with like file of configuration natd.rules, which we now will publish. For more information on the rules used, defer to the man page. We make only one rapid introduction in connection with our securized configuration. However, note that the redirection via natd can be done starting from the address with redirect_adress, by port with redirect_port and protocols with redirect_proto. A last rule can prove very useful for the users of IRC and ftp: the rule punch_fw followed basenumber:count respectively the number of the starting rule followed by the number of dynamic rules which can be created.


    log            yes
    deny_incoming        no
    use_sockets        yes  # allocate a socket limiting the conflicts of ports
                                 # dynamic
    same_ports        yes  # try to use the same port for the translation
    verbose         no
    port            natd
    unregistered_only    yes  # NAT only for the addresses type RFC 1918
    log_ipfw_denied     yes  # log packages not reinjected due to
                                 # blocking by ipfw (useful for debugger)
    # DNS
    redirect_port udp jail_IP_alias:53 public_IP_adress:53

    # HTTP or HTTPS
    # LSNAT > RFC 2391
    redirect_port tcp jail_IP_alias:80,443 80,443
    redirect_adress tcp www1_IP:80, www2_IP:80 jail_IP_adress:80

    # SSH on the second jail
    redirect_port tcp jail_user_IP_alias:22

    # static NAT for other machines
    redirect_address internal_IP1 public_IP
    redirect_address internal_IP2 public_IP
    redirect_address internal_IP3 public_IP


    Note that natd naturally integrates functionalities of follow-up of connections. Therefore, when you configure a footbridge to use natd, it is not really any more useful to use the stateful inspection on the level of ipfw. You can simply configure a static firewall and natd deals with the inspection of states for relayed connections. If you still smell the need to preserve rules keep-state, then the key word skipto returning to another rules can prove to be useful.

    Server FreeBSD Part 4 - Tools and Security awareness

    syncro writes: This is paper 4 of 4 of the server series.

    The topics we will be covering are in today’s paper are:

    3. Tools
    3.1. TCPdump
    3.2. Nessus
    3.3. lsof
    3.4. stack smashing
    3.5. tunneling
    4. Conclusion


    3. Tools

    We will lean on certain Tools more or less in direct connection with the system but who are not inevitably available by defect or then by the ports but not up to date, or which is caracteristic quite specific system. Thus we here will decouvrir some Tools allowing to reinforce our safety as well proactive manner as reactive.

    3.1. TCPdump

    TCPdump is the ultimate tool for sniffer the traffic of a network in order to carry out its debugging. It will enable us to capture whole or part of the traffic local area network in order to enable us to analyze it in order to check the correct operation of our configurations network. With this intention TCPdump bases itself on the layer system BPF for Berkeley Packet Filter in order to intercept the Ethernet screens and packages IP forwarding by the machine in promiscuous mode (mode where Network Interface Card or NIC can see the whole of the traffic network) according to expressions' bpf similar to the concepts of expressions regulières. This method of capture by BPF east provides by the bookshop libpcap facilitating the development of sniffers enormously advanced.

    TCPdump provides a number of options impressive of which we will approach most useful here. First of all with each capture we recommend following syntax to you:

    ($:~)=> tcpdump -X -s 1500 -e -n -i fxp0

    This line of order makes it possible to obtain a dump at the same time in hexa and ASCII, a length of 1500 bytes, posting information of heading on the level of the connection layer which will be generally Ethernet, we do not carry out a resolution of names in order to gain in speed, discretion and facilitated of analysis; and finally we specify the NIC on which to listen what can avèrer useful when the console admin has several interfaces or is used as footbridge.

    The exit as for it is appeared - in the case of a package TCP here - as a timestamp, then Initial the Number Sequence followed by the number of sequence of the package, the size of the package between brackets, flags TCP, the number of acknowledgment, the window size, flag IP informing about the state of fragmentation and finally options TCP. The exit can of course vary if one captures a package UDP or ICMP (with in this last case type ICMP). With the options already presented, we also obtain in the dump the headers layer connection, you can of course remove this option for more simplicity.

    A combination of also interesting options and if required to use with the options already seen, is as follows:

    ($:~)=> tcpdump -i fxp0 -l > file && tail -f file

    This entry enables us to redirect the traffic captured on the interface specified towards a file ' file' that we will be able to then see to be brought up to date by group of 10 lines using tail. This allows a monitoring

    Of course, we do not need to capture the totality of the packages when we seek only one particular transmission in order to carry out debugging or other analyzes. For that we have the possibility of using expressions BPF introduced higher. They enable us to test a given byte of a package IP or even of its part TCP/UDP/ICMP. It is also possible, thanks to expressions boolénnes to test one or more bits of each byte. Expressions BPF are placed simply at the end of the options of the line of TCPdump order. Traditional expressions BPF are subdivided in 3 groups which can be combined between them to carry out any (or almost:) matching.

    The first group is consisted of the ' types' which can be host for matcher an address IP or a field, Net for matcher a class network - this field can be refined by specifying a mask with its continuation - and port for matcher a port. These types are the core operators of the capture. We have then the ' dir' which specifies the direction to be sought. We have here at our disposal the key words src for the origin and dst for the destination. Lastly, we have the group ' proto' which makes it possible to seek corresponding packages. We find there ether or FDDI for the layers Ethernet connections and assimilated, arp and RARP for the protocols of the same name, IP and ip6 for the versions of IP v4 and v6, ICMP and icmp6 in a similar way and finally TCP and UDP. With these 3 groups, it is necessary for us to add several additional expressions to knowing gateway which allows matcher a package whose Ethernet address corresponds to the expression but not address IP source nor destination and thus to obtain the packages coming from a certain router. We also have less and greater in order to capture the packages lower or higher than a given length. Finally we have the traditional logical operators but, and and not representing inclusion, the concatenation or exclusion.

    ping of death
    ($:~)=> tcpdump -Xni fxp0 icmp greater 65535

    traffic HTTPS and IRCS
    ($:~)=> tcpdump -Xni fxp0 (tcp port 443) or (tcp port 994)

    There are also advanced expressions making it possible to carry out finer operations of capture on the packages. The syntax of an expression BPF is as follows

    proto[offset:longuor ] logical operation

    where proto is similar to one of the fields of the group ' proto' referred to above, offset indicates the shift of the field to be tested, the length indicates the length of the field to be intended and the logical operation the test itself. This requires a precise knowledge of the fields of the various protocols what can be done after a study of the RFC corresponding. To seek a precise field, it is wise to point out the structure of a datagram IP and a segment TCP by considering the dump according to:


    4500 003c 0a66 4000 4006 a320 c0a8 0001
    c0a8 0002 04c5 0016 801e 78e3 0000 0000
    a002 3fc4 fe70 0000 0204 05cc 0402 080a
    0014 7e59 0000 0000 0103 0300


    4 = IP Version
    5 = IP header length
    003c = IP total length
    0a66 = IP ID
    4000 = IP fragmentation (flags then multiple offset of 8)
    40 = IP TTL
    06 = IP Protocol
    a320 = IP checksum
    c0a8 0001 = IP source
    c0a8 0002 = IP destination
    04c5 = TCP source port
    0016 = TCP destination port
    801e 78e3 = TCP sequence number
    a = TCP data offset
    002 = TCP Control bits (flags, ici SYN)
    3fc4 = TCP Window Size
    fe70 = TCP Checksum
    0000 = Urgent Pointer
    0204 05cc = TCP Maximum Segment Size (only with SYN)
    0402 = TCP SackOK Permitted (only with SYN)
    080a 0014 7e59 0000 0000 = TCP Timestamp (field reply to 0, since SYN)
    0103 = Padding
    0300 = TCP Window Scale (only with SYN)

    Not to have to retain this heavy diagram (who is right that of a traditional flow), you can carry out following your order tcpdump and after a Unix pipe, tcpdumpx writes by Wietse Venema which precisely comments on the dumpées data. You will be able to find this prorgramme with .ftp://ftp.porcupine.org/pub/debugging/.

    Above a series of filters ready with employment.


    * paquets TCP avec flags
      SYN : tcp[13] & 2 != 0
      ACK : tcp[13] & 16 != 0
      FIN : tcp[13] & 1 != 0
      RST : tcp[13] & 4 != 0
      PSH : tcp[13] & 8 != 0
      URG : tcp[13] & 32 != 0

    * Christmas Tree Scan
      ($:~)=> tcpdump -Xni ed0 '(tcp[13] & 1 != 0) and (tcp[13] & 8 != 0) and
               (tcp[13] & 32 != 0)'

    * capture ICMP echo request and fold up
      ($:~)=> tcpdump -Xni ed0 '(icmp[0] = 8) or (icmp[0] = 0)'

    * fragmented packages IP
      MF : ip[6] & 32 != 0
      DF : ip[6] & 64 != 0
      offset : ip[6:2] & 0x1fff != 0


    In margin of TCPdump, we recommend to you to throw an eye with the following programs inspired, based on TCPdump or being used as extensions:
  • ethereal (http://www.ethereal.org)
  • Shadow (http://www.nswc.navy.mil/ISSEC/CID/)
  • NStreams (http://www.hsc.fr/ressources/Tools/nstreams/)

    3.2. Nessus

    Nessus is what is called a scanner of vulnerabilities (assessment scanner). It has as a characteristic to really carry out the tests corresponding to an attack known against the machine, and this by exploiting as well traditional software attacks as errors of configuration. In addition, it is equipped with a modern architecture aliant customer-server modularity and model. The waiter nessusd carries out the tests while the graphic interface nessus - which can be GTK, Java or even Win32 - allows to select the tests and of reading the reports/ratios of scan by controlling the waiter. This architecture makes it possible to imagine all the configurations like a distant daemon for several operators or an operator for several let us daemons on several networks (this idea not having escaped the companies carrying out from the tests from intrusion on the basis of nessus and seldom contributing). In addition, Nessus is modular, which means that each attack is a plugin in NASL (Nessus Attack Script Language, a language with syntax similar to C for the writing of tests) or out of C called by nessusd to carry out the tests. The plugins are managed by Knowledge Base, true architecture of communication inter plugins in which they are seen sorted according to their type, dependence, need or exclusion and by which they can share information in order to avoid the redundancy of tests. A last notable characteristic is that through the KB, it does not take account of the scanné port, but only of the service thus avoiding being misled by exotic bindés ports. Nessus will use to us to check if our preceding configurations on the level network did not involve the creation of exploitable errors by an intruder and also to check if our services and our system are vulnerable or not to the hundreds of attacks that Nessus tests. It will then only remain us to take measurements necessary like patcher our machine or to modify the configuration of it. You can recover Nessus with http://www.nessus.org or since the ports tree with/usr/ports/security/nessus-1.2.3. You could need also Queso, Nmap or in the future Whisker or IDS which parse the ruleset Snort like Prelude.

    Initially, once the finished installation, you must launch the order nessus-adduser in order to add a user to the daemon nessus.

    ($:~)=> nessus-adduser
    Using /var/tmp as a temporary file holder

    Add a new nessusd user
    ----------------------

    Login : eberkut
    Authentication (pass/cert) [pass] : pass
    Login password : foobar

    User rules
    ----------
    nessusd has a rules system which allows you to restrict the hosts
    that astro has the right to test. For instance, you may want
    him to be able to scan his own host only.

    Please see the nessus-adduser(8) man page for the rules syntax

    Enter the rules for this user, and hit ctrl-D once you are done :
    (the user can have an empty rules set)
    ^D

    Login : eberkut
    Password : foobar
    DN :
    Rules :

    Is that ok ? (y/n) [y] y
    user added.

    Note that the syntax of the access rules is rather simplistic since it counts like rules deny to prevent the scan, accept to authorize it and default to define the policy by defect in deny or accept. For each rule, you specify an address IP possibly followed by a netmask in notation CIDR or the variable client_ip automatically indicating the machine source of the customer. You can moreover to be used you as nessusd.users to define rules by users (authenticated by password or key). See nessusd(8) for more details.

    # password
    eberkut:foobar
    # rules
    accept client_ip
    default deny

    These rules as of other options are still configurable after nessus-adduser via nessusd.conf that we will decide to preserve in/etc rather than in the repertory nessus.

    ($:~)=> cp /usr/local/nessus/etc/ /etc/nessus/ && cd /etc/nessus/
    ($:~)=> ee nessusd.conf

    # access path to the plugins
    plugins_folder = /nessus/lib/nessus/plugins

    # a many simultaneous tests, must be equal to the number of devices bpf
    max_threads = 20
    track_iothreads = yes

    # log file
    logfile = syslog

    # log all details of the attacks?
    log_whole_attack = yes

    # log names of plugins to their loading?
    log_plugins_names_at_load = yes

    # dump file for debugging purpose
    dumpfile = /nessus/var/nessus/nessusd.dump

    # rules file
    rules = /etc/nessus/nessusd.rules

    # user database
    users = /etc/nessus/nessusd.users

    # CGI path
    cgi_path = /cgi-bin

    # space ports for nmap
    port_range = 1-32768

    # optimize test
    optimize_test = yes

    # language (english or French)
    language = francais

    # Crypto options
    negot_timeout = 600
    force_pubkey_auth = yes
    # peks has been deprecated, and the author of this document does' NT cuts any
    # box to install Nessus and update this share of the configuration slips by. Sorry
    peks_username = nessusd
    peks_keylen = 1024
    peks_keyfile = /etc/nessus/nessusd.private-keys
    peks_usrkeys = /etc/nessus/nessusd.user-keys
    peks_pwdfail = 3
    cookie_logpipe = /etc/nessus/nessusd.logpipe
    cookie_logpipe_suptmo = 2

    # optimization
    # read timeout for the test sockets
    checks_read_timeout = 15
    # space between 2 tests against the same port in seconds
    delay_between_tests = 5

    For the totality of the tests implying the use of SSL as if you decided to use the authentification client/server by certificates, you will have to generate a certificate. Nessus lays out with this intention of a script nessus-mkcert (and nessus-mkcert-customer to generate a pair certificat/clé for your customer).

    ($:~)=> nessus-mkcert
    This depending script will now ask you the information to create the SSL certificate of Nessus. Note that this information will * NOT * Be feels to anybody (everything stays local), goal anyone with the ability to connect to your Nessus daemon will Be whitebait to retrieve this information.


    CA certificate life time in days [1460]:
    Server certificate life time in days [365]:
    Your country (two letter code) [CH]: FR
    Your state or province name [none]:
    Your location (e.g. town) [Paris]:
    Your organization [Nessus Users United]: CNS

    Congratulations. Your server certificate was properly created.

    /usr/local/etc/nessus/nessusd.conf updated

    The following files were created :

    . Certification authority :
    Certificate = /usr/local/com/nessus/CA/cacert.pem
    Private key = /usr/local/var/nessus/CA/cakey.pem

    . Nessus Server :
    Certificate = /usr/local/com/nessus/CA/servercert.pem
    Private key = /usr/local/var/nessus/CA/serverkey.pem

    Press [ENTER] to exit

    If you do not wish to use SSL, place ssl_version at none in nessusd.conf, or change the makefiles nessus-libraries and nessus-core for add - sayable-cipher to /configure. More information in README_SSL available in nessus-core.

    To launch the daemon nessus now configured, it any more but does not remain you to carry out

    ($:~)=> nessusd -c /etc/nessus/nessusd.conf -D

    Note also the option - L allowing to list the base of users.

    As regards customer, you lay out as explained various graphic interfaces previously customer, namely X11 in GTK, Java and even 2 Win32. However, remember that nessusd functions only under Unix. When you launch the customer nessus for the first time, it will deal with generating a pair of keys then will ask you a passphrase. The second time, you will not have any more but to return your passphrase. You are then vis-a-vis a window of login allowing you to connect itself to a distant nessusd (fields Nessusd Host, Port, Encryption and Login). You are then directed towards the Plugins panel allowing you to select the plugins test. The higher list classifies the plugins by types, and are posted in the lower list enabling you to select them or not. You also have the buttons Enable All for a complete scan, Enable all goal dangerous plugins not to carry out the tests like the Backs able to plant a weak machine (i.e. Windows) or Sayable All. For some plugins, you will need to specify additional arguments as for the POP2 overflow, the ftp privilege escalation and especially the configuration queso or nmap -- can be in the future Whisker, the cgi scanner by Rain Forrest Puppy. This can be done in the Prefs panel. You have then the panel Scan options in which you can configure the Port Arranges, the number maximum of threads competitor, or the access path to the cgi - this being already configured in the file configuration nessusd - more some other functionalities and especially the options of the port scanning (with nmap) Then come the panel Target Selection in which you specify, in the form of IP with or without netmask or of field, the machines which you wish scanner, separated by commas. You can also have files very ready specifying these rules and make them read by Nessus. You find then the User panel in which you can manage your key or change your passphrase and also specify here still rules of scanning this time specific to this scan in ' reject' the hosts with not scanner. Once all these panels reviewed, it any more but does not remain you to make a start scan and to await the results which will be presented in the form of trees. You will be able then to safeguard them in the form of the same Nessus carryforward (nsr) or in the form of file HTML with graphs, of file postscript or of LaTeX file and many others. In the versions to come, you will be able even directly to export the results in the form of Snort rules and thus use compatible IDS like Snort or Prelude to monitor your vulnerable machines. We will add finally a small bracket on some functionalities for the moment experimental but which will be officially installation at the time of the release 1.1.0. The first is the safeguard of Knowledge Base. Indeed, the information receuillies and shared through the KB is released from the memory after each scan requiring to remake all the process of information gathering each time. If you wish scanner regularly your network, you will pourez to prefer to use the option of panel KB of the interface allowing to activate the safeguard of the KB Before version 1.1.0, this option exists only if you compiled Nessus-core with

    ($:~)=> ./configure --enable-save-kb

    In this same panel KB, you can then specify if it is necessary of scanner the totality of the hosts, only those already scannés previously or only the new hosts ever scannés. In addition you can specify the re-use of old the KB which will then be reloaded in memory and with it to specify which plugins you do not want to see re-executed: not to remake the scans, not to remake the stages of information gathering, not to remake the attacks or not to remake the Backs Lastly, you have the possibility of defining a limit of time during which old the KB is valid in seconds. Another enticing experimental functionality is the possibility of carrying out detached scans, without intervention of the customer. After the activation of the safeguard of KB, we have in the panel Scan options new entries: detached scan meaning that the customer will not obtain the data in real time, continuous scan makes start again nessusd after each end of tests, send results to this email adress makes it possible to specify an address to which to send the results and finally delay between two scans definite time in seconds between 2 scans of the option continuous scan. By combining these 2 functionalities and by placant a update plugins in the crontab, we have the capacity from now on to carry out a scan of update regular without more troubling us about Nessus. With this intention, we must activate the options Enable KB saving, Only test hosts that cuts never been tested in the past, Reuse the knowledge bases butt the hosts for the test and the 4 options Do not execute in panel KB; and finally we decide that the KB will be valid for one week is 604800 seconds. Then, in the panel Scan options, us pigs the options detached scan and continuous scan and let us place the deadline between 2 scans at one hour, that is to say 3600 seconds. You can specify quite simply the address root like destination of the reports/ratios. Thus, Nessus will scannera only the hosts who have not already been scanné for the last 7 days, will wait one hour and will start again which more is with up to date plugins thanks to the entry of update in the crontab.

    If you have some talents in programming and in safety and/or that you wish to contribute to Nessus, you can learn how to create plugins, which make all the value and the power of Nessus, with the address .http://www.nessus.org/doc/nasl.html.

    3.3. lsof

    The utility lsof - meaning LiSt Open Slips by - is an advantageous replacement with netstat, fstat and sockstat under FreeBSD. It is able to list all the files opened not all the processes and can thus be used to list open ports and services like their owners. You can install lsof since the ports with/usr/ports/sysutils/lsof.

    For example we can list only the files sockets Internet with the option - I, the option - N allowing of not resoudre the addresses.


    ($:~)=> lsof -ni
    COMMAND    PID    USER    FD   TYPE      DEVICE SIZE/OFF NODE NAME
    portmap    156    daemon  3u   IPv4  0xc3dabf00    0t0   UDP  *:sunrpc (LISTEN)
    ssh        259    root   16u   IPv4  0xc3ddcd80    0t0   TCP  *:ssh (LISTEN)
    sendmail   287    daemon  4u   IPv4  0xc3dddb60    0t0   TCP  *:smtp (LISTEN)


    You see that the presentation of the listing makes it possible to see the types of sockets, TCP or UDP, in column NODE then the address and the port of listening in column NAME. The lines corresponding to connections in progress are posted with an arrow "- >" separating the addresses and ports sources and destinations. The ports in listening do not have an arrow and do not comprise that an address and a port. In this last case, the address can be a star if the process listens on all the addresses simultaneously.

    It is possible to ask lsof to post only one port and/or a given address IP. Note that lsof supports the IPv4 addresses as well as v6, it is enough to adopt the notation correct (loopback = 127.0.0.1 and::1)
    ($:~)=> lsof -ni proto@host:port

    But lsof offers many other possibilities. We can for example list the whole of the sockets whatever their field (UNIX or Internet)

    ($:~)=> lsof -U -n -i

    Or to list open files according to their owner by the option - U or their PID by the option - p like by the options - G to filter starting from the group. We can specify several PID, GID and use while placing commas

    ($:~)=> lsof -p pid -g gid -u username

    Lsof has finally some quite practical functions. First of all using the option - has, we can filter according to several similar arguments. What on sockets of field Internet, can enable us to seek several quite specific services or addresses.

    ($:~)=> lsof -a -n -i proto@host:port -i proto@host:port

    It as should be known as lsof can be carried out in repeat mode in order to obtain a constant monitoring or regulière. This is carried out using the option +|- R time when time designe time between each repetition in seconds. The option paramètrée with + instead of - makes it possible to stop lsof when it does not list anything any more in addition to stopping by a SIGINT.

    ($:~)=> lsof -ni +r30

    3.4. stack smashing

    We here will approach 2 Tools extremely practical for FreeBSD allowing to prevent the attacks of the type buffer overflow consisting in exceeding a static buffer memory to write an original code carried out with the rights of the program on which this buffer depends. We have of libparanoia and the GCC protector patch.

    libparanoia is a bookshop which intercepts the calls to functions supposed sensitive and replaces them by similar functions in all points and functionalities, with the only difference that these functions are modified to prevent all attempts at corruption of the pile memory what makes it possible to warn us faults of the type stack overflow or return- into-libc very documented and largment widespread these last years. Functions ANSI C supposed sensitive are strcpy, strcat, gets, sprintf and scanf which is known to be often exploited at illegitimate ends. The essential problem comes owing to the fact that the language C does not include aucunes technical native checking when we handle variables in a buffer memory. This behavior makes it possible, on the occasion, to write in this memory in order to make there carry out various orders - being able to involve until the complete compromising of the system so the aforementioned program is carried out with the rights root. The basic idea of libparanoia is never not to carry out new instructions following these functions if the stack were modified. One will then prefer to kill the process or to call a function of exit. The method can appear brutal but this supposes a corruption of the buffer memory of this program and, in this context, to block one moment the good course of a program or a single process appears much less serious than to risk the complete comprimission of the system. We install libparanoia by his port in/usr/ports/security/libparanoia. We then recommendons you to carry out the script Copy-to-libc which allows patcher directly the libc FreeBSD some is the version.

    ($:~)=> ./copy-to-libc

    The GCC Protector Patch consists, as for him, in a series of checking carried out directly by the GNU Compiler Collection during the compilation of programs. It draws part of its techniques from the work carried out for the patch StackGuard for Immunix OS, a distribution Slackware GNU/Linux reinforced by a series of patchs of safety. Thus, it uses a variable guard inserée just after the pointer of preceding screen. As this guard is higher in the pile than a table or a string likely to be diverted, it protects the arguments, the address return and the pointer of preceding screen. The value of this variable is random thus an attacker cannot calculate it to circumvent it.


                        |------------------------|
                        |       arguments        |
                        |------------------------|
                        |     return adress      |
                        |------------------------|
                        | previous frame pointer |
                        |------------------------|
                        |         guard          |
                        |------------------------|
                        |        arrays          |
                        |------------------------|
                        |     local variables    |
                        |------------------------|


    According to this model, the data in memory apart from a function cannot be damaged when the function turns over and the attacks on the pointers outwards or within the function do not pass because of the limitations of use of the pile. The GCC protector patch thus introduces here a model says Safety Protection Model of limitations of use of pile.

    All these protections run up of course against the limitations of the language C, for example one cannot protect a pointer being part of a structure also containing a table since réagencement is prohibited. Or, the use of the options of optimization of GCC can involve nonthe use of protections of the patch. However, the GCC Protector Patch remains an interesting option in the fight against the attacks by stack overflow. To install it and build FreeBSD with this protection, we must initially patcher GCC then build it indépendemment system.

    ($:~)=> cd /usr
    ($:~)=> patch -p1 < protector.patch

    ($:~)=> cd /usr/src/gnu/lib/libgcc
    ($:~)=> make depend && make all install clean

    ($:~)=> cd /usr/src/gnu/usr.bin/cc
    ($:~)=> make depend && make all install clean

    Then before carrying out the operations of recompiling of FreeBSD, we define the variable of environment CFLAGS indicating the options to be passed to the compiler

    ($:~)=> setenv CFLAGS=-O -pipe -fstack-protector

    It should be noted that the options - fstack-protector and its opposite - fnostack-protector last with GCC make it possible to activate or not the protection of the patch. We update the libc now.

    ($:~)=> cd /usr/src/lib/libc
    ($:~)=> make depend && make all install clean

    And we have nothing any more but with recompiler the world! This patch is valid since FreeBSD 4.3 and functions with the versions of GCC 2.95.2, 2.95.3 and 3.0. However, of the problems can appear with the compilation of a program not calling upon the variable of environment CFLAGS like XFree. More information with .http://www.trl.ibm.com/projects/security/ssp/.

    3.5. tunneling

    We now will study the various methods of tunneling available with FreeBSD. The tunneling enables us to encapsulate sometimes significant applicatives sessions like the handling of mail (POP/SMTP), the IRC, the navigation Web, ftp or any other transmission which can see passing from the passwords, within a crypté tunnel. We adopted 2 methods of them: OpenSSH and OpenSSL/Stunnel.

    Since the configuration of sshd higher, you must have OpenSSH of gold and already installed. We thus will satisfy we here to develop its options of tunneling. We carry out the following order

    ($:~)=> ssh -N -f -L localport:localhost:remoteport user@remotehost

    The option - N puts to us in tunnel only, the option - F makes it possible to make turn ssh in basic spot and - L allows preciser the data of the tunnel which are the local port then the distant port between which the tunnel will be carried out. It then does not remain any more but to return the distant host as usual. Once the established tunnel, any connection with like source the local port indicated in the tunnel and like destination the distant port indicated in the tunnel, will forward within tunnel SSH set up.

    The second solution consists to create and use tunnels SSL with stunnel, it is in particular the solution applied in the framework of IRCS, securized network IRC. With this intention, we need OpenSSL which is installed in the catalogue cvsup src-all and Stunnel which we will find in/usr/ports/security.

    ($:~)=> cd /usr/ports/security/stunnel && make install clean

    Then to launch a distant connection as a customer mode, we executons the following order

    ($:~)=> stunnel -c -d localhost:localport -r remotehost:remoteservice

    The option - C precise which we are as a customer mode carrying out a tunneling thus, and the option - R allows preciser the data of the distant host which are the distant address - which can be a IP or a field - and the distant service which can as well be a port as a name of service contained in/etc/services (while passing you can make a copier/coller since ).http://www.iana.org/assignments/port-numbers). You also can preciser a certificate allowing to authenticate the distant host (recommended) and the verifier by adding the options - v2 and - A path/to/certificat.pem.

    We now approach a last method of tunneling differing from the 2 preceding ones by its operation with bush-hammering OSI 3, and its capacity to be used for the installation of true Virtual Private Network between 2 distant LAN which one wants to rather join together by 2 IPSec footbridges - supposing that you diposez at the same time public and private address - than with a communication end-to-end. We thus now will study the configuration of the options of IPSec safety with IPv4. Under FreeBSD, we are used for ourselves to be made dual stack TCP/IP developed within the framework of the KAME project and which supports IPv6 and IPSec perfectly. You can obtain more information on KAME with .http://www.kame.net.

    We must first of all configure an interface GIF for the tunneling IPv6/4 over IPv6/4 in order to create the IPSec tunnel. Not to have to repair it with starting, add an entry ifconfig_gif0 to your rc.conf.

    ($:~)=> ifconfig create gif0
    ($:~)=> ifconfig gif0 tunnel localhost_public_IP remote_public_IP

    We use interface GIF so that it manages the tunnel between IP public and thus allows us to use our IP deprived for the configuration of the rules of coding. In this manner, the packages will be well routés on the level of the routing table of the kernel, and not via the SPD, according to a traditional forwarding path and connections appear in netstat. With GIF, it is possible to filter and sniffer on the level of interface GIF. Without GIF (i.e. by using the public addresses of the IPSec footbridges), there remains possible to filter on the private interfaces and possibly sniffer via rules tee.

    To use IPSec, the kernel handles 2 data bases to knowing Security Policy Database (SPD) which makes it possible to notemment define the implementing rules of the IPSec tunnel with the specification of associations of safety (SA); and Security Association Database (SAD) which contains the corresponding keys of SA. The administrator must first of all configure the policy SPD by the intermediare of the order setkey, the kernel refers then to the SPD to check if a package requires IPSec, if in fact the case, it uses SA specified in the SAD. In the event of error or of impossibility of obtaining the key, the kernel fact calls with the daemon IKE racoon will carry out the exchange of keys in order to normally allow SA by directly modifying the SAD. With a syntax and a use similar to ipfw, we use setkey to empty the databases before adding our news policy to it.

    ($:~)=> setkey -FP
    ($:~)=> setkey -F

    Then we enter our policy the SPD in the form
    action net_src net_dst upperspec -P direction action \
    protocol/mode/gw_src-gw_dst/level

    action can take as value: spdadd, spddelete or spdflush - this last correspondent with - FP. net_src and net_dst indicate the private addresses of the networks which one seeks to join together. uppersec indicates the protocols of the layer OSI 4 for which the rule applies. The field can be TCP, UDP or any. The option - P specifies the policy itself followed by the direction which can be in or out, of the action i.e. ipsec to apply ipsec, none to make a simple tunnel or discard to reject the package; follow-up of the protocol which can be ESP (Encapsulated Security Playload) thus offering confidentiality by encryption or AH (Header Authentification) offering the authentification, or finally IPCOMP. The integrity and the protéction against the rejeu of the data are ensured for ESP and AH. Ensuite comes the mode which can be transport in which IPSec intervenes between layer OSI 4 and 3 thus the final package uses clear IP addresses, or tunnel in which IPSec intervenes after layer OSI 3 by adding a header and by encryptant the totality of the package to the footbridge of destination. We have then the address of the footbridge source and of the footbridge of destination and to finish the level which can take the values default to use the variables kernel by defect, uses to use SA or to normally continue the transmission in the event of failure, or require to impose the use of SA. The first variables sysctl all are put at default, followed by an entry which enables us to reject (discard) the packages trying to use the VPN without IPSec because they do not correspond to the security policy. Then, we will paramètrons an entry sysctl allowing to force the renegotiation via Racoon following the loss of one of the 2 ends of the tunnel (by depreciating old SA). Lastly, we activate compatibility Explicit Congestion Notification for IPSec with the following treatment: with the encapsulation the ToS bits are copied except ECN EC, with the decapsulation, the ToS bits are copied but if ECN EC is present, it is copied with the decapsulé package.


    ($:~)=> sysctl -w net.inet.ipsec.esp_trans_deflev=1
    ($:~)=> sysctl -w net.inet.ipsec.esp_net_deflev=1
    ($:~)=> sysctl -w net.inet.ipsec.ah_trans_deflev=1
    ($:~)=> sysctl -w net.inet.ipsec.ah_net_deflev=1
    ($:~)=> sysctl -w net.inet.ipsec.def_policy=0
    ($:~)=> sysctl -w net.key.prefered_oldsa=0
    ($:~)=> sysctl -w net.inet.ipsec.ecn=1

    ($:~)=> setkey -c << EOF
    spdadd internal_net/24 remote_internal_net/24 any -P out ipsec
           esp/tunnel/localhost_public_IP-remote_public_IP/default;
    spdadd remote_internal_range/24 internal_range/24 any -P in ipsec
           esp/tunnel/remote_public_IP-localhost_public_IP/default;


    Now that our IPSec tunnel is ready to be useful, it remains us to configure Racoon in order to ensure the exchange of the symmetric keys and SAs. to obtain our configuration IPSec, we modify rc.conf to carry out setkey with starting with the file ipsec.conf in argument.

    ...
    ipsec_enable="YES"
    ipsec_file="/etc/ipsec.conf"
    ...


    flush
    spdflush

    # SAD entry
    # SA AH avec cle 160 bits
    add localhost_public_IP remote_public_IP ah 1500 -A hmac-sha1 123ABC456EFG789HIJ10
    add remote_public_IP localhost_public_IP ah 1600 -A hmac-sha1 123ABC456EFG789HIJ10
    # SA ESP avec cle 128 bits
    add localhost_public_IP remote_public_IP esp 1500 -E blowfish-cbc 123ABC456EFG789H
    add remote_public_IP localhost_public_IP esp 1600 -E blowfish-cbc 123ABC456EFG789H

    # SPD entry
    spdadd internal_net/24 remote_internal_net/24 any -P out ipsec
           esp/tunnel/localhost_public_IP-remote_public_IP/default;
    spdadd remote_internal_range/24 internal_range/24 any -P in ipsec
           esp/tunnel/remote_public_IP-localhost_public_IP/default;


    We then define for the configuration of racoon a file psk.txt containing the keys used for the identification in the first phase of the exchange of keys.


    ($:~)=> cat /etc/racoon/psk.txt
    remote_public_IP    shared_key


    Then we deal with racoon.conf itself which we publish starting from the file of configuration by defect.

    ($:~)=> cp /usr/local/etc/racoon/racoon.conf.dist /etc/racoon.conf
    ($:~)=> ee racoon.conf


    path pre_shared_key "/etc/racoon/psk.txt" ;
    path certificate "/usr/local/openssl/certs/";

    # Padding options
    padding
    {
        maximum_length 20;
        randomize off;
        strict_check on;
        exclusive_tail off;
    }

    # Timing Options.  They can be modified by the distant host.
    timer
    {
        counter 5;
        interval 10 sec;
        persend 1;
        phase1 1 min;
        phase2 30 sec;
    }

    # Phase 1. anonymous means that this phase is applied to all the hosts.  
    # You can configure phases 1 and 2 for particular hosts.
    remote anonymous
    {
        exchange_mode main,aggressive ;
        # mode of negotiation, aggressive is faster, but hand offers
        # a mechanism of cookie, the protéction of identity and the fixing of
        # Diffie-Hellman group id
        doi ipsec_doi;
        situation identity_only;
        nonce_size 16;
        lifetime time 1 min;    # sec,min,hour
        lifetime byte 2 MB;     # B,KB,GB
        initial_contact on;
        proposal_check obey;    # obey, strict or claim
        #support_mip6 on; # support of Mobile IPv6 (cf snapshots KAME)

        proposal
        {
            encryption_algorithm blowfish;
            hash_algorithm sha1;
            authentication_method pre_shared_key ;
            # group Diffie-Hellman
            dh_group 2 ;
        }
    }

    # Phase 2.
    sainfo anonymous
    {
        pfs_group 2;
        lifetime time 2 hour ;
        lifetime byte 100 MB ;
        encryption_algorithm 3des, blowfish, rijndael, twofish ;
        authentication_algorithm hmac_sha1, hmac_md5 ;
        # compression IPCOMP
        compression_algorithm deflate ;
    }


    You can also use for more safety of the certificates to format PEM instead of psk always prone to the rough force. The use of the certificates of the X.509v3 type supported by racoon enables us to remain perfectly interopérable in conformity with standard PKIX. We will need openssl which is in the FreeBSD base to generate a prive/public pair of keys then a certificate to be signed.

    Let us start by generating our pair of keys RSA to 1024 bits and stored with format PEM (Privacy Enhanced Mail).

    ($:~)=> openssl genrsa -out privkey.pem 1024

    Once this (long) finished operation, the following order enables us to carry out a request PKCS#10 of certification of a public key and a distinguished name even of certain numbers of attributes (see RFC 2986).

    ($:~)=> openssl req -new -nodes -newkey rsa:1024 -sha1 -keyform PEM -keyout
            privkey.pem -outform PEM -out request.pem


    This starts a procedure similar to that of adduser where it will be necessary for you to answer certain fields which will define your certificate. We must now make always sign this certificate either by an authority of certification by sending the result of request PKCS#10 to him or by signing it ourself to the assistance openssl with following syntax

    ($:~)=> openssl x509 -req -in request.pem -signkey privkey.pem -out cert.pem

    We obtain thus the certificate cert.pem with format PEM stored in
    /usr/local/openssl/certs/.

    Maintaining to use the certificates instead of psk, we will have to carry out some modifications of racoon.conf. First of all in the section remote, we must place

    ...
    certificate_type x509 "certificat" "cle_privee";
    my_identifier user_fqdn "cns@minithins.net";
    ...

    Thus specifying the use of X.509 certificates then the certificate and the private key, with going to seek in the definite path openssl at the beginning of racoon.conf. My_identifier is the single name used during the request. Then in the section proposal, we place

    ...
    authentication_method rsasig;
    ...

    Indicating the method of authentification, which is signature RSA here, the only available one with X.509 certification for the moment.

    We add finally an entry in the crontab so that racoon launches out to each reboot or we can place a script launching racoon in
    /usr/local/etc/rc.d/.

    4. Conclusion

    Veiled, this paper from now on is finished. You must now be in possession of a FreeBSD machine configured so as to largely reduce the risks of intrusion or compromising. However never forget that absolute safety is not EC world, all that we can do is to manage the risk and to put the most possible sticks in the wheels of the attacker. Ridges also very attention with all the relations of confidence which you establish with distant hosts. Indeed, via what is called the contamination by metastases, you could quickly be compromised if you do not pay any attention to your connections and that you always rely on no matter whom. Remember finally that safety cannot be summarized with a program or a single technique, it is a chain of process whose no link is sure at 100% what gives us with the theorie linear systems an extremely fragile process. The goal is to return the task of possible intruder the most difficult.

    -------------------------------------------------------------------------------

    Copyright (c) 2001,2002,2003 CNS

    Free Document Dissemination Licence -- FDDL version 1
    http://pauillac.inria.fr/~lang/licence/v1/fddl.html

    This document may be freely read, stored, reproduced, disseminated, translated
    or quoted by any means and on any medium provided the following conditions are
    met:

  • every reader or user of this document acknowledges that he his aware that no guarantee is given regarding its contents, on any account, and specifically concerning veracity, accuracy and fitness for any purpose;
  • no modification is made other than cosmetic, change of representation format, translation, correction of obvious syntactic errors, or as permitted by the clauses below;
  • comments and other additions may be inserted, provided they clearly appear as such; translations or fragments must clearly refer to an original complete version, preferably one that is easily accessed whenever possible;
  • translations, comments and other additions must be dated and their author(s) must be identifiable (possibly via an alias);
  • this licence is preserved and applies to the whole document with modifications and additions (except for brief quotes), independently of the representation format;
  • whatever the mode of storage, reproduction or dissemination, anyone able to access a digitized version of this document must be able to make a digitized copy in a format directly usable, and if possible editable, according to accepted, and publicly documented, public standards;
  • redistributing this document to a third party requires simultaneous redistribution of this licence, without modification, and in particular without any further condition or restriction, expressed or implied, related or not to this redistribution. In particular, in case of inclusion in a database or collection, the owner or the manager of the database or the collection renounces any right related to this inclusion and concerning the possible uses of the document after extraction from documents.

    Any incompatibility of the above clauses with legal, contractual or judiciary decisions or constraints implies a corresponding limitation of reading, usage, or redistribution rights for this document, verbatim or modified.