вторник, 2 октября 2012 г.

iptables features

Makes iptables wait 15 seconds between new connections from the same IP:
iptables -A INPUT -p tcp -i eth0 -m state --state NEW --dport 22 -m recent --update --seconds 15 -j DROP
iptables -A INPUT -p tcp -i eth0 -m state --state NEW --dport 22 -m recent --set -j ACCEPT

Same, but with counting of attempts: 
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set --name SSH 
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 5 --rttl --name SSH -j DROP 

Block Well-Known TCP Attacks

Blocking portscan

# Attempt to block portscans
# Anyone who tried to portscan us is locked out for an entire day.
iptables -A INPUT   -m recent --name portscan --rcheck --seconds 86400 -j DROP
iptables -A FORWARD -m recent --name portscan --rcheck --seconds 86400 -j DROP

# Once the day has passed, remove them from the portscan list
iptables -A INPUT   -m recent --name portscan --remove
iptables -A FORWARD -m recent --name portscan --remove

# These rules add scanners to the portscan list, and log the attempt.
iptables -A INPUT   -p tcp -m tcp --dport 139 -m recent --name portscan --set -j LOG --log-prefix "Portscan:"
iptables -A INPUT   -p tcp -m tcp --dport 139 -m recent --name portscan --set -j DROP

iptables -A FORWARD -p tcp -m tcp --dport 139 -m recent --name portscan --set -j LOG --log-prefix "Portscan:"
iptables -A FORWARD -p tcp -m tcp --dport 139 -m recent --name portscan --set -j DROP


Spoofed/Invalid packets

# Reject spoofed packets
# These adresses are mostly used for LAN's, so if these would come to a WAN-only server, drop them.
iptables -A INPUT -s 10.0.0.0/8 -j DROP
iptables -A INPUT -s 169.254.0.0/16 -j DROP
iptables -A INPUT -s 172.16.0.0/12 -j DROP
iptables -A INPUT -s 127.0.0.0/8 -j DROP

#Multicast-adresses.
iptables -A INPUT -s 224.0.0.0/4 -j DROP
iptables -A INPUT -d 224.0.0.0/4 -j DROP
iptables -A INPUT -s 240.0.0.0/5 -j DROP
iptables -A INPUT -d 240.0.0.0/5 -j DROP
iptables -A INPUT -s 0.0.0.0/8 -j DROP
iptables -A INPUT -d 0.0.0.0/8 -j DROP
iptables -A INPUT -d 239.255.255.0/24 -j DROP
iptables -A INPUT -d 255.255.255.255 -j DROP

# Drop all invalid packets
iptables -A INPUT -m state --state INVALID -j DROP
iptables -A FORWARD -m state --state INVALID -j DROP
iptables -A OUTPUT -m state --state INVALID -j DROP

Block Smurf attacks

# Stop smurf attacks
iptables -A INPUT -p icmp -m icmp --icmp-type address-mask-request -j DROP
iptables -A INPUT -p icmp -m icmp --icmp-type timestamp-request -j DROP
iptables -A INPUT -p icmp -m icmp -j DROP

# Drop excessive RST packets to avoid smurf attacks
iptables -A INPUT -p tcp -m tcp --tcp-flags RST RST -m limit --limit 2/second --limit-burst 2 -j ACCEPT


Optimize netfilter's Performance Using ipset

If you write a lot of similar rules based on mere IP, port, or both, consider using ipset to optimize netfilter's performance.
For example:
iptables -s 192.168.1.11 -j ACCEPT
iptables -s 192.168.1.27 -j ACCEPT
iptables -s 192.168.1.44 -j ACCEPT
... hundreds of similar rules ...
iptables -s 192.168.251.177 -j ACCEPT
This means that a packet with the source address of 192.168.251.177 must first traverse hundreds of rules before it can get its verdict of ACCEPT.
Of course, experienced sysadmins will split the rules by subnet. But that still means hundreds of rules.
ipset to the rescue!
First, define an IP Set of ipmap type:
ipset -N Allowed_Hosts ipmap --network 192.168.0.0/16
Then, populate it with the addresses:
for ip in $LIST_OF_ALLOWED_IP; do ipset -A Allowed_Hosts $ip; done
Finally, replace the hundreds of iptables rules above with one rule:
iptables -m set --match-set Allowed_Hosts src -j ACCEPT



http://serverfault.com/questions/245711/iptables-tips-tricks

четверг, 6 сентября 2012 г.

Отключение IPv6

В первую очередь, необходимо отредактировать файл /etc/modprobe.d/aliases:
$ sudo vim /etc/modprobe.d/aliases
И привести его, к следующему виду:
alias net-pf-10 ipv6 off
alias net-pf-10 off
alias ipv6 off
Если в файле присутствует строка "alias net-pf-10 ipv6", то ее необходимо закомментировать.
Далее, отключаем IPv6 в ядре:
$ echo 1 | sudo tee /proc/sys/net/ipv6/conf/all/disable_ipv6
А так же, добавляем строчку эту операции в автозагрузку. Скрипт /etc/rc.local должен выглядеть приблизительно следующим образом:
$ tail /etc/rc.local 
#....
echo 1 > /proc/sys/net/ipv6/conf/all/disable_ipv6
#
# By default this script does nothing.
exit 0
Далее, блокируем загрузку соответствующего модуля:
$ echo "blacklist ipv6" | sudo tee -a /etc/modprobe.d/blacklist
# в зависимости от версии, может быть и так:
# echo "blacklist ipv6" | sudo tee -a /etc/modprobe.d/blacklist.conf
И наконец, прописываем в grub опцию, отключающую загрузку IPv6 ():
$ sudo vim /boot/grub/menu.lst
Если, допустим, конфигурация загрузки у Вас выглядит так:
title           Ubuntu 9.10, kernel 2.6.31-20-generic
uuid            08b70bd0-5a61-4f9c-a8b8-464c5beb48e2
kernel         /boot/vmlinuz-2.6.31-20-generic root=UUID=08b70bd0-5a61-4f9c-a8b8-464c5beb48e2 ro nohotplug quiet splash
initrd          /boot/initrd.img-2.6.31-20-generic
quiet
то после редактирования конфигурация grub должна выглядеть так:
title           Ubuntu 9.10, kernel 2.6.31-20-generic
uuid            08b70bd0-5a61-4f9c-a8b8-464c5beb48e2
kernel          /boot/vmlinuz-2.6.31-20-generic root=UUID=08b70bd0-5a61-4f9c-a8b8-464c5beb48e2 ro nohotplug quiet splash ipv6.disable=1
initrd          /boot/initrd.img-2.6.31-20-generic
quiet
Все. Теперь необходимо перезагрузить компьютер. И убедиться, что нет никаких сетевых соединений, использующих IPv6:
$ sudo netstat -npl | grep -E "tcp6|udp6" | wc -l
 
 
 
http://debianworld.ru/articles/otklyuchenie-ipv6-v-ubuntu-debian/ 

пятница, 24 августа 2012 г.

Восстановление пакетов из бэкапа

Файлик dpkg.list позволяет быстро установить все необходимые пакеты 
(перед этим лучше сначала перенести учётные записи).





Пулучаем писок установленных пакетов 
dpkg --get-selections > /root/backups/dpkg.list 
 
Установка пакетов 
dpkg --set-selections < dpkg.list
apt-get dselect-upgrade 

вторник, 21 августа 2012 г.

Usefull zabbix UserParameters

# Network: ARP entries [Entries]
 
UserParameter=arp.entries,grep -c -v 'HW type' /proc/net/arp
 
# System: CPU speed []
 
UserParameter=cpuspeed.core0,grep MHz /proc/cpuinfo | head -n 1 | cut -c 12- | awk '{ sum += $1 } END { print sum }'
UserParameter=cpuspeed.core1,grep MHz /proc/cpuinfo | tail -n 1 | cut -c 12- | awk '{ sum += $1 } END { print sum }'
 
# System: HDD SMART Temperature
 
UserParameter=hdd_smart_temp[*],smartctl -a /dev/$1 |awk '/194 Tempera/ {print $4}'
 
# Detailed process count
 
UserParameter=processes_uninterruptible,ps axo state= |grep -c D
UserParameter=processes_runnable,ps axo state= |grep -c R
UserParameter=processes_sleeping,ps axo state= |grep -c S
UserParameter=processes_stopped,ps axo state= |grep -c T
UserParameter=processes_paging,ps axo state= |grep -c W
UserParameter=processes_dead,ps axo state= |grep -c X
UserParameter=processes_zombie,ps axo state= |grep -c Z
 
# Number of process forks per second
 
UserParameter=processes_forks,awk '/processes/ {print $2}' /proc/stat
 
# Available entropy
 
UserParameter=entropy,cat /proc/sys/kernel/random/entropy_avail
 
 
# WiFi level, noise, and network values
 
# Quality - link : general quality of the reception.
UserParameter=wifi_quality,awk -F'[ :]*' '/:/ {gsub(/\. /," ",$0); print $4; }' /proc/net/wireless
# Quality - level : signal strength at the receiver.
UserParameter=wifi_level,awk -F'[ :]*' '/:/ {gsub(/\. /," ",$0); print $5; }' /proc/net/wireless
# Quality - noise : silence level (no packet) at the receiver.
UserParameter=wifi_noise,awk -F'[ :]*' '/:/ {gsub(/\. /," ",$0); print $6; }' /proc/net/wireless
# Discarded - nwid : number of discarded packets due to invalid network id.
UserParameter=wifi_d_nwid,awk -F'[ :]*' '/:/ {gsub(/\. /," ",$0); print $7; }' /proc/net/wireless
# Discarded - crypt : number of packet unable to decrypt.
UserParameter=wifi_d_crypt,awk -F'[ :]*' '/:/ {gsub(/\. /," ",$0); print $8; }' /proc/net/wireless
# Discarded - misc
UserParameter=wifi_d_misc,awk -F'[ :]*' '/:/ {gsub(/\. /," ",$0); print $11; }' /proc/net/wireless
# Missed Beacons
UserParameter=wifi_mbeac,awk -F'[ :]*' '/:/ {gsub(/\. /," ",$0); print $12; }' /proc/net/wireless
 
# Networking: Connection tracking
 
UserParameter=conntrack_established,sudo grep -c ESTABLISHED /proc/net/ip_conntrack
UserParameter=conntrack_fin_wait,sudo grep -c FIN_WAIT /proc/net/ip_conntrack
UserParameter=conntrack_time_wait,sudo grep -c TIME_WAIT /proc/net/ip_conntrack
UserParameter=conntrack_syn_sent,sudo grep -c SYN_SENT /proc/net/ip_conntrack
UserParameter=conntrack_assured,sudo grep -c ASSURED /proc/net/ip_conntrack
UserParameter=conntrack_tcp_tot,sudo grep -c ^tcp /proc/net/ip_conntrack
UserParameter=conntrack_udp_tot,sudo grep -c ^udp /proc/net/ip_conntrack
 
# Remote Ping (specify host)
 
UserParameter=rping[*],ping $2 -c1 -W5|awk -F '[ /]*' '/rtt/ {print $7}' || echo
 
# Debian: packages stats - WARNING: quite heavy processes, run it infrequently
 
UserParameter=deb_pkg_removed,grep -c '^Status: deinstall ok config-files$' /var/lib/dpkg/status
UserParameter=deb_pkg_installed,grep -c '^Status: install ok installed$' /var/lib/dpkg/status
UserParameter=deb_pkg_purged,grep -c '^Status: purge ok not-installed$' /var/lib/dpkg/status
 
# Debian: last dpkg run date - useful to spot unmantained systems
 
UserParameter=deb_dpkg_lastrun,awk 'END{print $1,$2}' /var/log/dpkg.log
 
 
# iptables: bytes processed by each firewall rule. Rule number must be specified.
 
UserParameter=iptables_input_bytes[*],iptables -nv -LINPUT|awk "NR==2+$1"|echo $((`awk '{r=$2;sub(/G/,"*1048576",r);sub(/M/,"*1024",r);print r}'`))
UserParameter=iptables_forward_bytes[*],iptables -nv -LFORWARD|awk "NR==2+$1"|echo $((`awk '{r=$2;sub(/G/,"*1048576",r);sub(/M/,"*1024",r);print r}'`))
UserParameter=iptables_output_bytes[*],iptables -nv -LOUTPUT|awk "NR==2+$1"|echo $((`awk '{r=$2;sub(/G/,"*1048576",r);sub(/M/,"*1024",r);print r}'`))

raid и smartmontools debian

Стандартная команда мониторинга состояния физических дисков не выдаст ничего полезного:
smartctl --all /dev/sda

Можно использовать arcconf, но есть и другой путь:

Решение:

Linux создает для всех физических дисков, подключенных к контроллеру виртуальные устройства с именем /dev/sgX
  • /dev/sg0 - RAID 1 controller (you will not get any info or /dev/sg0).
  • /dev/sg1 - First disk in RAID 1 array.
  • /dev/sg2 - Second disk in RAID 1 array.
  • /dev/sg3 - Third disk in RAID 1 array.
     

    Тест:

    # smartctl -d sat --all /dev/sg1 -H

    Просмотр таблиц smart

    # smartctl -d sat --all /dev/sgX
    # smartctl -d sat --all /dev/sg1

    То же самое для дисков SAS

    # smartctl -d scsi --all /dev/sgX
    # smartctl -d scsi --all /dev/sg1
    # smartctl -d scsi --all /dev/sg1 -H
     

пятница, 10 августа 2012 г.

ZYXEL ADSL console mode

wan adsl chandata              ADSL channel data, line rate
wan adsl close                   Close ADSL line
wan adsl linedata near        Show ADSL near end noise margin
wan adsl linedata far           Show ADSL far end noise margin
wan adsl open                   Open ADSL line
wan adsl opencmd             Glite Open ADSL line with specific standard
wan adsl opmode               Show the operational mode
wan adsl rateadap [on|off]   Turn on/off rate adaptive mechanism
wan adsl perfdata               Show performance information,CRC, FEC, error seconds.
wan adsl reset                   Reset ADSL modem, and must reload the modem code again
wan adsl Status                 ADSL status (ex: up, down or wait for init)

понедельник, 6 августа 2012 г.

Настройка синхронизации каталогов/файлов с помощью rsync



Устанавливаем пакет rsync на исходном (192.168.234.41) и на копируемом (192.168.234.39) сервере:
atp-get install rsync

На копируемом сервере создаем конфигурационный файл /etc/rsyncd.conf

[freeradius]
comment = For backups openvpn
path = /etc/freeradius
use chroot = true
uid = root
gid = root
log file = /var/log/rsyncd.log
read only = false
write only = false
hosts allow = 192.168.234.41
hosts deny = *
transfer logging = false


Разкоментируем запуск службы в /etc/default/rsync

# defaults file for rsync daemon mode

# start rsync in daemon mode from init.d script?
#  only allowed values are "true", "false", and "inetd"
#  Use "inetd" if you want to start the rsyncd from inetd,
#  all this does is prevent the init.d script from printing a message
#  about not starting rsyncd (you still need to modify inetd's config yourself).
RSYNC_ENABLE=true

# which file should be used as the configuration file for rsync.
# This file is used instead of the default /etc/rsyncd.conf
# Warning: This option has no effect if the daemon is accessed
#          using a remote shell. When using a different file for
#          rsync you might want to symlink /etc/rsyncd.conf to
#          that file.
# RSYNC_CONFIG_FILE=

# what extra options to give rsync --daemon?
#  that excludes the --daemon; that's always done in the init.d script
#  Possibilities are:
#   --address=123.45.67.89<----><------>(bind to a specific IP address)
#   --port=8730><------><------><------>(bind to specified port; default 873)
RSYNC_OPTS=''

# run rsyncd at a nice level?
#  the rsync daemon can impact performance due to much I/O and CPU usage,
#  so you may want to run it at a nicer priority than the default priority.
#  Allowed values are 0 - 19 inclusive; 10 is a reasonable value.
RSYNC_NICE=''

# run rsyncd with ionice?
#  "ionice" does for IO load what "nice" does for CPU load.
#  As rsync is often used for backups which aren't all that time-critical,
#  reducing the rsync IO priority will benefit the rest of the system.
#  See the manpage for ionice for allowed options.
#  -c3 is recommended, this will run rsync IO at "idle" priority. Uncomment
#  the next line to activate this.
# RSYNC_IONICE='-c3'

# Don't forget to create an appropriate config file,
# else the daemon will not start.


Стартуем службу
/etc/init.d/rsync restart

На исходном сервере добавляем запуск команды в /etc/crontab

1   *   * * *   root    rsync -au /etc/freeradius/ rsync://192.168.234.39/freeradius
30  8   * * 7   root    rsync --del -au /etc/freeradius/ rsync://192.168.234.39/freeradius


ЗЫ. Ну и не забываем в iptables открыт tcp порт 873 на на копируемом сервере