FreeBSD

From IdefixWiki

Jump to: navigation, search

Contents

Filessystems

Filessystems

Apache

Apache

Cups

Cups

Setting up Awstats

Awstats

Courier IMAP

Currier-Imap

Dovecot IMAP

Dovecot-Imap

Sendmail

Sendmail

Exim

Exim

LDAP

LDAP

Asterisk

Asterisk

Ports

Downgrade a port

Define in the /etc/make.conf

# the default cvs server for portdowngrade
DEFAULT_CVS_SERVER=":pserver:anoncvs@anoncvs2.de.FreeBSD.org:/home/ncvs"

and install

sysutils/portdowngrade

Create an own Port

See [1]]

Web-Dav

Load the following modules in apache2

LoadModule dav_module         libexec/apache2/mod_dav.so
LoadModule dav_fs_module      libexec/apache2/mod_dav_fs.so

Configure WebDav:

<IfModule mod_dav.c>
  DavLockDB     /var/db/DAV/DAVLock
  BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully
  BrowserMatch "Microsoft Data Access Internet Publishing Provider"  redirect-carefully
  BrowserMatch "Microsoft-WebDAV-MiniRedir/5.1.2600" redirect-carefully
  BrowserMatch "^WebDrive" redirect-carefully
  BrowserMatch "^WebDAVFS" redirect-carefully
  BrowserMatch "^gnome-vfs" redirect-carefully
</IfModule>

Create the directory and set permissions:

mkdir -p /var/db/DAV/
chown www /var/db/DAV/
chgrp html /var/db/DAV/
chmod 775 /var/db/DAV/

Create a directory and set the privileges for the webserver

mkdir /usr/home/http/default/htdocs/dav
chown idefix dav
chgrp html dav
chmod g+w dav

Create the htdigest password file with:

htdigest -c filename realm username

where realm is "DAV password required".

Add the following lines to the apache2 configuration:

 <Location /dav>
  DAV On
  AllowOverride AuthConfig
  AuthType Digest
  AuthName "DAV password required"
  AuthDigestDomain /dav/

  AuthDigestFile /usr/home/http/htdigest_passwd_dav
  Require valid-user

  order allow,deny
  allow from all
  Options Indexes Includes FollowSymLinks
 </Location>

Create calendar for Sunbird

Go to the directory where the calendar should be saved and type:

echo "BEGIN:VCALENDAR" > private.ics
echo "END:VCALENDAR" >> private.ics

Configure Calendar or Sunbird with the URL

http://server/calendar/private.ics

Jails

[2]
[3]

Introduction

Jails are a great way to secure your processes to a virtual system. Though they have more overhead than chroot, (which basically just restricts the root of a process) a jail uses a virtual machine to house your process or processes. This means that far more restrictions can be placed on the jail, and there's no "breaking out" as can be done with chroot (see links in references).

A few notes first of all. It's very true what they say in the man page about it being easier to make a fat jail, and scale down to a thin one than vice versa. A few weeks of research (and many make worlds) have helped me discover that.

Also note that as of FreeBSD 5.4 (and likely 6.0) there is no IPv6 support for jails. This is unfortunate because jails tend to monopolize address space after making quite a few of them and address space is what IPv6 is all about. Sure there's NAT but everyone knows NAT is an ugly hack these days. I can only hope that IPv6 will be supported soon.

Jail Creation Techniques

From what I've seen there are three primary ways of creating jails.

MiniBSD

I've heard reports of people using MiniBSD to do this, but I haven't had much luck with it, and I have yet to see a howto explaining how they made it work, it's a great idea of making an initial thin jail but there's a million things that can go wrong since it's very minimal and the service(s) you are trying to run may have dependancy issues.

Using /stand/sysinstall

Other howtos tell to use /stand/sysinstall to go out to the net, download the system binaries, and install specific distributions from the installer. I've had little luck with this as well since you run into the problem of not having an interface set up for the installer to use. There's probably a way to do this but none of the howtos I tried did a very good job of explaining how.

Using make world

This is the way I'll use here in this tutorial and the way explained in the manpage. You can customize the make file to scale down your distribution and set some optomization flags for your system. The primary drawback is the time it takes to build the world which can be hours depending on your system.

Getting services to not listen to *

First off, we should make sure we get the system so that we have nothing listening on *, to check what what we need to modify issue this command

sockstat|grep "\*:[0-9]"

This should give you a synopsys of all the processes and ports you need to trim down. Here are some hints with your ipv4 addr being 10.0.0.1 and your ipv6 addr being 2002::7ea9

sshd:

  • edit /etc/ssh/sshd_config
  • change ListenAddress derivative
ListenAddress 10.0.0.1
ListenAddress 2002::7ea9

httpd

  • edit /usr/local/etc/apache/httpd.conf (and ssl.conf for https)
  • change Listen derivative
Listen 10.0.0.1:80
Listen [2002::7ea9]:80

slapd

  • edit /etc/rc.conf
  • change slapd_flags
slapd_flags='-h "ldapi://%2fvar%2frun%2fopenldap%2fldapi/ ldap://10.0.0.1/ ldap://127.0.0.1/ ldap://[2002::7ea9]/"'

inetd

  • edit /etc/rc.conf
  • change inetd_flags=
inetd_flags="-wW -a yourhost.example.com"

mysql

  • edit /etc/my.cnf
bind-address=10.0.0.1

postfix edit /usr/local/etc/postfix/main.cf

  • change inet_interfaces
inet_interfaces = [2002::7ea9], 10.0.0.242

samba (this will get you most of the way there)

  • edit /usr/local/etc/smb.conf
  • change the following:
interfaces = 10.0.0.242/24 127.0.0.1
socket address = 10.0.0.242
bind interfaces only = yes

note: if you don't need wins lookups and netbios name translation

    you can safely disable nmbd. There doesn't seem to be a way
    for nmb to not listen to *:138 anyhow.

To disable nmb go to /etc/rc.conf and replace samba_enable="YES" with smbd_enable="YES"

openntpd (xntpd listens on all and cannot be changed)

*edit /usr/local/etc/ntpd.conf
listen on 10.0.0.1
listen on 2002::7ea9

syslogd

*edit /etc/rc.conf
syslogd_flags="-s -s" #For no listening
syslogd_flags="-a 10.0.0.1"

bind

  • edit your named.conf (may be in /var/named/etc/named.conf)
  • In the options section:
listen-on { 10.0.0.242; };
listen-on-v6 port 53 { 2002:d8fe:10f1:6:202:b3ff:fea9:7ea9; };
query-source address 10.0.0.242 port *;
query-source-v6 address 2002:d8fe:10f1:6:202:b3ff:fea9:7ea9 port *;

Unrealircd

  • In the listen section:
listen[::ffff:10.0.0.1]:6667
listen[2002::7ea9]:6667
  • In the "set { dns {" section
bind-ip 10.0.0.242;

Building your jail for the first time

Creating an appropriate make.conf

You'll need to run make world (or make installworld) to create your jail. If you don't want to install the whole kitchen sink you can use the make.conf below. You can put it in your jail for future use and it'll be used by future port builds inside your jail. One thing I've noticed is that make installworld doesn't seem to respect and MAKE_CONF or __MAKE_CONF variables passed to it so we'll just put it in /etc/make.conf for now.

Lets first back our current make.conf up:

cp /etc/make.conf /etc/make.conf.bak

And new one in there. Keep in mind, depending on what you want to use this jail for you may want to modify this make.conf. For me this has worked on building a variety of services from ports (inside the jail). I like to name the below file make.conf.jail and copy it to make.conf, then copy make.conf.bak back to make.conf when I'm done building the jail.

NO_ACPI=       true    # do not build acpiconf(8) and related programs
NO_BOOT=       true    # do not build boot blocks and loader
NO_BLUETOOTH=  true    # do not build Bluetooth related stuff
NO_FORTRAN=    true    # do not build g77 and related libraries
NO_GDB=        true    # do not build GDB
NO_GPIB=       true    # do not build GPIB support
NO_I4B=        true    # do not build isdn4bsd package
NO_IPFILTER=   true    # do not build IP Filter package
NO_PF=         true    # do not build PF firewall package
NO_AUTHPF=     true    # do not build and install authpf (setuid/gid)
NO_KERBEROS=   true    # do not build and install Kerberos 5 (KTH Heimdal)
NO_LPR=        true    # do not build lpr and related programs
NO_MAILWRAPPER=true    # do not build the mailwrapper(8) MTA selector
NO_MODULES=    true    # do not build modules with the kernel
NO_NETCAT=     true    # do not build netcat
NO_NIS=        true    # do not build NIS support and related programs
NO_SENDMAIL=   true    # do not build sendmail and related programs
NO_SHAREDOCS=  true    # do not build the 4.4BSD legacy docs
NO_USB=        true    # do not build usbd(8) and related programs
NO_VINUM=      true    # do not build Vinum utilities
NOATM=         true    # do not build ATM related programs and libraries
NOCRYPT=       true    # do not build any crypto code
NOGAMES=       true    # do not build games (games/ subdir)
NOINFO=        true    # do not make or install info files
NOMAN=         true    # do not build manual pages
NOPROFILE=     true    # Avoid compiling profiled libraries

# BIND OPTIONS
NO_BIND=               true    # Do not build any part of BIND
NO_BIND_DNSSEC=        true    # Do not build dnssec-keygen, dnssec-signzone
NO_BIND_ETC=           true    # Do not install files to /etc/namedb
NO_BIND_LIBS_LWRES=    true    # Do not install the lwres library
NO_BIND_MTREE=         true    # Do not run mtree to create chroot directories
NO_BIND_NAMED=         true    # Do not build named, rndc, lwresd, etc.

Building the Jail

Now for actually building your jail...

I'm defining JAILDIR here because I'm going to use it in a shellscript style example throughout the rest of this howto.

# Let's first make some directories
JAILDIR=/home/jail
mkdir -p $JAILDIR/dev
mkdir -p $JAILDIR/etc
mkdir -p $JAILDIR/usr/tmp
chmod 777 $JAILDIR/usr/tmp

cd /usr/src/

# You can replace the below with make installworld if you've built your
# world previously
make buildworld
make installworld DESTDIR=$JAILDIR
cd /usr/src/etc
cp /etc/resolv.conf $JAILDIR

make distribution DESTDIR=$JAILDIR NO_OPENSSH=YES NO_OPENSSL=YES
cd $JAILDIR

# At this point we'll mount devfs, and then hide the unneeded devs
mount_devfs devfs $JAILDIR/dev
devfs -m $JAILDIR/dev rule -s 4 applyset

# Create a null kernel
ln -s dev/null kernel

# Quell warnings about fstab
touch $JAILDIR/etc/fstab

# Use our existing resolv.conf
cp /etc/resolv.conf $JAILDIR/etc/resolv.conf

# Copy our settings for ssl
mkdir -p $JAILDIR/etc/ssl
mkdir -p $JAILDIR/usr/local/openssl
cp /etc/ssl/openssl.cnf $JAILDIR/etc/ssl
cd $JAILDIR/usr/local/openssl/
ln -s ../../../etc/ssl/openssl.cnf openssl.cnf

Make a decent rc.conf:

hostname="jail.example.com"    # Set this!
ifconfig_em0="inet 10.0.0.20 netmask 255.255.255.255"
defaultrouter="10.0.0.1"        # Set to default gateway (or NO).
clear_tmp_enable="YES"  # Clear /tmp at startup.
# Once you set your jail up you may want to consider adding a good securelevel:
# Same as sysctl -w kern.securelevel=3
kern_securelevel_enable="YES"    # kernel security level (see init(8)),
kern_securelevel="3"

You'll also want to make an alias on your interface for the ip above so we'll do something like:

ifconfig em0 10.0.0.20 netmask 255.255.255.255 alias

Now you'll want to have devfs inside your jail, so to get it working for the first time do this:

mount_devfs devfs $JAILDIR/devfs

And finally, copy your original make.conf back.

cp /etc/make.conf.bak /etc/make.conf

Starting the jail for the first time

OPTIONAL (but probably necessary): You'll want to mount /usr/ports and /usr/src so you can install ports inside your jail, unless you have another way you want to do this (such as downloading packages).

mount_nullfs /usr/ports $JAILDIR
mount_nullfs /usr/src $JAILDIR

Now we can start our jail

jail $JAILDIR jail.example.com 10.0.0.20 /bin/sh

Once inside the jail you'll want to start services:

/bin/sh /etc/rc

While you're here you'll want to edit your password file since if someone breaks into your jail, and starts cracking it you won't want them to have the same passwords as your root system has. Also remove all users you don't need in the jail:

vipw
passwd root

From here, assuming all went well you can do something like:

cd /usr/ports/security/openssh
make install clean

And build your port(s) inside your jail. Once you're finished be sure to unmount the directories so a compromised jail can't build more ports.


If you have trouble getting your programs to start inside your jail you can use the methods I outlined in [Chrooting_an_Eggdrop#Figuring_out_what_eggdrop_needs | my chroot tutorial]]. I've verifed that truss works correctly in a jail so between ldd and truss you should be set.

Also note that if you try to start your jail with just:

jail $JAILDIR jail.example.com 10.0.0.20 /bin/sh /etc/rc

but you have no services/daemons/programs set to run, the jail will simply start and then exit since there's nothing running inside.

Getting it to start automatically

You'll now need to put your settings in /etc/rc.conf First put the alias you jail has in there:

ifconfig_em0_alias0="inet 10.0.0.20 netmask 0xffffffff"

Editing the rc.conf

For those of you that are looking to make your own rc script, I don't recommend it. I've found issues getting devfs rules to be applied with the a script, and really this way is much easier. It's also the standard way and you can attach to jails later on quite easily without using screen (read below).

Here's the standard rc.conf way of getting your jail to run at startup:

jail_enable="YES"        # Set to NO to disable starting of any jails
jail_list="cell"            # Space separated list of names of jails
jail_set_hostname_allow="NO" # Allow root user in a jail to change its hostname
jail_socket_unixiproute_only="YES" # Route only TCP/IP within a jail

jail_cell_rootdir="/usr/home/prison/cell"
jail_cell_hostname="cell.example.com"
jail_cell_ip="10.0.0.20"
jail_cell_exec_start="/bin/sh /etc/rc"
jail_cell_devfs_enable="YES"
jail_cell_devfs_ruleset="devfsrules_jail"

Jail maintenance

Of course from time to time you may have to upgrade ports in your jail, or the world in the jail itself. This isn't a big deal either. Instead of using jail (which makes its own IP address and everything) we can use chroot instead which is similar since all we're using is a simple shell and then we'll be done with it.

First mount the dirs so they're accessable in the chroot:

mount_nullfs /usr/ports $JAILDIR
mount_nullfs /usr/src $JAILDIR

Connect to your jail: find the jail id of the jail you are running with jls:

#jls
   JID  IP Address      Hostname                      Path
    1  10.0.0.20       cell.example.com              /usr/home/prison/cell

Now connect to it using the JID:

jexec 1 /bin/sh

To upgrade your world:

cd /usr/src
make buildworld
make installworld

NOTE: If you've just done make buildworld previously you can do make installworld and install all the newly compiled binaries again.

To build a port:

cd /usr/ports/sysutils/example
make install clean

NOTE: You may also want to install portupgrade to make port management easier.

When you're done just exit:

exit

Integrating Portaudit

You'll notice that portaudit security check only checks the root server, but none of the jails. There are many ways around this, but here's one:

Create a shell script in a place you keep custom shell scripts. We'll use /root/bin/metaportaudit.sh

#!/bin/sh

JAILDIR=/usr/home/prison/
JAILS="irc www mysql"
TMPDIR="/tmp"

# First lets audit the root server
/usr/local/sbin/portaudit -a

# Now Lets create temp files of ports in the jails,
# audit the root server all jails
# and delete the temp files
cd $TMPDIR
for jail in $JAILS; do
  echo ""
  echo "Checking for packages with security vulnerabilities in jail \"$jail\":"
  echo ""
  ls -1 $JAILDIR/$jail/var/db/pkg > $TMPDIR/$jail.paf
  /usr/local/sbin/portaudit -f $TMPDIR/$jail.paf
  rm $TMPDIR/$jail.paf
done

Now lets edit /usr/local/etc/periodic/security on about line 55 you'll want to change:

echo
echo /usr/local/sbin/portaudit -a |
         su -fm "${daily_status_security_portaudit_user:-nobody}" || rc=$?

to

echo
echo /root/bin/metaportaudit.sh -a |
         su -fm "${daily_status_security_portaudit_user:-nobody}" || rc=$?

Jails in Linux

Now you may think "well I have to use Linux, because xapplication only works on Linux! Well there's hope. You can mess around with the bsdjail patch (http://kerneltrap.org/node/3823), or you can install vserver (which has packages in Debian). There's a great tutorial on vserver in Debian here: Running_Vservers_on_Debian

Null-FS

For 6...

/etc/rc.conf:

        jail_sandbox_rootdir="/local/jails/sandbox/"
        jail_sandbox_hostname="sandbox.pjkh.com"
        jail_sandbox_ip="123.123.123.123"
        jail_sandbox_exec="/bin/sh /etc/rc"
        jail_sandbox_devfs_enable="YES"
        jail_sandbox_mount_enable="YES"

/etc/fstab.sandbox:

        /usr/ports /local/jails/sandbox/usr/ports nullfs rw 0 0

Then once started with /etc/rc.d/jail start sandbox I have this:

% df -h

Filesystem     Size    Used   Avail Capacity  Mounted on
...
devfs          1.0K    1.0K      0B   100%    /local/jails/sandbox/dev
/usr/ports     3.9G    1.9G    1.7G    52%    /local/jails/sandbox/usr/ports

I also came across this afterward... which I might give a go...

http://www.freebsd.org/cgi/url.cgi?ports/sysutils/ezjail/pkg-descr

Looks like it null mounts a lot more (ie /bin /sbin, /usr/lib, etc.)

Examples

I basically set up

/local/jails/master and install according to man jail into this place. I never start this jail.

I happen to use disk backed md devices as the root for each jail. I mount each on on /local/jail/<jailname>

Then I do

/sbin/mount_nullfs -o ro /local/jails/master/bin /local/jails/adcmw/bin
/sbin/mount_nullfs -o ro /local/jails/master/lib /local/jails/adcmw/lib
/sbin/mount_nullfs -o ro /local/jails/master/libexec /local/jails/adcmw/libexec
/sbin/mount_nullfs -o ro /local/jails/master/sbin /local/jails/adcmw/sbin
/sbin/mount_nullfs -o ro /local/jails/master/usr /local/jails/adcmw/usr
/sbin/mount -t procfs proc /local/jails/adcmw/proc
devfs_domount /local/jails/adcmw/dev devfsrules_jail
devfs_set_ruleset devfsrules_jail /local/jails/adcmw/dev
/sbin/devfs -m /local/jails/adcmw/dev rule -s 4 applyset

In my master jail I have some symlinks so that each jail has its own / usr/local/ that is writable.

Memory disk

Create a 4 MB memory disk

mdconfig -a -t malloc -s 4m
newfs -U /dev/md0
mount /dev/md0 /mnt

PXE-Boot

http://www.freebsd.org/doc/en_US.ISO8859-1/articles/pxe/index.html, http://www.daemonsecurity.com/pxe/jumpstart.html and http://www.daemonsecurity.com/pxe/diskless.html

and http://www.daemonsecurity.com/pub/pxeboot/

http://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/network-diskless.html


Autoinstall

To setup PXEBoot to autoinstall a FreeBSD:

# mdconfig -a -t vnode -f kern.flp -u 0 # (vnconfig vn0 kern.flp) associate a vndevice with the file
# mount /dev/md0 /mnt/test # (mount /dev/vn0 /mnt) mount it
# cp -R /mnt /usr/tftp/boot # copy the contents to /usr/tftpboot
# umount /mnt              # unmount it
# mdconfig -d -u 0         # disassociate the vndevice from the file

# mdconfig -a -t vnode -f mfsroot.flp -u 0
# mount /dev/md0 /mnt/test              # mount it
# cp /mnt/test/mfsroot.gz /usr/tftp/boot # copy the contents to /usr/tftp/boot
# umount /mnt/test                     # unmount it
# mdconfig -d -u 0                  # disassociate the vndevice from the file
# cd /usr/tftp/boot                 # get into the pxeboot directory
# gunzip mfsroot.gz                # uncompress the mfsroot

# cd /usr/tftp/boot
# mdconfig -a -t vnode -f mfsroot -u 0
# mount /dev/md0 /mnt/test
# cp /root/install.cfg /mnt/test
# umount /mnt/test
# mdconfig -d -u 0

Diskless client

Make a diskless client:

Building the base system

# cd /usr/src
# make buildworld
# make DESTDIR=/usr/local/diskless/FreeBSD installworld
# make DESTDIR=/usr/local/diskless/FreeBSD distribution

Building a custom kernel

# cd /usr/src/sys/i386/conf
# cp GENERIC DISKLESS

Add the following lines to the kernel configuration:

# Filesystems
options         PSEUDOFS        # Pseudo-filesystem framework
options         NFSCLIENT       # NFS filesystem support
options         NFS_ROOT        # NFS is a posible root device

# Memory pseudo devices
device          mem             # Memory and kernel memory devices
device          md              # Memory "disks"

# NETWORKING OPTIONS
options         BOOTP           # BOOTP is only needed to get hostname 

Now build the kernel with

# cd /usr/src
# make KERNCONF=DISKLESS buildkernel

Installing the boot files:

# mkdir -p /usr/local/diskless/FreeBSD/boot/defaults
# cp /boot/defaults/loader.conf /usr/local/diskless/FreeBSD/boot/defaults/
# cp /usr/src/sys/boot/i386/loader/loader.rc /usr/local/diskless/FreeBSD/boot/
# cp /usr/src/sys/i386/conf/GENERIC.hints /usr/local/diskless/FreeBSD/boot/device.hints

Install the kernel:

# make KERNCONF=DISKLESS DESTDIR=/usr/local/diskless/FreeBSD installkernel

Installing tftp

Copy the files:

# cp /usr/local/diskless/FreeBSD/boot/pxeboot /usr/local/tftp/boot/

Enable tftp in the inetd.conf

tftp    dgram   udp wait    nobody  /usr/libexec/tftpd  tftpd -l -s /usr/local/tftp

Setting up dhcp server

Put the following lines into the dhcpd.conf:

filename "boot/pxeboot";
subnet 192.168.0.0 netmask 255.255.255.0 {
     next-server 192.168.0.251;
     option root-path "192.168.0.251:/usr/local/diskless/FreeBSD";
}

Setting up the NFS server

Edit the /etc/exports and add the following lines:

# for pxe boot
#/usr/local/diskless/FreeBSD    -alldirs    -ro
/usr    -alldirs    -ro

Disable ACPI

Edit the file /usr/local/diskless/FreeBSD/boot/loader.conf.local:

verbose_loading="YES"            # Set to YES for verbose loader output
autoboot_delay=2
hint.acpi.0.disabled="1"

If you boot the diskless system now, it should load the kernel and boot up to the login prompt with some error messages.

Configure the diskless client

At first we chroot to avoid confusion about pathes:

# cd /usr/local/diskless
# chroot FreeBSD/

To enable syslog edit /etc/rc.conf:

syslogd_enable="YES"            # Run syslog daemon (or NO).

Edit /etc/syslog.conf and put only these lines into it:

*.err;kern.warning;auth.notice;mail.crit        /dev/console
*.*                                             @server.idefix.loc

After the @ put the hostname which should receive the logs.

Disable cron and enable ntp for time syncronization, edit /etc/rc.conf:

cron_enable="NO"                # Run the periodic job daemon.
ntpdate_enable="YES"            # Run ntpdate to sync time on boot (or NO).
ntpdate_hosts="192.168.0.251"   # ntp server to use for ntpdate

Configure the filesystems in the file /etc/fstab:

# Device                                   Mount  FStype  Options       Dump  Pass#
192.168.0.251:/usr/local/diskless/FreeBSD  /      nfs     ro            0     0
192.168.0.251:/usr/home                    /home  nfs     rw,userquota  0     0
proc                                       /proc  procfs  rw            0     0

To enable /tmp and /var as ram drive add to /etc/rc.conf:

tmpmfs="YES"       # Set to YES to always create an mfs /tmp, NO to never
varmfs="YES"       # Set to YES to always create an mfs /var, NO to never

Creating the HOME directory:

mkdir /home

Set password for root account:

passwd root

Create a useraccount:

adduser

Exit from the chroot.

Installing software

Mount the porttree via nullfs to /usr/local/diskless/FreeBSD:

# mount_nullfs /usr/ports/ /usr/local/diskless/FreeBSD/usr/ports

To get all software installed correctly mount /dev into the chroot environment:

# mount -t devfs devfs /usr/local/diskless/FreeBSD/dev

Now chroot with:

# cd /usr/local/diskless
# chroot FreeBSD/

and install cvsup at first.

After installing required software with the port-tree unmount the devfs again with:

# umount /usr/local/diskless/FreeBSD/dev

Firewall PF

Enable PF

To enable pf insert the following lines in your kernel configuration and compile the kernel:

# needed for new packetfilter pf
device          pf                      # required
device          pflog           # optional
device          pfsync          # optional

# enable QoS from pf
options         ALTQ
options         ALTQ_CBQ        # Class Bases Queuing (CBQ)
options         ALTQ_RED        # Random Early Detection (RED)
options         ALTQ_RIO        # RED In/Out
options         ALTQ_HFSC       # Hierarchical Packet Scheduler (HFSC)
options         ALTQ_PRIQ       # Priority Queuing (PRIQ)
#options         ALTQ_NOPCC      # Required for SMP build

Realtime logging

tcpdump -n -e -ttt -i pflog0
tcpdump -A -s 256 -n -e -ttt -i pflog0

View Ruleset

pfctl -sr

Block SSH-Bruteforce attacks

Install:

security/bruteforeceblocker (requires pf as the firewall)
or
security/denyhosts (uses tcp_wrappers and /etc/hosts.allow)
or
security/sshit (requires ipfw as firewall)

or http://www.pjkh.com/wiki/ssh_monitor

Use pf:

If using pf, you can write rules like (original is one line):

  pass in on $ext_if proto tcp from any to $ext_if port $tcp_login
flags
  S/SA keep state (max-src-conn-rate 6/25, overload <bad_hosts>
  flush global)

The rule follows traffic in ssh port (aliased $tcp_login in my config)
and in this case if the connection attempts exceed 6 in 25 seconds,
the offending IP is moved into "bad_hosts" table and ruleset is
flushed to get the blocking effective. The conn attempt/time ratio can
be about anything, I've found the one used good enough.

Then in the top of ruleset I have the following (the filtering rule
from above is further down):

  block in quick on $ext_if from <bad_hosts>

The bad host table is initialised in my ruleset like this:

  table <bad_hosts> persist { }

Just remeber to put it into right section of pf.conf.

http://www.daemonsecurity.com/pub/src/tools/cc-cidr.pl

Recent BSDs (all of them, FreeBSD 5.n/6.n included) have PF in the base system.
'overload' rules are fairly easy to set up, eg

table <bruteforce> persist

#Then somewhere fairly early in your rule set you set up to block from the bruteforcers

block quick from <bruteforce>

#And finally, your pass rule.

pass inet proto tcp from any to $localnet port $tcp_services \
        flags S/SA keep state \
        (max-src-conn 100, max-src-conn-rate 15/5, \
         overload <bruteforce> flush global)

for more detailed discussion see eg http://www.bgnett.no/~peter/pf/en/bruteforce.html

ALTQ

To reduce priority for traffic:

altq on $ext_if cbq bandwidth 10Mb queue { def, mostofmybandwidth, notalot }
     queue def bandwidth 20% cbq(default borrow red)
     queue mostofmybandwidth 77% cbq(default borrow red) { most_lowdelay, most_bulk }
     queue most_lowdelay priority 7
     queue most_bulk priority 7
     queue notalot 3% cbq
[...]
block all
pass from $localnet to any port $allowedports keep state queue mostofmybandwidth
pass from $iptostarve to any port $allowedports keep state queue notalot

Mailman

Add a new list

Execute the following command:

cd /usr/local/mailman
bin/newlist -u fechner.net -e fechner.net -l de listname

Mgetty+Sendfax

Fax to Email Gateway

Copy the files in Image:Faxtools.tar.bz2 to /usr/local/lib/mgetty+sendfax.

Edit /usr/local/etc/mgetty+sendfax/mgetty.config:

port cuad1
debug 6
fax-id +49 8141 xxxxxxxx
speed 38400
direct NO
blocking NO
port-owner uucp
port-group uucp
port-mode 0660
toggle-dtr YES
toggle-dtr-waittime 500
data-only NO
fax-only NO
modem-type auto
init-chat "" ATS0=0Q0&D3&C1 OK ATM0 OK
modem-check-time 3600
rings 1
answer-chat "" ATA CONNECT \c \r
answer-chat-timeout 80
autobauding NO
ringback NO
ringback-time 30
ignore-carrier false
issue-file /etc/issue
prompt-waittime 500
login-prompt @!login:
login-time 240
diskspace 4096
fax-owner uucp
fax-group dialer
fax-mode 0660

Then configure the file /usr/local/lib/mgetty+sendfax/new_fax with your emailaddress.

Email to Fax Gateway

Then configure the file /usr/local/etc/mgetty+sendfax/faxheader with the wished header for outgoing faxes.

Edit /usr/local/etc/mgetty+sendfax/faxrunq.config:

success-send-mail n
failure-send-mail n
success-call-program /usr/local/lib/mgetty+sendfax/fax_done
failure-call-program /usr/local/lib/mgetty+sendfax/fax_done
delete-sent-jobs y

Configure for emailaddress in the file /usr/local/lib/mgetty+sendfax/fax_done.

Edit /usr/local/etc/mgetty+sendfaxsendfax.config:

fax-devices cuad1

port cuad1
fax-id +49 8141 xxxxx
modem-type auto
debug 4
modem-handshake AT&H3
max-tries 3
max-tries-continue no
speed 38400
dial-prefix ATD
poll-dir ./
normal-res NO
verbose NO

Add the following into your exim-config /usr/local/etc/exim/configure:

## MAIN ##
domainlist fax = <; fax

## Routers ##
fax:
   driver = manualroute
   transport = fax
   route_list = fax

## transports ##
fax:
  driver = pipe
  user = idefix
  command ="/usr/local/bin/mail2g3.pl ${local_part}"
  home_directory = /usr/local/bin

The script can be found Image:Mail2g3.txt, rename it to mail2g3.pl and copy it into /usr/local/bin. Restart exim with:

/usr/local/etc/rc.d/exim restart

To send the faxes every day put the following into your /etc/crontab:

5   20  *   *   *   root    faxrunq

Now send mail to faxnumber@fax.

Hylafax

Seems to be broken with newer versions... Use mgetty+sendfax instead.

Send fax after a defined time

To send all faxes after 20:00 edit /usr/local/lib/fax/sendfax.conf

SendTime: "20:00"

E-Mail to FAX gateway

Configure faxmail for PDF attachments

Edit /usr/local/lib/fax/hyla.conf

# FontMap/FontPath added by faxsetup (Thu Feb  2 14:32:10 CET 2006)
FontMap:   /usr/local/share/ghostscript/7.07/lib:/usr/local/share/ghostscript/fonts
FontPath:  /usr/local/share/ghostscript/7.07/lib:/usr/local/share/ghostscript/fonts
PageSize: ISO A4
MIMEConverters: /usr/local/faxscripts

Create the MIME conversion tools:

mkdir /usr/local/faxscripts
mkdir /usr/local/faxscripts/application

Create the file /usr/local/faxscripts/application/pdf

#!/usr/local/bin/bash
/bin/echo " "
/bin/echo "showpage"
/usr/local/bin/gs -q -sPAPERSIZE=a4 -dFIXEDMEDIA -dBATCH -dNOPAUSE -r600x800 -sDEVICE=pswrite -sOutputFile=- $1 | /usr/local/faxscripts/filter.pl

Create the file /usr/local/faxscripts/filter.pl

#!/usr/bin/perl
# Read from the standard input
@text=<STDIN>;
$size=@text;

# Count the number of "showpage"
$count=0;
for($i=0;$i<=$size;$i++){if($text[$i] =~ /showpage/){$count++;}}

# Discard the last line that contain "showpage"
$num=1;
for($i=0;$i<=$size;$i++){
        if($text[$i] =~ /showpage/){
                if($num!=$count){$num++;}
                else{$text[$i]=~s/showpage//g;}
        }

                print $text[$i];
}

Give both file the executable bit

chmod +x /usr/local/faxscripts/application/pdf
chmod +x /usr/local/faxscripts/filter.pl

Now conversion to postscript should be possible. Take an email with a pdf attachment and save it under testmail.mail. Now execute the command:

cat testmail.mail|faxmail -v >test.ps

Check the output from faxmail at screen and have a look at test.ps and verify that it was a successfully conversion.

Configure Exim

Add a new domain_list for faxes:

domainlist fax = <; fax

Add at the section routers:

fax:
   driver = manualroute
   transport = fax
   route_list = fax

Add at the section transports:

fax:
  driver = pipe
  user = idefix
  command ="/usr/local/bin/faxmail -n -d ${local_part}"
  home_directory = /usr/local/bin

Sending a fax

Now send an email to the address

<number>@fax

replace <number> with the fax number.

The fax is now scheduled, you can check this with the command:

faxstat -l -s

PPTP VPN Dialin

Install mpd4

# cd /usr/ports/net/mpd4/
# make install clean

Configuration

Edit /usr/local/etc/mpd4/mpd.conf

startup:
    # enable TCP-Wrapper (hosts_access(5)) to block unfriendly clients
    set global enable tcp-wrapper
    # configure the console
    set console port 5005
    set console ip 0.0.0.0
    set console user idefix test
    set console open

default:
    load pptp1
    load pptp2

pptp1:
    new -i ng0 pptp1 pptp1
    set ipcp ranges 192.168.0.251/32 192.168.0.2/32
    load client_standard

pptp2:
    new -i ng1 pptp2 pptp2
    set ipcp ranges 192.168.0.251/32 192.168.0.3/32
    load client_standard

client_standard:
    set iface disable on-demand
    set iface enable proxy-arp
    set iface idle 1800
    set iface enable tcpmssfix
    set bundle enable multilink
    set link yes acfcomp protocomp
    set link no pap chap
    set link enable chap
    set link mtu 1460
    set link keep-alive 10 60
    set ipcp yes vjcomp
    set ipcp dns 192.168.0.251
    set ipcp nbns 192.168.0.251
    set bundle enable compression
    set ccp yes mppc
    set ccp yes mpp-e40
    set ccp yes mpp-e128
    set ccp yes mpp-stateless

Edit /usr/local/etc/mpd4/mpd.links

pptp0:
    set link type pptp
    set pptp self 0.0.0.0
    set pptp enable incoming
    set pptp disable originate

pptp1:
    set link type pptp
    set pptp self 0.0.0.0
    set pptp enable incoming
    set pptp disable originate

Edit /usr/local/etc/mpd4/mpd.secret

<username> <password>

Fix permissions:

chmod 600 /usr/local/etc/mpd4/mpd.secret

Enable IP forwarding

Edit /etc/rc.conf

gateway_enable="YES"

Enable proxy arp

Edit /etc/rc.conf

arpproxy_all="YES"

Start pptpd

/usr/local/etc/rc.d/mpd4.sh start

Allow acces from extern through the firewall

Allow TCP port pptp (1723). Allow protocol GRE.

Cloning disks

dump/restore

If it were me, I would plub the second disk in. It is SCSI so it should show up as da1 (or higher if you have more disks you haven't mentioned).

Then I would use fdisk(8) and bsdlabel(8) to slice and partition it to be like the other disk. Use newfs(8) to create the file systems and then use dump(8) and restore(8) to copy the file systems.

Lets presume you have 1 slice all FreeBSD on the disk and in that slice you have /, swap, /tmp, /usr, /var and /home just for example and you don't need to copy swap and /tmp, of course.

The following would do it nicely.

  dd if=/dev/zero of=/dev/da1 bs=512 count=1024
  fdisk -BI da1
  bsdlabel -w -B da1s1
  bsdlabel -e
    --- At this point you will be put in to an editor file with a
        nominal 1 partition created.   Just for example I will
        pick some sizes.   Actually, you want to do a bsdlabel on
        your da0s1 to see what values to use.  Make them the same.
  Leave alone all the stuff above the partition information

So, starting here, edit it to be:
  8 partitions:
#        size   offset    fstype   [fsize bsize bps/cpg]
  a:   393216        0    4.2BSD     2048 16384    94   #
  b:  2572288        *      swap                        # (Cyl.   32*- 192*)
  c:156119670        0    unused        0     0         # (Cyl.    0 - 4858)
  e:  1048576        *    4.2BSD     2048 16384    89   # (Cyl.  192*- 258*)
  f:  4194304        *    4.2BSD     2048 16384    89   # (Cyl.  258*- 519*)
  g:  6291456        *    4.2BSD     2048 16384    89   # (Cyl.  519*- 910*)
  h:        *        *    4.2BSD     2048 16384    89   # (Cyl.  910*- 4826*)
~
That would be /     = 192 MB
              swap  = 1256 MB
              /tmp  = 512 MB
              /usr  = 2048 MB
              /var  = 3072 MB
              /home = all the rest of the slice on a nominal 76 GB drive.

Sizes are before newfs or system reserves. As mentioned above, use the partition identifiers the same as on your other disk that you want to copy.

Write and exit the editor and your label is done.

newfs /dev/da1s1a            becomes /
newfs -U /dev/da1s1e         becomes /tmp
newfs -U /dev/da1s1f         becomes /usr
newfs -U /dev/da1s1g         becomes /var
newfs -U /dev/da1s1h         becomes /home

Swap does not get newfs-ed.

Add mount points

mkdir /cproot
mkdir /cpusr
mkdir /cpvar
mkdir /cphome

You don't need one for the copy of /tmp since you don't need to copy it.

Edit /etc/fstab to add mount instructions.

# Presuming your original fstab has the following as per my example
/dev/da0s1a             /               ufs     rw              1       1
/dev/da0s1b             none            swap    sw              0       0
/dev/da0s1e             /tmp            ufs     rw              2       2
/dev/da0s1f             /usr            ufs     rw              2       2
/dev/da0s1g             /var            ufs     rw              2       2
/dev/da0s1h             /home           ufs     rw              2       2
# add something like the following according to your setup needs.
/dev/da1s1a             /cproot         ufs     rw              2       2
/dev/da1s1f             /cpusr          ufs     rw              2       2
/dev/da1s1g             /cpvar          ufs     rw              2       2
/dev/da1s1h             /cphome         ufs     rw              2       2

Note that you want to change the pass on the cproot to '2' so it won't mess up boots.

Now mount everything.

mount -a

Then do the copies.

cd /cproot
dump -0af - / | restore -rf -
cd /cpusr
dump -0af - /usr | restore -rf -
cd /cpvar
dump -0af - /var | restore -rf -
cd /cphome
dump -0af - /home | restore -rf -

You are finished.

In the future, if you make the same copies on to the same disk, you do not have to reslice, relabel and renewfs everything. You can just go in to each filesystem and rm -rf it. Or you could just umount, newfs and remount each partition to clear them.

cd /cproot
rm -rf *
 etc or
umount /cproot
newfs /dev/da1s1a
   etc etc
mount -a

Then do copies.

It looks a bit complicated to set up, but it really isn't and it is the most complete way to create bootable copies of disks.

If you do periodic copies, it would be easy to create a script to clean the copy (using either rm -rf * or newfs method) and do the dump/restores. It could even run on the cron if you want. I would actually suggest setting up a three disk rotation for copies.

Encrypting harddisks

GELI

Create a key with:

dd if=/dev/random of=/root/storage.key bs=256 count=1

Create a encrypted disk:

geli init -a aes -l 256 -s 4096 -K /root/storage.key /dev/ad3
Enter new passphrase:
Reenter new passphrase:

or
cat keyfile1 keyfile2 keyfile3 | geli init -a aes -l 256 -s 4096 -K - /dev/ad3

To attach the provider:

geli attach -k /root/storage.key /dev/ad3
Enter passphrase:

Create a filesystem and mount it:

dd if=/dev/random of=/dev/ad3.eli bs=1m
newfs /dev/ad3.eli
mount /dev/ad3.eli /usr/home/storage

Unmounting the drive and detach it:

umount /usr/home/storage
geli detach ad3.eli

Mount it at bootup edit /etc/rc.conf:

# GELI config
geli_devices="ad3"
geli_ad3_flags="-k /root/storage.key"

Edit /etc/fstab:

/dev/ad3.eli            /home/storage ufs rw                    1       2

Running out of swapspace

Run the following command to see which process needs so much memory:

ps aux | sort -n +5

OpenVPN

Configure as client

Create a file /usr/local/etc/openvpn/idefix.ovpn:

client
dev tun
proto udp
remote <server-host> <port>
resolv-retry infinite
nobind
ca /usr/local/etc/openvpn/keys/ca.crt
cert /usr/local/etc/openvpn/keys/idefix.crt
key /usr/local/etc/openvpn/keys/idefix.key
comp-lzo
verb 1
mute 10

Copy the the keyfiles from the server to the client into the directory /usr/local/etc/openvpn/keys.

Edit /etc/rc.conf:

openvpn_enable="YES"  # YES or NO
openvpn_if="tun"      # driver(s) to load, set to "tun", "tap" or "tun tap"
openvpn_flags=""      # openvpn command line flags
openvpn_configfile="/usr/local/etc/openvpn/idefix.ovpn"      # --config file
openvpn_dir="/usr/local/etc/openvpn"                          # --cd directory

Start vpn connection now with /usr/local/etc/rc.d/openvpn start.

Check /var/log/messages for error etc.

Configure as Server

Create the keys with:

cd /usr/local/share/doc/openvpn/easy-rsa

Edit vars at the bottom of the page.

bash
. ./vars
./clean-all
./build-ca
./build-key-server server
./build-key client1
./build-dh
cp ca.crt ca.key dh1024.pem server.crt server.key /usr/local/etc/openvpn/keys-server/

Repair UFS2

As a follow up to the previous thread on which I was the OP have followed the advice given, contacted Ian Dowse who kindly walked me through fixing my hard drive. Here is a synopsis as best as I can do to explain what was done:

First find out the offsets of the bad sectors, and check with dd that you can't read them

Then write zeros over that sector

dd if=/dev/zero seek=12345 count=1 of=/dev/ad1

and recheck that the original failing dd now works.

After fixing all the bad sectors that way, you'll probably have much more luck with standard tools such as fsck.


%sudo fsck /dev/ad1s1a

    • /dev/ad1s1a

Cannot find file system superblock /dev/ad1s1a: INCOMPLETE LABEL: type 4.2BSD fsize 0, frag 0, cpg 0, size 490223412

Try editing the disklabel with `disklabel -e ad1s1', and changing the line to look like:

 a: 490223412        0    4.2BSD        2048  16384 94088

%sudo fsck /dev/ad1s1a

    • /dev/ad1s1a

Cannot find file system superblock

LOOK FOR ALTERNATE SUPERBLOCKS? [yn] y

32 is not a file system superblock 28780512 is not a file system superblock 57560992 is not a file system superblock [snip] 460486688 is not a file system superblock 489267168 is not a file system superblock SEARCH FOR ALTERNATE SUPER-BLOCK FAILED. YOU MUST USE THE -b OPTION TO FSCK TO SPECIFY THE LOCATION OF AN ALTERNATE SUPER-BLOCK TO SUPPLY NEEDED INFORMATION; SEE fsck(8). %

looking for superblocks in the right place. What do you get if you run the following - this is a crude way to search for superblocks:

dd if=/dev/ad1 bs=32k | hd -v | grep "19 01 54 19"


Better still, if you can get a hex dump using dd and hd of a few kb before one of the matching lines, the parameters can be extracted from there.


> %sudo dd if=/dev/ad1 bs=32k | hd -v | grep "19 01 54 19" > Password: > 00008b10 00 74 27 3d 19 01 54 19 75 31 8b 04 bd 9d 34 00 |.t'=..T.u1....4.| > 00008bd0 8b 4d 64 81 bd 5c 05 00 00 19 01 54 19 89 c6 89 |.Md..\.....T....| > 0001c350 00 00 00 00 00 00 00 00 00 00 00 00 19 01 54 19 |..............T.| > 005ec350 00 00 00 00 00 00 00 00 00 00 00 00 19 01 54 19 |..............T.| > 0b7e0350 00 00 00 00 00 00 00 00 00 00 00 00 19 01 54 19 |..............T.|

Looks good - the 3rd and later lines look like superblocks - try:

 fsck_ffs -b 160 /dev/ad1s1a

(160 is calculated by taking 0x0001c350 from the third line above, subtracting 0x550 to get the start of the superblock, and then dividing by 512 to get the sector number, and finally subtracting the partition offset of 63)

I'm guessing that fsck was looking for superblocks in the wrong place becasue without a valid superblock it was assuming that the filesystem was UFS1 not UFS2. As far as I can tell, for UFS2 the first standard backup superblock is usually at block 160, whereas for UFS1 it's at block 32. I guess fsck_ffs and/or the man page need to be updated to deal with that.

===========================

In end, it worked fine and that HD is back in business. Thanks Ian, and everyone else that helped out on this one.

Marty

-- Web Installed Formmail - http://face2interface.com/formINSTal/ Webmaster's BBS - http://bbs.face2interface.com/ _______________________________________________ freebsd-questions@freebsd.org mailing list http://lists.freebsd.org/mailman/listinfo/freebsd-questions To unsubscribe, send any mail to "freebsd-questions-unsubscribe@freebsd.org"

Personal tools