Pages

FreeBSD Configs, Tools and FAQs

1.FreeBSD install and customization
2.FreeBSD custom configs

3.FreeBSD tunning 
4.FreeBSD FAQ

To export all MySQL user privileges run following script.
Note : Replace {host_name}, {user_name} and {password} with your values.
mysql -h {host_name} -u {user_name} -p{password} -Ne "select distinct concat( \"SHOW GRANTS FOR '\",user,\"'@'\",host,\"';\" ) from user;" mysql | mysql -h {host_name} -u {user_name} -p{password} | sed 's/\(GRANT .*\)/\1;/;s/^\(Grants for .*\)/## \1 ##/;/##/{x;p;x;}'

Restart IPFW and routing
service ipfw restart
/etc/rc.d/netif restart && /etc/rc.d/routing restart

View config without comments
[/zzz/lighty/conf]# grep ^[^#] lighttpd.conf

PING show TIMEOUT
http://superuser.com/questions/270083/linux-ping-show-time-out
/sbin/scping
#!/bin/bash

host=$1

if [ -z $host ]; then
    echo "Usage: `basename $0` [HOST]"
    exit 1
fi

while :; do
    result=`ping -W 1 -c 1 $host | grep 'bytes from '`
    if [ $? -gt 0 ]; then
        echo -e "`date +'%Y/%m/%d %H:%M:%S'` - host $host is \033[0;31mdown\033[0m"
    else
         echo -e "`date +'%Y/%m/%d %H:%M:%S'` - host $host is \033[0;32mok\033[0m -`echo $result | cut -d ':' -f 2`"
        sleep 1 # avoid ping rain
    fi
done


1.FreeBSD install and customization
1.1 Basic Tools
vmware-tools
/etc/periodic/weekly/310.locate  (probl: locate: database too small: /var/db/locate.database)
make -C /usr/ports/shells/bash -D WITH_STATIC_BASH -DWITHOUT_NLS PREFIX=/ config-recursive install clean
mc
ncdu
atop
portupgrade
pstree
sendEmail-1.56
sysinfo (+dmidecode)
whowatch
lsof - "list open files", report a list of all open files and the processes that opened them
wget
1.2 Basic Config
rc.conf (hostname, interfaces, routes, services)
KERNEL  +  IPFW  ( http://sclabs.blogspot.com/2011/02/freebsd-software-installremove.html )
SSHD
SYSCTL (icmp limit, source route ...)
fstab (enable atime)
ntp
bsnmp
snmptt-1.3  (+net-snmp)
sudo - allows users to run programs with the security privileges of another user
cron
1.3 User Soft
tmux      
curl
fpdns
fping
net-lft
lynx
tcping-1.3.5
tcptraceroute-1.4_2
dhcpdump
mtr-nox11
dhcpcd 6.0.2 PATCHUIT (manual install)
whowatch - interactive who-like program that displays information about the users currently logged.
1.4 Zabbix requirements
mysql55-server
xtrabackup
mysqltuner
mtop
-/var/log/mysql
-/var/db/mysql   (-> /usr/mysql   ) 
-/usr/mysql-backups
-config
php5  (5.4)
php5-extensions
+php.ini

lighttpd-1.4.30_2
+config (main, modules,conf.d)

zabbix2-
 +/var/log/zabbix
 +/var/run/zabbix 
 + Zabbix database is down.    
1.5 Looking Glass
 +perl XML/Parser.pm
 /usr/ports/textproc/p5-libxml
install Bundle::LWP
install Net::IP
install Net::Ping
install Net::Telnet
install Net::SSH
2. FreeBSD custom configs

/etc/sysctl.conf
# Uncomment this to prevent users from seeing information about processes that
# are being run under another UID.
#security.bsd.see_other_uids=0
net.inet.icmp.icmplim=10000
kern.polling.enable=1
kern.ipc.nmbclusters=262144
kern.maxfiles=204800
kern.maxfilesperproc=200000
kern.maxvnodes=200000
# stops route cache degregation during a high-bandwidth flood
# http://www.freebsd.org/doc/en/books/handbook/securing-freebsd.html
#net.inet.ip.rtexpire=2
net.inet.ip.rtminexpire=2
net.inet.ip.rtmaxcache=1024

# Security
net.inet.ip.redirect=0
net.inet.ip.sourceroute=0
net.inet.ip.accept_sourceroute=0
net.inet.icmp.maskrepl=0
net.inet.icmp.log_redirect=0
net.inet.icmp.drop_redirect=1
net.inet.tcp.drop_synfin=1
net.inet.udp.blackhole=1
net.inet.tcp.blackhole=2

Full example  http://wiki.nginx.org/FreeBSDOptimizations
# sysctl.conf
# http://www.thern.org/projects/sysctl.conf
# http://serverfault.com/questions/64356/freebsd-performance-tuning-sysctls-loader-conf-kernel

# ipfw
# default e 4096
net.inet.ip.fw.dyn_max=16000

# default e 60s = 60000
net.inet.tcp.finwait2_timeout=15000

# Shared memory // 7.2+ can use shared memory > 2Gb
kern.ipc.shmmax=134217728
kern.ipc.semmap=256
kern.ipc.shmall=32768

# Увеличить максимальное число открытых сокетов
kern.ipc.maxsockets=204800

# kern.ipc.somaxconn ограничивает размер очереди для приема новых TCP соединений.
# Значение по умолчанию 128 слишком мало для надежной обработки новых соединений
# для нагруженного web сервера.
# Для такого сервера рекомендуется увеличить это значение до 1024 или выше.
kern.ipc.somaxconn=4096

# increase the size of network mbufs to allocate
kern.ipc.nmbclusters=65536

# update maximum files allowed for the kernel
kern.maxfiles=65536
#kern.maxfilesperproc=200000
#kern.maxvnodes=200000

### NETWORK
# Lessen max segment life to conserve resources
# ACK waiting time in miliseconds
# (default: 30000. RFC from 1979 recommends 120000)
net.inet.tcp.msl=5000

# FIN_WAIT_2 state fast recycle
net.inet.tcp.fast_finwait2_recycle=1

# Security
net.inet.ip.redirect=0
net.inet.icmp.maskrepl=0
net.inet.icmp.log_redirect=0
net.inet.icmp.drop_redirect=1
net.inet.tcp.drop_synfin=1

# security against stealth port scans and some DoS attacks
net.inet.udp.blackhole=1
net.inet.tcp.blackhole=2

# stops some syn flood attacks, and route cache degregation during a high-bandwidth flood
net.inet.ip.rtexpire=2
net.inet.ip.rtminexpire=2
net.inet.ip.rtmaxcache=256

# don't accept sourcerouted packets (they are evil, gross, and have cooties)
net.inet.ip.accept_sourceroute=0
net.inet.ip.sourceroute=0

# IPv6 Security
# For more info see http://www.fosslc.org/drupal/content/security-implications-ipv6
# Disable Node info replies
# To see this vulnerability in action run `ping6 -a sglAac ::1` or `ping6 -w ::1` on unprotected node
net.inet6.icmp6.nodeinfo=0

# Turn on IPv6 privacy extensions
# For more info see proposal http://unix.derkeiler.com/Mailing-Lists/FreeBSD/net/2008-06/msg00103.html
net.inet6.ip6.use_tempaddr=1
net.inet6.ip6.prefer_tempaddr=1

# Disable ICMP redirect
net.inet6.icmp6.rediraccept=0
Another SYSCTL info
Некоторые полезные sysctl переменные для FreeBSD
security.bsd.* - управление моделью безопасности
    security.bsd.see_other_uids, security.bsd.see_other_gids - если 1, то пользователи (группы) могут видеть чужие процессы, сокеты и т.д. через ps, netstat, procfs;
    security.bsd.conservative_signals - если 1, то некоторые сигналы запрещается посылать setuid/setgid процессам;
    security.bsd.unprivileged_proc_debug - если 1, то пользовательский процесс можно отлаживать через ptrace, procfs, ktrace и т.д..
    security.bsd.unprivileged_read_msgbuf - если 1, то пользовательский процесс может читать из системного консольного буфера сообщений;
    security.bsd.hardlink_check_uid, security.bsd.hardlink_check_gid - если 1, то пользователи могут делать hardlink только на собственные файлы;
    security.bsd.unprivileged_get_quota - если 1, пользователи могут просматривать информацию по установленным для них квотам.
    vfs.usermount - если 1, то непривилегированный пользователь может монтировать и размонтировать FS, если для устройства выставлены "rw" права и пользователь является владельцем точки монтирования;

security.jail.* - ограничения для jail
    security.jail.set_hostname_allowed - если 1, то внутри jail можно поменять имя хоста;
    security.jail.socket_unixiproute_only - если 1 , то сокет в jail можно создать только для доменов PF_LOCAL, PF_INET или PF_ROUTE, иначе, возвращается ошибка;
    security.jail.sysvipc_allowed - если 1, то то в jail можно получить доступ к глобальному System V IPC;
    security.jail.getfsstatroot_only - если 1, то в jail можно получить информацию (df)только о той файловой системе на которой создан jail;
    security.jail.allow_raw_sockets - если 1, то в jail можно создавать raw sockets;
    security.jail.chflags_allow - если 1, то процессы в jail могут модифицировать флаги ФС.

IPFW
    net.link.ether.bridge_ipfw - если 1 и ядро собрано с опциями IPFIREWALL и BRIDGE, то позволяет использовать ipfw для трафика внутри бриджа;
    net.link.ether.ipfw - если 1, то ipfw2 позволяет фильтровать по MAC адресам;
    net.inet.ip.fw.autoinc_step - задается число на которое увеличивается счетчик при добавления нового ipfw правила, когда явно не указан его номер;
    net.inet.ip.fw.debug - если 1, то в логи помещается дополнительная отладочная информация по работе ipfw;
    net.inet.ip.fw.verbose - если 0, то не отображать работу "log" правил в syslog;
    net.inet.ip.fw.one_pass - если 1, то просмотр правил ipfw прекращается сразу после подпадание под queue или pipe правило. Если 0, то продолжается обработка далее идущих правил;

ICMP, соединение.
    net.inet.icmp.icmplim - задается максимальное число ICMP "Unreachable" и TCP RST пакетов, которое может быть отправлено в секунду, net.inet.icmp.icmplim_output=0 позволяет не отражать в логах факты превышения лимита;
    net.inet.tcp.icmp_may_rst, если 1, то TCP соединения со статусом SYN_SENT, могут быть оборваны посредством сообщения "ICMP unreachable";
    net.inet.ip.redirect - если 0, то нет реакции на ICMP REDIRECT пакеты;
    net.inet.icmp.log_redirect - если 1, то все ICMP REDIRECT пакеты отражаются в логе;
    net.inet.icmp.drop_redirect - если 1, то ICMP REDIRECT пакеты игнорируются;
    net.inet.tcp.icmp_may_rst - если 1, то игнорируются ICMP сообщения от блокировки пакета по пути;
    net.inet.icmp.bmcastecho - для защиты от SMURF атак (ICMP echo request на broadcast адрес) нудно поставить 0;

Тюнинг сетевой подсистемы, борьба с DoS атаками
    net.inet.tcp.log_in_vain, net.inet.udp.log_in_vain - если 1, отражаем в логе попытки соединения к портам, для которых нет активных сервисов;
    net.inet.tcp.blackhole - если 1, то SYN пакеты пришедшие на порты для которых нет активных сервисов, остаются без RST ответа, если 2, то на любые пакеты нет ответа (затрудняет сканирования портов);
    kern.ipc.nmbclusters - если по "netstat -m" mbufs в "peak" приближается к "max", то число сетевых буферов нужно увеличить (kern.ipc.nmbclusters=N в /boot/locader.conf);
    net.inet.ip.forwarding - если 1, то машина может форвадить пакеты между интерфейсами;
    net.inet.tcp.sack.enable - если 1, то включен TCP Selective Acknowledgements (SACK, RFC 2018) позволяющий увеличить производительность системы в ситуации большой потери пакетов;
    net.link.ether.inet.max_age - время жизни записи в IP route кэше, рекомендуется уменьшить для ослабления эффекта от DoS атак через ARP флуд;

Оборудование и системная информация
    dev.cpu.0.freq_levels - выдает список поддерживаемых частот, на которые можно переключить CPU, путем указание нужной частоты через dev.cpu.0.freq;
    hw.snd.maxautovchans, hw.snd.pcm0.vchans - задается число виртуальных звуковых каналов, для каждого из которых может быть отдельный источник звука (на выходе они будут смикшированы);
    kern.boottime - время последней загрузки системы;
    kern.disks - список дисков в системе;
    kern.geom.debugflags, для работы boot0cfg и подобных утилит нужно установить в 16;

Изменение и тюнинг системных ограничений
    kern.coredump - если 0, то при крахе приложения не будут создаваться core файлы, формат имени и путь для которых задается через kern.corefile (например: /tmp/%U.%N.core). kern.sugid_coredump=0 позволяет запретить генерацию core suid/sgid процессами;
    kern.maxfiles - максимально допустимое число открытых файлов (файловых дескрипторов), текущее число открытых файлов можно посмотреть через kern.openfiles;
    kern.maxprocperuid - максимально допустимое число процессов, которое может быть запущено из-под одного пользователя;
    kern.maxvnodes - максимальное число vnode для кеширования дисковых операций, текущее значение можно посмотреть через vfs.numvnodes или debug.numvnodes/debug.freevnodes;

SMP (FreeBSD 5)
    kern.smp.maxcpus (machdep.smp_cpus) - максимальное число процессоров, поддерживаемое текущей сборкой ядра;
    kern.smp.active, kern.smp.disabled - число активных и выключенных CPU;
    kern.smp.cpus (machdep.smp_active) - сколько CPU в online;
    kern.smp.forward_signal_enabled - включить возможность мгновенной пересылки сигнала для процессов выполняемых в данный момент времени на разных CPU;
    kern.smp.forward_roundrobin_enabled;

ARP
    net.link.ether.inet.log_arp_movements - отражать в логе все широковещательные ARP пакеты с хостов MAC адрес которых отсутствует в локальном ARP кэше;
    net.link.ether.inet.log_arp_wrong_iface - отражать в логе все ARP пакеты пришедшие с неправильного интерфейса;


/boot/loader.conf
kern.ipc.semmap=60
kern.ipc.semmni=20
kern.ipc.semmns=120
kern.ipc.semmnu=60
kern.ipc.semmsl=120
kern.ipc.semopm=200
kern.ipc.semume=20
# Beginning of the block added by the VMware software - DO NOT EDIT
vmxnet_load="YES"
# End of the block added by the VMware software
# Beginning of the block added by the VMware software - DO NOT EDIT
vmxnet3_load="YES"
# End of the block added by the VMware software

/usr/local/etc/sudoers
touch /var/log/sudolog
echo 'Defaults !syslog' >> /usr/local/etc/sudoers
echo 'Defaults logfile = /var/log/sudolog' >> /usr/local/etc/sudoers

You can disable the logging on a user basis using the Defaults: directive
example (disabled logging for user zabbix)
Defaults:zabbix !syslog

echo 'root ALL=(ALL) ALL' >> /usr/local/etc/sudoers
echo 'zabbix ALL=(ALL) NOPASSWD: /sbin/sysctl, /usr/local/bin/sudo' >> /usr/local/etc/sudoers

echo '/var/log/sudolog 644 5 100 * JC' >> /etc/newsyslog.conf
/var/log/lighttpd/access.log<--><------>www:www><------>644<--->5   10000<----->*<----->B<----->/var/run/lighttpd.pid
service newsyslog restart

cat /usr/local/etc/sudoers ; cat /etc/newsyslog.conf; cat /var/log/sudolog

/etc/snmpd.config   (grep ^[^#] ./snmpd.config )  +custom MIBS @ /usr/local/share/snmp
location := "NOC "
contact := "noc@mydomain.com"
system := 1 # FreeBSD
traphost := localhost
trapport := 162
read := "custpublic"
write := "custpublic"
trap := "custpublic"
NoAuthProtocol          := 1.3.6.1.6.3.10.1.1.1
HMACMD5AuthProtocol     := 1.3.6.1.6.3.10.1.1.2
HMACSHAAuthProtocol     := 1.3.6.1.6.3.10.1.1.3
NoPrivProtocol          := 1.3.6.1.6.3.10.1.2.1
DESPrivProtocol         := 1.3.6.1.6.3.10.1.2.2
AesCfb128Protocol       := 1.3.6.1.6.3.10.1.2.4
securityModelAny        := 0
securityModelSNMPv1     := 1
securityModelSNMPv2c    := 2
securityModelUSM        := 3
MPmodelSNMPv1           := 0
MPmodelSNMPv2c          := 1
MPmodelSNMPv3           := 3
noAuthNoPriv := 1
authNoPriv := 2
authPriv := 3
%snmpd
begemotSnmpdDebugDumpPdus       = 2
begemotSnmpdDebugSyslogPri      = 7
begemotSnmpdCommunityString.0.1 = $(read)
begemotSnmpdCommunityDisable    = 1
begemotSnmpdPortStatus.0.0.0.0.161 = 1
begemotSnmpdLocalPortStatus."/var/run/snmpd.sock" = 1
begemotSnmpdLocalPortType."/var/run/snmpd.sock" = 4
begemotTrapSinkStatus.[$(traphost)].$(trapport) = 4
begemotTrapSinkVersion.[$(traphost)].$(trapport) = 2
begemotTrapSinkComm.[$(traphost)].$(trapport) = $(trap)
sysContact      = $(contact)
sysLocation     = $(location)
sysObjectId     = 1.3.6.1.4.1.12325.1.1.2.1.$(system)
snmpEnableAuthenTraps = 2
begemotSnmpdModulePath."mibII"  = "/usr/lib/snmp_mibII.so"
begemotSnmpdModulePath."ucd" = "/usr/local/lib/snmp_ucd.so"
/usr/local/etc/snmp/snmp.conf    (add custom MIBS to /usr/local/share/snmp/mibs/)
mibs +ALL

OR

mibs  +/usr/local/share/snmp/mibs/VMWARE-AGENTCAP-MIB.mib
mibs  +/usr/local/share/snmp/mibs/VMWARE-CIMOM-MIB.mib
mibs  +/usr/local/share/snmp/mibs/VMWARE-ENV-MIB.mib
mibs  +/usr/local/share/snmp/mibs/VMWARE-OBSOLETE-MIB.mib
mibs  +/usr/local/share/snmp/mibs/VMWARE-PRODUCTS-MIB.mib
mibs  +/usr/local/share/snmp/mibs/VMWARE-RESOURCES-MIB.mib
mibs  +/usr/local/share/snmp/mibs/VMWARE-ROOT-MIB.mib
mibs  +/usr/local/share/snmp/mibs/VMWARE-SRM-EVENT-MIB.mib
mibs  +/usr/local/share/snmp/mibs/VMWARE-SYSTEM-MIB.mib
mibs  +/usr/local/share/snmp/mibs/VMWARE-TC-MIB.mib
mibs  +/usr/local/share/snmp/mibs/VMWARE-VC-EVENT-MIB.mib
mibs  +/usr/local/share/snmp/mibs/VMWARE-VCOPS-EVENT-MIB.mib
mibs  +/usr/local/share/snmp/mibs/VMWARE-VMINFO-MIB.mib
mibs  +/usr/local/share/snmp/mibs/ds3500.mib
mibs  +/usr/local/share/snmp/mibs/imm.mib
mibs  +/usr/local/share/snmp/mibs/immalert.mib
mibs  +/usr/local/share/snmp/mibs/v3700.mib

/usr/local/etc/snmp/snmptrapd.conf    (Traps goes to Zabbix Trapper)
disableAuthorization yes
ignoreauthfailure no
donotlogtraps no
pidfile /var/run/snmptrapd.pid
authCommunity log,execute,net public
perl do "/usr/local/etc/zabbix/zabbix_trap_receiver.pl"

/etc/ntp.conf
server 0.europe.pool.ntp.org
server 1.europe.pool.ntp.org
server 2.europe.pool.ntp.org
server 3.europe.pool.ntp.org
server 0.ro.pool.ntp.org
server 1.ro.pool.ntp.org
server 2.ro.pool.ntp.org
server 3.ro.pool.ntp.org
server 0.freebsd.pool.ntp.org iburst maxpoll 9
server 1.freebsd.pool.ntp.org iburst maxpoll 9
server 2.freebsd.pool.ntp.org iburst maxpoll 9
logfile /var/log/ntp.log
/etc/ssh/sshd_config
#Port 22
ListenAddress 10.1.1.1
UseDNS no
/etc/resolv.conf
domain mydom.com
namserver       8.8.4.4
nameserver       8.8.8.8
/etc/fstab
# Device        Mountpoint      FStype  Options Dump    Pass#
/dev/da0p2      /               ufs     rw      1       1
/dev/da0p3      none            swap    sw      0       0
/dev/da0p4      /var            ufs     rw,noatime      2       2
/dev/da0p5      /usr            ufs     rw,noatime      2       2
/dev/da0p6      /tmp            ufs     rw,noatime      2       2
#
# /dev/md0      /cache          mfs     rw,noatime,-s1024M      0       0
# /dev/da1s1b     none            swap    sw      0       0
/etc/my.cnf      cp /usr/local/share/mysql/my-large.cnf  /var/db/mysql/my.cnf   (ln -s /etc/my.cnf)
mkdir /var/log/mysql
chown mysql:mysql /var/log/mysql
[client]
port            = 3306
socket          = /tmp/mysql.sock
[mysqld]
bind-address = 127.0.0.1
datadir= /usr/mysql
port            = 3306
socket          = /tmp/mysql.sock
skip-external-locking
key_buffer_size = 32M
max_allowed_packet = 1M
table_open_cache = 64
sort_buffer_size = 512K
net_buffer_length = 8K
read_buffer_size = 256K
read_rnd_buffer_size = 512K
myisam_sort_buffer_size = 8M
server-id       = 1
query_cache_limit = 1048576
query_cache_size = 24000000
query_cache_type = 1
max_allowed_packet = 16M
thread_stack = 256K
thread_cache_size = 80
thread_concurrency = 4
tmp_table_size = 512M
max_heap_table_size = 256M
table_cache = 512
log_error = /var/log/mysql/mysql-error.log
slow_query_log_file = /var/log/mysql/mysql-slow.log
slow_query_log = 1
long_query_time = 10
# Replication Master Server (default)
# binary logging is required for replication
# log-bin=mysql-bin
# binary logging format - mixed recommended
# binlog_format=mixed
innodb_data_home_dir = /usr/mysql
innodb_data_file_path = ibdata1:128M;ibdata2:128M:autoextend:max:4096M
innodb_log_group_home_dir = /usr/mysql
innodb_file_per_table = 1     #Creates idb for every table in db folders
innodb_status_file = 1
innodb_thread_concurrency = 8     #Should match number of processors
innodb_io_capacity = 2000
innodb_flush_log_at_trx_commit = 2
innodb_support_xa = 0
innodb_buffer_pool_size = 1500M
innodb_additional_mem_pool_size = 10M
innodb_log_file_size = 192M
innodb_flush_log_at_trx_commit = 0
innodb_thread_concurrency=4
innodb_lock_wait_timeout = 50
innodb_log_buffer_size = 16M
[mysqldump]
quick
max_allowed_packet = 16M
[mysql]
no-auto-rehash
[myisamchk]
key_buffer_size = 20M
sort_buffer_size = 20M
read_buffer = 2M
write_buffer = 2M
[mysqlhotcopy]
interactive-timeout
/usr/local/etc/lighttpd/lighttpd.conf  (Lighttpd+PHP)
var.log_root    = "/var/log/lighttpd"
var.server_root = "/usr/local/www/apache22/data"
var.state_dir   = "/var/run"
var.home_dir    = "/var/spool/lighttpd"
var.conf_dir    = "/usr/local/etc/lighttpd"
var.cache_dir   = "/var/cache/lighttpd"
var.socket_dir  = home_dir + "/sockets"
include "modules.conf"
server.port = 80
server.use-ipv6 = "disable"
server.username  = "www"
server.groupname = "www"
server.document-root = "/usr/local/www/apache22/data/"
server.pid-file = state_dir + "/lighttpd.pid"
server.errorlog             = log_root + "/error.log"
include "conf.d/debug.conf"
server.event-handler = "freebsd-kqueue"
server.network-backend = "writev"
server.max-fds = 2048
server.stat-cache-engine = "simple"
server.max-connections = 1024
index-file.names += (
  "index.xhtml", "index.html", "index.htm", "default.htm", "index.php"
)
url.access-deny             = ( "~", ".inc" )
$HTTP["url"] =~ "\.pdf$" {
  server.range-requests = "disable"
}
static-file.exclude-extensions = ( ".php", ".pl", ".fcgi", ".scgi" )
include "conf.d/mime.conf"
include "conf.d/dirlisting.conf"
server.follow-symlink = "enable"
server.upload-dirs = ( "/var/tmp" )
$SERVER["socket"] == ":80" { }
alias.url = (
"/lg"         => "/usr/local/www/apache22/data/lg/lg.cgi",
"/drupal"     => "/usr/local/www/drupal6"
)
$HTTP["remoteip"] !~ "10.0|172.16|192.168" {
    $HTTP["url"] =~ "^/lg/" {  url.access-deny = ( "" )   }
}

/usr/local/etc/lighttpd/modules.conf
server.modules = (
  "mod_access",
  "mod_alias",
)
include "conf.d/status.conf"
include "conf.d/fastcgi.conf"
include "conf.d/cgi.conf"

/usr/local/etc/lighttpd/fastcgi.conf
server.modules += ( "mod_fastcgi" )
fastcgi.server = (
 ".php" =>
        ((
        "socket" => "/tmp/php-fpm.sock",
        "bin-path" => "/usr/local/bin/php-cgi",
        "bin-environment" => ("PHP_FCGI_CHILDREN" => "16","PHP_FCGI_MAX_REQUESTS" => "10000" ),
        "max-procs" => 2,
        "bin-copy-environment" => ( "PATH", "SHELL", "USER" ),
        "broken-scriptfilename" => "enable" ))
)
/usr/local/etc/php.ini       grep '^[^ ;]' ./php.ini 
[PHP]
engine = On
short_open_tag = Off
asp_tags = Off
precision = 14
output_buffering = 4096
zlib.output_compression = Off
implicit_flush = Off
unserialize_callback_func =
serialize_precision = 17
disable_functions =
disable_classes =
zend.enable_gc = On
expose_php = On
max_execution_time = 300
max_input_time = 300
memory_limit = 512M
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
display_errors = Off
display_startup_errors = Off
log_errors = On
log_errors_max_len = 1024
ignore_repeated_errors = Off
ignore_repeated_source = Off
report_memleaks = On
track_errors = Off
html_errors = On
variables_order = "GPCS"
request_order = "GP"
register_argc_argv = Off
auto_globals_jit = On
post_max_size = 24M
auto_prepend_file =
auto_append_file =
default_mimetype = "text/html"
doc_root =
user_dir =
enable_dl = Off
file_uploads = On
upload_max_filesize = 8M
max_file_uploads = 20
allow_url_fopen = On
allow_url_include = Off
default_socket_timeout = 60
[CLI Server]
cli_server.color = On
[Date]
date.timezone = "Europe/Chisinau"
[filter]
[iconv]
[intl]
[sqlite]
[sqlite3]
[Pcre]
[Pdo]
[Pdo_mysql]
pdo_mysql.cache_size = 2000
pdo_mysql.default_socket=
[Phar]
[mail function]
SMTP = localhost
smtp_port = 25
mail.add_x_header = On
[SQL]
sql.safe_mode = Off
[ODBC]
odbc.allow_persistent = On
odbc.check_persistent = On
odbc.max_persistent = -1
odbc.max_links = -1
odbc.defaultlrl = 4096
odbc.defaultbinmode = 1
[Interbase]
ibase.allow_persistent = 1
ibase.max_persistent = -1
ibase.max_links = -1
ibase.timestampformat = "%Y-%m-%d %H:%M:%S"
ibase.dateformat = "%Y-%m-%d"
ibase.timeformat = "%H:%M:%S"
[MySQL]
mysql.allow_local_infile = On
mysql.allow_persistent = On
mysql.cache_size = 2000
mysql.max_persistent = -1
mysql.max_links = -1
mysql.default_port =
mysql.default_socket =
mysql.default_host =
mysql.default_user =
mysql.default_password =
mysql.connect_timeout = 60
mysql.trace_mode = Off
[MySQLi]
mysqli.max_persistent = -1
mysqli.allow_persistent = On
mysqli.max_links = -1
mysqli.cache_size = 2000
mysqli.default_port = 3306
mysqli.default_socket =
mysqli.default_host =
mysqli.default_user =
mysqli.default_pw =
mysqli.reconnect = Off
[mysqlnd]
mysqlnd.collect_statistics = On
mysqlnd.collect_memory_statistics = Off
[OCI8]
[PostgreSQL]
pgsql.allow_persistent = On
pgsql.auto_reset_persistent = Off
pgsql.max_persistent = -1
pgsql.max_links = -1
pgsql.ignore_notice = 0
pgsql.log_notice = 0
[Sybase-CT]
sybct.allow_persistent = On
sybct.max_persistent = -1
sybct.max_links = -1
sybct.min_server_severity = 10
sybct.min_client_severity = 10
[bcmath]
bcmath.scale = 0
[browscap]
[Session]
session.save_handler = files
session.use_cookies = 1
session.use_only_cookies = 1
session.name = PHPSESSID
session.auto_start = 0
session.cookie_lifetime = 0
session.cookie_path = /
session.cookie_domain =
session.cookie_httponly =
session.serialize_handler = php
session.gc_probability = 1
session.gc_divisor = 1000
session.gc_maxlifetime = 1440
session.bug_compat_42 = Off
session.bug_compat_warn = Off
session.referer_check =
session.cache_limiter = nocache
session.cache_expire = 180
session.use_trans_sid = 0
session.hash_function = 0
session.hash_bits_per_character = 5
url_rewriter.tags = "a=href,area=href,frame=src,input=src,form=fakeentry"
[MSSQL]
mssql.allow_persistent = On
mssql.max_persistent = -1
mssql.max_links = -1
mssql.min_error_severity = 10
mssql.min_message_severity = 10
mssql.compatability_mode = Off
mssql.secure_connection = Off
[Assertion]
[COM]
[mbstring]
[gd]
[exif]
[Tidy]
tidy.clean_output = Off
[soap]
soap.wsdl_cache_enabled=1
soap.wsdl_cache_dir="/tmp"
soap.wsdl_cache_ttl=86400
soap.wsdl_cache_limit = 5
[sysvshm]
[ldap]
ldap.max_links = -1
[mcrypt]
[dba]


3.FreeBSD tunning

Tuning FreeBSD for different applications
http://silverwraith.com/papers/freebsd-tuning.php

FreeBSD performance tuning
http://serverfault.com/questions/64356/freebsd-performance-tuning-sysctls-loader-conf-kernel
http://www.openbsd.ru/docs/howto-sysctl.html

Kernel Customizing
http://www.a1poweruser.com/13.00-Kernal_customizing.htm

BIND
http://tools.ietf.org/html/rfc1035
(DNS - IMPLEMENTATION AND SPECIFICATION)

0) http://ru.wikipedia.org/wiki/DNS
1) http://adw0rd.ru/2009/freebsd-dns-bind9/
2) http://www.cymru.com/Documents/secure-bind-template.html
3) http://habrahabr.ru/blogs/sysadm/120620/ (DNSSec)
http://www.dnsbindeditor.com


JAILS

http://www.cyberciti.biz/faq/how-to-upgrade-freebsd-jail-vps/


SCREEN
http://neophob.com/2007/04/gnu-screen-cheat-sheet/
http://www.softpanorama.org/Utilities/screen.shtml



4.FreeBSD FAQ

1) locate: database too small
ns2# locate mutt
locate: database too small: /var/db/locate.database
/etc/periodic/weekly/310.locate
or alternatively
#/usr/libexec/locate.updatedb
2) PERL install modules
#perl -MCPAN -eshell
cpan> help
cpan> install Bundle::LWP
cpan> install Net::IP
cpan> install Net::Ping
3) Output redirects
Use command >/dev/null if you only want error output.
Use command 2>/dev/null if you don't want error output.
Use command > dev/null 2>&1 if you don't want any output. 
4) Mail
# /etc/rc.d/sendmail status
Cannot 'status' sendmail. Set sendmail_enable to YES in /etc/rc.conf or use 'onestatus' instead of 'status'.
Cannot 'status' sendmail_clientmqueue. Set sendmail_msp_queue_enable to YES in /etc/rc.conf or use 'onestatus' instead of 'status'.

# service sendmail status 
sendmail is not running.
sendmail_clientmqueue is not running.
# /etc/rc.d/sendmail onestatus
sendmail is not running.
sendmail_clientmqueue is not running.
5) Noatime tuning
mount -u -o rw,noatime /usr
6) Reboot in single user mode
# mount -u /
# mount -a
# chsh /bin/tcsh
# chpass -s /bin/bash
7) Custom kernel
# cd /usr/src/sys/i386/conf
# cp GENERIC MYKERNEL
# ee MYKERNEL
# cd /usr/src
# make buildkernel KERNCONF=MYKERNEL; make installkernel KERNCONF=MYKERNEL
8) Remove all those ^M characters from a DOS file
tr -d '\015' < dosfile > newfile
9) Port updates
Adding the following line to /etc/crontab will cause portsnap to update its compressed snapshot and the INDEX files in /usr/ports/, and will send an email if any installed ports are out of date:
0 3 * * * root portsnap -I cron update && pkg_version -vIL=
crontab
30      5       *       *       *       root    portsnap -I cron update && pkg_version -vIL=
30      3       *       *       *       root    /bin/sh /etc/rc.d/ntp

10) Blackholing DDOS
http://www.opennet.ru/base/sec/bsd_stop_flood.txt.html
http://adw0rd.ru/2009/http-ddos-and-ipfw/

11) ICMP Limit (if use server for monitoring)
Limiting icmp unreach response from 244 to 200 packets per second
Limiting icmp unreach response from 257 to 200 packets per second
# sysctl -w net.inet.icmp.icmplim=10000
net.inet.icmp.icmplim: 200 -> 10000
[root@stats /zzz/munin_node]# echo 'net.inet.icmp.icmplim=1000' >> /etc/sysctl.conf
12) Kill a lot of same process
for i in `ps -aux |grep logcheck|awk '{print $2}'`;do kill -9 $i;done
13) Protect important files
# chflags schg /tmp/test
# rm -f /tmp/test
rm: /tmp/test: Operation not permitted
# ls -lo /tmp/test
-rw-r--r--  1 root  wheel  schg 0 Mar 19 08:36 /tmp/test
#chflags noschg /tmp/test
14) Autoconf error while compile
 You should check, where you've got makeinfo. If exists in both directories - /usr/bin and /usr/local/bin, then rename
/usr/bin/makeinfo -> /usr/bin/makeinfo_
This should fix this problem
(i found this solution at some forum)
or
autom4te: need GNU m4 1.4 or later: /usr/local/bin/gm4
gmake[2]: *** [autoconf.in] Error 1
gmake[2]: Leaving directory `/usr/ports/devel/autoconf/work/autoconf-2.69/bin'
gmake[1]: *** [all-recursive] Error 1
gmake[1]: Leaving directory `/usr/ports/devel/autoconf/work/autoconf-2.69'
gmake: *** [all] Error 2
*** Error code 1
solution
deinstall bison and m4, and recompile again
FreeBSD 9.3
[root@zabbix-access-bsd9 /etc]# pkg remove m4-1.4.17_1,1
Updating database digests format: 100%
Checking integrity... done (0 conflicting)
Deinstallation has been requested for the following 2 packages (of 0 packages in the universe):

Installed packages to be REMOVED:
        m4-1.4.17_1,1
        bison-2.7.1,1 (depends on m4-1.4.17_1,1)

The operation will free 2 MB.

Proceed with deinstalling packages? [y/N]: y
[1/2] Deleting bison-2.7.1,1: 100%
[2/2] Deleting m4-1.4.17_1,1: 100%
[root@zabbix-access-bsd9 /etc]# 
[root@zabbix-access-bsd9 /usr/ports/devel/autoconf]# make clean
===>  Cleaning for autoconf-2.69
FreeBSD 9.2
# pkg_info | grep m4
m4-1.4.16_1,1       GNU m4
# pkg_info | grep bison
bison-2.5.1,1       A parser generator from FSF, (mostly) compatible with Yacc
# pkg_delete bison-2.5.1,1
# pkg_delete m4-1.4.16_1,1
15) Automatic restart service
В процессе установки ПО для FreeBSD "правильные" службы автоматически прописывают скрипт запуска в /usr/local/etc/rc.d и управление его поведением определяется в /etc/rc.conf

Однако случается так что успешно запустившись при включении сервера, служба по ряду причин падает позже в процессе работы (такое случается например c dovecot или squid). В результате чего как минимум требуется перезапуск с последующим анализом причин поведения. Про анализ причин поведения отдельная песня, а вот перезапускать в таких редких случаях ручками может получиться с изрядными задержками, пока не выяснится, что что-то перестало работать.

На этот счет я практикую запуск через cron команды которая проверяет все сконфигурированные к запуску скрипты /usr/local/etc/rc.d на предмет поддержки команды status и если эта команда возвращает отрицательный результат (т.е. сервис не активен) то заново запускает его.

Итого в файле /var/cron/tabs/root значится строка

   */5 * * * * /usr/bin/find /usr/local/etc/rc.d/ -type file | xargs -I$ sh -c "($  2>&1 | grep -q -v status) \
      && exit ; ($ status > /dev/null) && exit ; $ start"

В итоге, если служба остановилась, она будет перезапущена в течении 5 минут, и на root придет сообщение с логом запуска (если конечно почтовая подсистема настроена)
Автор: Алексей Волков 
16) Disk performance
INFO: For security recommendations see the security(7) man page.
INFO: For system tuning advice, see the tuning(7) man page.
INFO: To view various system statistics use the systat(1) tool.

ESXI
[root@rs2 /usr/home/sc]# diskinfo -c /dev/da0p2
/dev/da0p2
        512             # sectorsize
        10199433216     # mediasize in bytes (9.5G)
        19920768        # mediasize in sectors
        0               # stripesize
        82944           # stripeoffset
        1240            # Cylinders according to firmware.
        255             # Heads according to firmware.
        63              # Sectors according to firmware.
                        # Disk ident.

I/O command overhead:
        time to read 10MB block      0.099943 sec       =    0.005 msec/sector
        time to read 20480 sectors   6.619615 sec       =    0.323 msec/sector
        calculated command overhead                     =    0.318 msec/sector
17) net-snmp SNMP
**** This port installs snmp daemon, header files and libraries but don't
     invokes snmpd by default.
     If you want to invoke snmpd and/or snmptrapd at startup, put these
     lines into /etc/rc.conf.

        snmpd_enable="YES"
        snmpd_flags="-a"
        snmpd_conffile="/usr/local/share/snmp/snmpd.conf /etc/snmpd.conf"
        snmptrapd_enable="YES"
        snmptrapd_flags="-a -p /var/run/snmptrapd.pid"

**** You may specify the following make variables:

        NET_SNMP_SYS_CONTACT="sylvio@FreeBSD.org"
        NET_SNMP_SYS_LOCATION="Brasilia, BRA"
        DEFAULT_SNMP_VERSION=3
        NET_SNMP_MIB_MODULES="host smux mibII/mta_sendmail ucd-snmp/diskio"
        NET_SNMP_LOGFILE=/var/log/snmpd.log
        NET_SNMP_PERSISTENTDIR=/var/net-snmp

     to define default values (or overwriting defaults).  At least
     setting first two variables, you will not be prompted during
     configuration process.  You may also set

        BATCH="yes"

     to avoid interactive configuration.
18) pkgconf-0.8.9
 ===>  Installing for pkgconf-0.8.9
===>  pkgconf-0.8.9 conflicts with installed package(s):
      pkg-config-0.25_1

      They install files into the same place.
      Please remove them first with pkg_delete(1).
*** Error code 1
 Solution: portmaster -o devel/pkgconf devel/pkg-config
 From:
 /usr/ports/UPDATING
20120726:
  AFFECTS: users of devel/pkg-config
  AUTHOR: bapt@FreeBSD.org
    devel/pkg-config has been replaced by devel/pkgconf
    # portmaster -o devel/pkgconf devel/pkg-config
     or
   # portupgrade -fo devel/pkgconf pkg-config-\*

  pkgng:
  # pkg set -o devel/pkg-config:devel/pkgconf
  # pkg install -f devel/pkgconf
19) Rotate sudolog
touch /var/log/sudolog
echo 'Defaults !syslog' >> /usr/local/etc/sudoers
echo 'Defaults logfile = /var/log/sudolog' >> /usr/local/etc/sudoers

echo 'root ALL=(ALL) ALL' >> /usr/local/etc/sudoers
echo 'zabbix ALL=(ALL) NOPASSWD: /sbin/sysctl, /usr/local/bin/sudo' >> /usr/local/etc/sudoers

echo '/var/log/sudolog 644 5 100 * JC' >> /etc/newsyslog.conf
service newsyslog restart

cat /usr/local/etc/sudoers ; cat /etc/newsyslog.conf; cat /var/log/sudolog

newsyslog -F     will force ALL log files in newsyslog.conf to be rotated immediately.
20) pkg_info: corrupted record (pkgdep line without argument), ignoring

grep "^@pkgdep" /var/db/pkg/*/+CONTENTS | awk '{ if (NF != 2) { print $1 } }' | cut -d':' -f1
I then did a 'portupgrade -f' on those packages. 
Problem solved.

21) FreeBSD FTP server
1) vi /etc/inetd.conf
# uncomment
ftp stream tcp nowait root /usr/libexec/ftpd ftpd -l

2) add inetd_enable="YES"  @ rc.conf
/etc/rc.d/inetd restart
3) echo ftpuser >> /etc/ftpchroot

4) vi /etc/syslog.conf
# add
ftp.info      /var/log/xferlog

 service syslogd restart

5) vi /etc/shells
# add nologin shell
/usr/sbin/nologin

6) Add ftp user
adduser ftpuser
Username: ftpuser
Full name: ftpuser
Uid (Leave empty for default):
Login group [ftp]:
Login group is ftp. Invite ftpuser into other groups? []:
Login class [default]:
Shell (sh csh tcsh bash rbash nologin) [sh]: nologin
Home directory [/home/ftpuser]:
Home directory permissions (Leave empty for default):
Use password-based authentication? [yes]:
Use an empty password? (yes/no) [no]:
Use a random password? (yes/no) [no]: yes
Lock out the account after creation? [no]:
Username   : ftpuser
Password   : <random>
Full Name  : ftpuser
Uid        : 1005
Class      :
Groups     : ftp
Home       : /home/ftpuser
Home Mode  :
Shell      : /usr/sbin/nologin
Locked     : no
OK? (yes/no): yes
adduser: INFO: Successfully added (ftpuser) to the user database.
adduser: INFO: Password for (ftpuser) is: IcsPSQUtx
Add another user? (yes/no): no
Goodbye!

7) Generate random file 100 MBytes
dd if=/dev/random of=myfile.dat bs=$(( 1024 * 1024 )) count=500

21a)  Pure-FTP Virtual users
https://forums.freebsd.org/threads/howto-setup-a-pure-ftpd-server-with-virtual-users.591/
# cat /etc/passwd  | grep -i ftp
user1ftp:*:1003:1003:Virtual FTP user:/usr/home/user1ftp?:/sbin/nologin

pure-pw userdel ftpvirtuser
pure-pw useradd ftpvirtuser -u www -g www -d /usr/local/www/nginx/md185/
***
***
pure-pw mkdb
In case of ...
/usr/local/etc/rc.d/pure-ftpd restart
/usr/local/etc/rc.d/pure-ftpd status
22) Squid config
rc.conf
squid_enable="YES"

/usr/local/etc/squid/squid.conf
# cat ./squid.conf | egrep -v "(^#.*|^$)"
acl all src all
acl manager proto cache_object
acl localhost src 127.0.0.1/32
acl to_localhost dst 127.0.0.0/8 0.0.0.0/32
acl localnet src 10.0.0.0/8     # RFC1918 possible internal network
acl localnet src 172.16.0.0/12  # RFC1918 possible internal network
acl localnet src 192.168.0.0/16 # RFC1918 possible internal network
acl SSL_ports port 443
acl Safe_ports port 80          # http
acl Safe_ports port 21          # ftp
acl Safe_ports port 443         # https
acl Safe_ports port 70          # gopher
acl Safe_ports port 210         # wais
acl Safe_ports port 1025-65535  # unregistered ports
acl Safe_ports port 280         # http-mgmt
acl Safe_ports port 488         # gss-http
acl Safe_ports port 591         # filemaker
acl Safe_ports port 777         # multiling http
acl CONNECT method CONNECT
http_access allow manager localhost
http_access deny manager
http_access deny !Safe_ports
http_access deny CONNECT !SSL_ports
http_access allow localnet
http_access deny all
icp_access allow localnet
icp_access deny all
http_port 3128
hierarchy_stoplist cgi-bin ?
cache_dir ufs /var/log/squid/cache 100 16 256
access_log /var/log/squid/logs/access.log squid
cache_log /var/log/squid/logs/cache.log
pid_filename /var/log/squid/logs/squid.pid
netdb_filename /var/log/squid/logs/netdb.state
refresh_pattern ^ftp:           1440    20%     10080
refresh_pattern ^gopher:        1440    0%      1440
refresh_pattern -i (/cgi-bin/|\?) 0     0%      0
refresh_pattern .               0       20%     4320
acl shoutcast rep_header X-HTTP09-First-Line ^ICY.[0-9]
upgrade_http0.9 deny shoutcast
acl apache rep_header Server ^Apache
broken_vary_encoding allow apache
cache_mgr admins@mydomain
visible_hostname my-proxy
coredump_dir /var/log/squid/cache
cache deny all

# sockstat -4 | grep squid
squid    squid      1904  6  udp4   *:42109               *:*
squid    squid      1904  13 tcp4   *:3128                *:*
squid    squid      1904  14 udp4   *:3130                *:*

23) mc (midnight commander) slow start
check hostname from rc.conf and /etc/hosts
::1                     localhost
127.0.0.1               localhost
127.0.0.2               zabbix221.domain.com      zabbix221
1.1.1.1         zabbix221.domain.com freebsd92

24) Migrate FreeBSD users from one system to another
Move user entries from the following old files:
/etc/passwd
/etc/group
/etc/master.passwd
Then run the following command to rebuild the password database:
pwd_mkdb -p /etc/master.passwd 

25) pkg_info @ 25_08_2014

apr-1.4.8.1.5.3     Apache Portability Library
argp-standalone-1.3_2 Standalone version of arguments parsing functions from GLIB
atop-2.0.2.b2       ASCII Monitor for system resources and process activity
autoconf-2.69       Automatically configure source code on many Un*x platforms
autoconf-wrapper-20130530 Wrapper script for GNU autoconf
automake-1.14       GNU Standards-compliant Makefile generator
automake-wrapper-20131203 Wrapper script for GNU automake
bash-static-4.2.45  The GNU Project's Bourne Again SHell
bigreqsproto-1.1.2  BigReqs extension headers
bison-2.7.1,1       A parser generator from FSF, (mostly) compatible with Yacc
boost-jam-1.52.0_1  Build tool from the boost.org
boost-jam-1.55.0    Build tool from the boost.org
boost-libs-1.52.0_2 Free portable C++ libraries (without Boost.Python)
bsdadminscripts-6.1.1_4 Collection of administration scripts
bsdinfo-0.22        A simple utility to display system-based information
bsdpan-App-cpanminus-1.7004 App::cpanminus - get, unpack, build and install modules fro
bsdpan-Archive-Extract-0.72 Archive::Extract - A generic archive extracting mechanism
bsdpan-Archive-Tar-2.00 Archive::Tar - module for manipulations of tar archives
bsdpan-Attribute-Handlers-0.96 Attribute::Handlers - Simpler definition of attribute handl
bsdpan-AutoLoader-5.74 AutoLoader - load subroutines only on demand
bsdpan-B-Debug-1.21 B::Debug - Walk Perl syntax tree, printing debug info about
bsdpan-B-Lint-1.17  B::Lint - Perl lint
bsdpan-CGI-Fast-2.02 CGI::Fast - CGI Interface for Fast CGI
bsdpan-CGI.pm-4.03  CGI - Handle Common Gateway Interface requests and response
bsdpan-CPAN-2.05    CPAN - query, download and build perl modules from CPAN sit
bsdpan-CPAN-DistnameInfo-0.12 CPAN::DistnameInfo - Extract distribution name and version
bsdpan-CPAN-Meta-Requirements-2.126 CPAN::Meta::Requirements - a set of version requirements fo
bsdpan-CPANPLUS-0.9152 CPANPLUS - API & CLI access to the CPAN mirrors
bsdpan-Carp-1.3301  Carp - alternative warn and die for modules
bsdpan-Cisco-Management-0.06 Cisco::Management - Interface for Cisco Management
bsdpan-Cisco-Management-0.08 Cisco::Management - Interface for Cisco Management
bsdpan-Compress-Raw-Bzip2-2.064 Compress::Raw::Bzip2 - Low-Level Interface to bzip2 compres
bsdpan-Compress-Raw-Zlib-2.065 Compress::Raw::Zlib - Low-Level Interface to zlib compressi
bsdpan-Convert-ASN1-0.26 Unknown perl module
bsdpan-DB_File-1.831 DB_File - Perl5 access to Berkeley DB version 1.x
bsdpan-Data-Dumper-2.151 Data::Dumper - stringified perl data structures, suitable f
bsdpan-Devel-PPPort-3.24 Devel::PPPort - Perl/Pollution/Portability
bsdpan-Digest-MD5-2.53 Digest::MD5 - Perl interface to the MD5 Algorithm
bsdpan-Digest-SHA-5.92 Digest::SHA - Perl extension for SHA-1/224/256/384/512
bsdpan-Encode-2.62  Encode - character encodings in Perl
bsdpan-Encode-Locale-1.03 Encode::Locale - Determine the locale encoding
bsdpan-Exporter-5.70 Exporter - Implements default import method for modules
bsdpan-ExtUtils-MakeMaker-6.98 ExtUtils::MakeMaker - Create a module Makefile
bsdpan-ExtUtils-Manifest-1.65 ExtUtils::Manifest - utilities to write and check a MANIFES
bsdpan-FCGI-0.77    FCGI - Fast CGI module
bsdpan-File-Fetch-0.48 File::Fetch - A generic file fetching mechanism
bsdpan-File-Listing-6.04 File::Listing - parse directory listing
bsdpan-File-Path-2.09 File::Path - Create or remove directory trees
bsdpan-Filter-1.49  Filter::Util::Call - Perl Source Filter Utility Module
bsdpan-Filter-Simple-0.91 Filter::Simple - Simplified source filtering
bsdpan-Foo-Bar-0.01 Sample - Foo foo sample foo
bsdpan-Getopt-Long-2.42 Getopt::Long - Extended processing of command line options
bsdpan-HTML-Parser-3.71 HTML::Parser - HTML parser class
bsdpan-HTML-Tagset-3.20 HTML::Tagset - data tables useful in parsing HTML
bsdpan-HTTP-Cookies-6.01 HTTP::Cookies - HTTP cookie jars
bsdpan-HTTP-Daemon-6.01 HTTP::Daemon - a simple http server class
bsdpan-HTTP-Date-6.02 HTTP::Date - date conversion routines
bsdpan-HTTP-Message-6.06 HTTP::Message - HTTP style message (base class)
bsdpan-HTTP-Negotiate-6.01 HTTP::Negotiate - choose a variant to serve
bsdpan-IO-1.25      IO - load various IO modules
bsdpan-IO-Compress-2.064 IO::Compress::Base - Base Class for IO::Compress modules
bsdpan-IO-HTML-1.00 IO::HTML - Open an HTML file with automatic charset detecti
bsdpan-IPC-Cmd-0.92 IPC::Cmd - finding and running system commands made easy
bsdpan-IPC-SysV-2.04 IPC::SysV - System V IPC constants and system calls
bsdpan-LWP-MediaTypes-6.02 LWP::MediaTypes - guess media type for a file or a URL
bsdpan-Locale-Maketext-1.25 Unknown perl module
bsdpan-Log-Message-0.08 Log::Message - A generic message storing mechanism;
bsdpan-Log-Message-Simple-0.10 Log::Message::Simple - Simplified interface to Log::Message
bsdpan-MIME-Base64-3.14 MIME::Base64 - Encoding and decoding of base64 strings
bsdpan-Math-Base85-0.2 Math::Base85 - Perl extension for base 85 numbers, as refer
bsdpan-Memoize-1.03 Memoize - Make functions faster by trading space for time
bsdpan-Module-CoreList-5.021002 Unknown perl module
bsdpan-Module-Load-0.32 Module::Load - runtime require of both modules and files
bsdpan-Module-Load-Conditional-0.62 Module::Load::Conditional - Looking up module information /
bsdpan-Net-DNS-0.78 Net::DNS - Perl Interface to the Domain Name System
bsdpan-Net-HTTP-6.06 Net::HTTP - Low-level HTTP connection (client)
bsdpan-Net-HTTP-6.07 Net::HTTP - Low-level HTTP connection (client)
bsdpan-Net-IP-1.26  Net::IP - Perl extension for manipulating IPv4/IPv6 address
bsdpan-Net-IPv4Addr-0.10 Net::IPv4Addr - Perl extension for manipulating IPv4 addres
bsdpan-Net-IPv6Addr-0.2 Net::IPv6Addr -- check validity of IPv6 addresses
bsdpan-Net-Ping-2.41 Net::Ping - check a remote host for reachability
bsdpan-Net-SNMPTrapd-0.12 Net::SNMPTrapd - Perl implementation of SNMP Trap Listener
bsdpan-Net-SNMPTrapd-0.13 Net::SNMPTrapd - Perl implementation of SNMP Trap Listener
bsdpan-Net-SSH-0.09 Net::SSH - Perl extension for secure shell
bsdpan-Net-Syslogd-0.10 Net::Syslogd - Perl implementation of Syslog Listener
bsdpan-Net-Syslogd-0.11 Net::Syslogd - Perl implementation of Syslog Listener
bsdpan-Net-TFTPd-0.06 Net::TFTPd - Perl extension for Trivial File Transfer Proto
bsdpan-Net-Telnet-3.04 Net::Telnet - interact with TELNET port or other TCP ports
bsdpan-Net-Telnet-Cisco-1.10 Net::Telnet::Cisco - interact with a Cisco router
bsdpan-NetSNMP-default_store-5.0404 NetSNMP::default_store - Perl extension for Net-SNMP generi
bsdpan-Object-Accessor-0.48 Object::Accessor - interface to create per object accessors
bsdpan-Package-Constants-0.04 Package::Constants - List all constants declared in a packa
bsdpan-Params-Check-0.38 Params::Check - A generic input parsing/checking mechanism.
bsdpan-PathTools-3.47 Cwd - get pathname of current working directory
bsdpan-PerlIO-via-QuotedPrint-0.07 PerlIO::via::QuotedPrint - PerlIO layer for quoted-printabl
bsdpan-Pod-Checker-1.71 Pod::Checker - check pod documents for syntax errors
bsdpan-Pod-Escapes-1.06 Pod::Escapes - for resolving Pod EE<lt>...E<gt> sequences
bsdpan-Pod-Parser-1.62 Pod::Find - find POD documents in directory trees
bsdpan-Pod-Perldoc-3.23 Pod::Perldoc - Look up Perl documentation in Pod format.
bsdpan-Pod-Simple-3.28 Unknown perl module
bsdpan-Pod-Usage-1.63 Pod::Usage, pod2usage() - print a usage message from embedd
bsdpan-Pod-Usage-1.64 Pod::Usage - print a usage message from embedded pod docume
bsdpan-Safe-2.35    Safe - Compile and execute code in restricted compartments
bsdpan-Scalar-List-Utils-1.39 List::Util - A selection of general-utility list subroutine
bsdpan-Search-Dict-1.07 Search::Dict - look - search for key in dictionary file
bsdpan-Socket-2.013 C<Socket> - networking constants and support functions
bsdpan-Socket-2.014 C<Socket> - networking constants and support functions
bsdpan-Socket6-0.25 Socket6 - IPv6 related part of the C socket.h defines and s
bsdpan-Storable-2.51 Storable - persistence for Perl data structures
bsdpan-Sys-Syslog-0.33 Sys::Syslog - Perl interface to the UNIX syslog(3) calls
bsdpan-Term-Cap-1.16 Term::Cap - Perl termcap interface
bsdpan-Term-UI-0.42 Term::UI - Term::ReadLine UI made easy
bsdpan-TermReadKey-2.32 Term::ReadKey - A perl module for simple terminal control
bsdpan-Test-1.26    Test - provides a simple framework for writing test scripts
bsdpan-Test-Deep-0.112 Test::Deep - Extremely flexible deep comparison
bsdpan-Test-Harness-3.32 Test::Harness - Run Perl standard test scripts with statist
bsdpan-Test-NoWarnings-1.04 Test::NoWarnings - Make sure you didn't emit any warnings w
bsdpan-Test-Simple-1.001003 Test::Simple - Basic utilities for writing tests.
bsdpan-Test-Tester-0.109 Test::Tester - Ease testing test modules built with Test::B
bsdpan-Text-ParseWords-3.29 Text::ParseWords - parse text into an array of tokens or ar
bsdpan-Text-Soundex-3.04 Text::Soundex - Implementation of the soundex algorithm.
bsdpan-Text-Tabs+Wrap-2013.0523 Text::Wrap - line wrapping to form simple paragraphs
bsdpan-Thread-Queue-3.05 Thread::Queue - Thread-safe queues
bsdpan-Tie-File-1.00 Tie::File - Access the lines of a disk file via a Perl arra
bsdpan-Time-HiRes-1.9726 Time::HiRes - High resolution alarm, sleep, gettimeofday, i
bsdpan-Time-Piece-1.27 Time::Piece - Object Oriented time objects
bsdpan-URI-1.60     URI - Uniform Resource Identifiers (absolute and relative)
bsdpan-URI-1.64     URI - Uniform Resource Identifiers (absolute and relative)
bsdpan-Unicode-Collate-1.07 Unicode::Collate - Unicode Collation Algorithm
bsdpan-Unicode-Normalize-1.18 Unicode::Normalize - Unicode Normalization Forms
bsdpan-WWW-RobotRules-6.02 WWW::RobotRules - database of robots.txt-derived permission
bsdpan-XML-NamespaceSupport-1.11 XML::NamespaceSupport - a simple generic namespace support
bsdpan-XML-Parser-2.41 XML::Parser - A perl module for parsing XML documents
bsdpan-XML-SAX-0.99 XML::SAX - Simple API for XML
bsdpan-XML-SAX-Base-1.08 XML::SAX::Base - Base class SAX Drivers and Filters
bsdpan-XML-SAX-Expat-0.50 XML::SAX::Expat - SAX2 Driver for Expat (XML::Parser)
bsdpan-XML-SAX-Expat-0.51 XML::SAX::Expat - SAX2 Driver for Expat (XML::Parser)
bsdpan-XML-Simple-2.20 XML::Simple - Easily read/write XML (esp config files)
bsdpan-YAML-0.88    YAML - YAML Ain't Markup Language (tm)
bsdpan-install-0.01 install - Dummy module that prevents unexpected results fro
bsdpan-libnet-1.23  Net::Cmd - Network Command class (as used by FTP, SMTP etc)
bsdpan-libwww-perl-6.05 LWP - The World-Wide Web library for Perl
bsdpan-libwww-perl-6.08 LWP - The World-Wide Web library for Perl
bsdpan-local-lib-2.000012 local::lib - create and use a local lib/ for perl modules w
bsdpan-parent-0.228 parent - Establish an ISA relationship with base classes at
bsdpan-podlators-2.5.3 Unknown perl module
bsdpan-threads-1.92 threads - Perl interpreter-based threads
bsdpan-threads-shared-1.46 threads::shared - Perl extension for sharing data structure
bsnmp-ucd-0.4.0     A bsnmpd module that implements parts of UCD-SNMP-MIB
ca_root_nss-3.15.3.1 The root certificate bundle from the Mozilla Project
cmake-2.8.12.1      Cross-platform Makefile generator
cmake-modules-2.8.12.1 Modules and Templates for CMake
compat6x-amd64-6.4.604000.200810_3 Convenience package to install the compat6x libraries
coreutils-8.20_2    The Free Software Foundation's core utilities
curl-7.33.0_1       Non-interactive tool to get files from FTP, GOPHER, HTTP(S)
db41-4.1.25_4       The Berkeley DB package, revision 4.1
db42-4.2.52_5       The Berkeley DB package, revision 4.2
dhcpdump-1.8        Decode and diagnose sniffed DHCP packets
dialog4ports-0.1.5_2 Console Interface to configure ports
diffstat-1.57       Makes a histogram summarizing "diff" output
dmidecode-2.12      Tool for dumping DMI (SMBIOS) contents in human-readable fo
dtpstree-1.0.3      Display a tree of processes
expat-2.1.0         XML 1.0 parser written in C
fontconfig-2.10.95,1 XML-based font configuration API for X Windows
fpdns-0.10.0.20130404 Fingerprinting DNS servers
fping-3.5           Quickly ping N hosts w/o flooding the network
freeipmi-1.3.4      Library and tools to support IPMI-capable hardware
freetype2-2.5.0.1   Free and portable TrueType font rendering engine
gawk-4.1.0          The GNU version of Awk
gdbm-1.10           GNU database manager
gettext-0.18.3.1    GNU gettext package
glib-2.36.3         Some useful routines of C programming (current stable versi
gmake-3.82_1        GNU version of 'make' utility
gsed-4.2.2          The GNU stream editor
help2man-1.43.3     Automatically generating simple manual pages from program o
icu-50.1.2          International Components for Unicode (from IBM)
inputproto-2.3      Input extension headers
ipmitool-1.8.12_4   CLI to manage IPMI systems
jpeg-8_4            IJG's jpeg compression utilities
jwhois-4.0_3        An improved WHOIS client capable of selecting server to que
kbproto-1.0.6       KB extension headers
libICE-1.0.8,1      Inter Client Exchange library for X11
libSM-1.2.2,1       Session Management library for X11
libX11-1.6.2,1      X11 library
libXScrnSaver-1.2.2 The XScrnSaver library
libXau-1.0.8        Authentication Protocol library for X11
libXaw-1.0.12,2     X Athena Widgets library
libXdmcp-1.1.1      X Display Manager Control Protocol library
libXext-1.3.2,1     X11 Extension library
libXft-2.3.1        Client-sided font API for X applications
libXmu-1.1.2,1      X Miscellaneous Utilities libraries
libXp-1.0.2,1       X print library
libXpm-3.5.11       X Pixmap library
libXrender-0.9.8    X Render extension library
libXt-1.1.4,1       X Toolkit library
libcheck-0.9.11     Unit test framework for C
libexecinfo-1.1_3   A library for inspecting program's backtrace
libffi-3.0.13       Foreign Function Interface
libgcrypt-1.5.3     General purpose crypto library based on code used in GnuPG
libgpg-error-1.12   Common error values for all GnuPG components
libiconv-1.14_1     A character set conversion library
libidn-1.28_1       Internationalized Domain Names command line tool
libltdl-2.4.2_2     System independent dlopen wrapper
libmcrypt-2.5.8     Multi-cipher cryptographic library (used in PHP)
libmcrypt-2.5.8_1   Multi-cipher cryptographic library (used in PHP)
libnet10-1.0.2a_5,1 A C library for creating IP packets
libpthread-stubs-0.3_4 This library provides weak aliases for pthread functions
libpthread-stubs-0.3_5 This library provides weak aliases for pthread functions
libsigsegv-2.10     Handling page faults in user mode
libssh2-1.4.3_1,2   Library implementing the SSH2 protocol
libtool-2.4.2_2     Generic shared library support script
libxcb-1.9.1_1      The X protocol C-language Binding (XCB) library
libxml2-2.8.0_3     XML parser library for GNOME
libxslt-1.1.28_1    The XSLT C library for GNOME
libyaml-0.1.4_2     A YAML 1.1 parser and emitter written in C
lighttpd-1.4.33     Secure, fast, compliant, and flexible Web Server
lsof-4.88.e_1,8     Lists information about open files (similar to fstat(1))
lsof-4.88.g,8       Lists information about open files (similar to fstat(1))
lynx-2.8.7.2,1      Non-graphical, text-based World-Wide Web client
m4-1.4.17,1         GNU m4
mc-4.8.10           Midnight Commander, a free Norton Commander Clone
mtr-nox11-0.85_1    Traceroute and ping in a single network diagnostic tool
mysql55-client-5.5.34 Multithreaded SQL database (client)
mysql55-server-5.5.34 Multithreaded SQL database (server)
ncdu-1.10           Ncurses du(1)
ncurses-5.9_3       Library for terminal-independent, full-screen output
net-snmp-5.7.2_3    An extendable SNMP implementation
oniguruma4-4.7.1    BSDL Regular Expressions library compatible with POSIX/GNU/
openipmi-2.0.19_2   Complex IPMI management software
p5-DBD-mysql-4.025  MySQL driver for the Perl5 Database Interface (DBI)
p5-DBI-1.630        The perl5 Database Interface.  Required for DBD::* modules
p5-Digest-HMAC-1.03 Perl5 interface to HMAC Message-Digest Algorithms
p5-IO-Socket-INET6-2.69 Perl module with object interface to AF_INET6 domain socket
p5-Locale-gettext-1.05_3 Message handling functions
p5-Net-DNS-0.73     Perl5 interface to the DNS resolver, and dynamic updates
p5-Socket6-0.25_1   IPv6 related part of the C socket.h defines and structure m
p5-XML-Parser-2.41_1 Perl extension interface to James Clark's XML parser, expat
p5-libxml-0.08      Collection of Perl5 modules for working with XML
patch-2.7_1         GNU patch utility
pcre-8.33           Perl Compatible Regular Expressions library
pcre-8.34_2         Perl Compatible Regular Expressions library
perl5-5.16.3_11     Practical Extraction and Report Language
perl5-5.16.3_2      Practical Extraction and Report Language
php5-5.4.23         PHP Scripting Language
php5-bcmath-5.4.23  The bcmath shared extension for php
php5-ctype-5.4.23   The ctype shared extension for php
php5-curl-5.4.23_1  The curl shared extension for php
php5-dom-5.4.23     The dom shared extension for php
php5-extensions-1.7 A "meta-port" to install PHP extensions
php5-filter-5.4.23  The filter shared extension for php
php5-gd-5.4.23      The gd shared extension for php
php5-gettext-5.4.23 The gettext shared extension for php
php5-hash-5.4.23    The hash shared extension for php
php5-iconv-5.4.23   The iconv shared extension for php
php5-json-5.4.23    The json shared extension for php
php5-mbstring-5.4.23 The mbstring shared extension for php
php5-mcrypt-5.4.23  The mcrypt shared extension for php
php5-mysql-5.4.23   The mysql shared extension for php
php5-mysqli-5.4.23  The mysqli shared extension for php
php5-pdo-5.4.23     The pdo shared extension for php
php5-pdo_sqlite-5.4.23 The pdo_sqlite shared extension for php
php5-phar-5.4.23    The phar shared extension for php
php5-posix-5.4.23   The posix shared extension for php
php5-session-5.4.23 The session shared extension for php
php5-simplexml-5.4.23 The simplexml shared extension for php
php5-snmp-5.4.23    The snmp shared extension for php
php5-soap-5.4.23    The soap shared extension for php
php5-sockets-5.4.23 The sockets shared extension for php
php5-sqlite3-5.4.23 The sqlite3 shared extension for php
php5-tokenizer-5.4.23 The tokenizer shared extension for php
php5-xml-5.4.23     The xml shared extension for php
php5-xmlreader-5.4.23 The xmlreader shared extension for php
php5-xmlwriter-5.4.23 The xmlwriter shared extension for php
pkg-1.1.4_1         New generation package manager
pkgconf-0.9.3       Utility to help to configure compiler and linker flags
png-1.5.17          Library for manipulating PNG images
popt-1.16           A getopt(3) like library with a number of enhancements, fro
portaudit-0.6.1     Checks installed ports against a list of security vulnerabi
portupgrade-2.4.11.2_1,2 FreeBSD ports/packages administration and management tool s
printproto-1.0.5    Print extension headers
procmail-3.22_7     Local mail delivery agent
py27-tkinter-2.7.6_4 Python bindings to the Tk widget set
python-2.7_1,2      The "meta-port" for the default version of Python interpret
python2-2_1         The "meta-port" for version 2 of the Python interpreter
python27-2.7.6_1    Interpreted object-oriented programming language
qpress-1.1          Portable file archiver using QuickLZ
quilt-0.60          A collection of bash scripts to ease working with patch fil
renderproto-0.11.1  RenderProto protocol headers
ripe-whois-3.2.2    The RIPE whois client version 3
ruby-1.9.3.448,1    An object-oriented interpreted scripting language
ruby19-bdb-0.6.6_1  Ruby interface to Oracle Berkeley DB revision 2 or later
scons-2.3.0         Build tool alternative to make
scrnsaverproto-1.2.2 ScrnSaver extension headers
sendEmail-1.56_2    Lightweight, completely command line based, SMTP email agen
serf-1.3.2_1        Serf HTTP client library
spawn-fcgi-1.6.3    spawn-fcgi is used to spawn fastcgi applications
spawn-fcgi-1.6.4    Spawns fastcgi applications
sqlite3-3.8.0.2     SQL database engine in a C library
subversion-1.8.5    Version control system
sudo-1.8.8          Allow others to run commands as root
sysinfo-1.0.1       Utility used to gather system configuration information
t1lib-5.1.2_2,1     Type 1 font rasterization library for Unix/X11
tcl86-8.6.1         Tool Command Language
tcping-1.3.5        Do a TCP connect to the given IP/port combination
tcpshow-1.74_1      Decode tcpdump(1) output
tcptraceroute-1.4_2 Traceroute implementation using TCP packets
tix-8.4.3_1         An extension to the Tk toolkit
tk86-8.6.1          Graphical toolkit for Tcl
trafshow-5.2.3_2,1  Full screen visualization of network traffic
unzip-6.0_1         List, test, and extract compressed files in a ZIP archive
wget-1.14_2         Retrieve files from the Net via HTTP(S) and FTP
whowatch-1.4_1      Displays information in real time about users currently log
xcb-proto-1.8       The X protocol C-language Binding (XCB) protocol
xcmiscproto-1.2.2   XCMisc extension headers
xextproto-7.2.1     XExt extension headers
xf86bigfontproto-1.2.0 XFree86-Bigfont extension headers
xorg-macros-1.17.1  X.Org development aclocal macros
xproto-7.0.24       X11 protocol headers
xtrabackup-2.1.4    OpenSource version of InnoDB backup with support of Percona
xtrans-1.2.7        Abstract network code for X
26) cleanup folder by crontab
FreeBSD:
# delete zabbix backups older than 120 days
17       5       *       *       *      root   find /usr/BACKUPS -type f -mtime +120d -delete > /dev/null 2>&1

CentOS:
17       5       *       *       *      root   find /backup/BACKUPS -type f -mtime +30 -delete > /dev/null 2>&1

27) After Freebsd 9.0 - > upgrade to 10.1 was neede to fix some issues:
pkgdb -Ff   
portmaster -o lang/perl5.12
portmaster -o lang/perl5.14
portupgrade -f 'p5-*'
#portmaster net-mgmt/mrtg




99) ...future