KVM на Debian Stretch

Добавляем репозиторий
vim /etc/apt/sources.list:

deb http://ftp.ua.debian.org/debian/ stretch main

aptitude update
aptitude install bridge-utils kvm libvirt-bin virtinst isc-dhcp-server iptables-persistent vim

Создаём сетевой мост для виртуальных машин
vim /etc/network/interfaces:

auto br0
allow-hotplug br0
iface br0 inet static
        address 192.168.40.1
        gateway 192.168.40.1
        bridge_ports eth0
        bridge_stp off
        bridge_maxwait 0

/etc/init.d/networking stop && /etc/init.d/networking start

Настраиваем DHCP сервер
vim /etc/dhcp/dhcpd.conf:

option domain-name "example.com";
option domain-name-servers 192.168.40.1;
default-lease-time 3600;
max-lease-time 43200;
authoritative;
ddns-update-style none;
log-facility local7;
subnet 192.168.40.0 netmask 255.255.255.0 {
default-lease-time 3600;
option domain-name "example.com";
option subnet-mask 255.255.255.0;
option routers 192.168.40.1;
range 192.168.40.2 192.168.40.30;
}
vim /etc/default/isc-dhcp-server
INTERFACES="br0"
/etc/init.d/isc-dhcp-server restart Включаем пересылку пакетов vim /etc/sysctl.conf:
net.ipv4.ip_forward=1

sysctl -p

Настраиваем kvm на протокол удалённого доступа spice
Создаём самоподписные сертификаты TLS
mkdir /etc/ssl/spicetls
cd /etc/ssl/spicetls
openssl genrsa -des3 -out ca-key.pem 1024
openssl req -new -x509 -days 7300 -key ca-key.pem -out ca-cert.pem
openssl genrsa -out server-key.pem 1024
openssl req -new -key server-key.pem -out server-key.csr
openssl x509 -req -days 7300 -in server-key.csr -CA ca-cert.pem -CAkey ca-key.pem -set_serial 01 -out server-cert.pem
openssl rsa -in server-key.pem -out server-key.pem.insecure
mv server-key.pem server-key.pem.secure
mv server-key.pem.insecure server-key.pem

vim /etc/libvirt/qemu.conf:

spice_listen = "0.0.0.0"
spice_tls = 1
spice_tls_x509_cert_dir = "/etc/ssl/spicetls/"

/etc/init.d/libvirtd restart

Создаём виртуальную машину
Настраиваем пул для хранения виртуальных жёсткий дисков
pool-define-as ssd dir --target /root/kvm/
pool-start ssd
pool-autostart ssd

Запускаем установку
virt-install --name deb --ram 1024 --vcpus=6 --boot cdrom,hd,network,menu=on --cdrom=debian-testing-amd64-DVD-1.iso --disk pool=ssd,bus=ide,size=20,format=qcow2,io=native --network bridge=br0,model=e1000 --graphics spice,port=52000,listen=0.0.0.0,keymap=en-us,password=mypasswd --noautoconsole --hvm --soundhw=ac97 --video qxl --channel spicevmc

Для управления виртуальной машиной нужно установить клиент spice
Linux: spice-client-gtk (в консоли запускаем spicy), virt-manager или virt-viewer
Windows: virt-viewer (https://virt-manager.org/download/sources/virt-viewer/virt-viewer-x64-3.1.msi)

В гостевой ОС нужно установить дополнения
aptitude install spice-vdagent
На Windows http://www.spice-space.org/download/windows/spice-guest-tools/spice-guest-tools-0.100.exe

Открываем порты и включаем NAT
iptables -I INPUT 1 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -I INPUT 2 -s 192.168.40.0/24 -d 192.168.40.1 -i br0 -p tcp -m state --state NEW --dport 52000 -j ACCEPT
iptables -I INPUT 3 -s 192.168.40.0/24 -d 192.168.40.1 -i br0 -p udp --dport 67 -j ACCEPT
iptables -t nat -I POSTROUTING 1 -s 192.168.40.0/24 -o eth0 -j SNAT --to-source 192.168.40.1
/etc/init.d/netfilter-persistent save

ISPConfig на Debian Stretch

Подготавливаем программы для ispconfig
Добавляем репозитории
vim /etc/apt/sources.list:

deb http://ftp.ua.debian.org/debian/ stretch main
deb http://http.debian.net/debian/ stretch main contrib non-free

aptitude update
aptitude install mysql-server bind9 apache2 apache2.2-common apache2-doc apache2-mpm-prefork apache2-utils libexpat1 ssl-cert libapache2-mod-php5 php5 php5-common php5-gd php5-mysql php5-imap phpmyadmin php5-cli php5-cgi libapache2-mod-fcgid apache2-suexec php-pear php-auth php5-mcrypt mcrypt php5-imagick imagemagick libruby php5-curl php5-intl php5-memcache php5-memcached php5-pspell php5-recode php5-sqlite php5-tidy php5-xmlrpc php5-xsl memcached libapache2-mod-passenger libapache2-mod-fastcgi php5-fpm phpmyadmin quota quotatool roundcube roundcube-mysql vlogger webalizer fcgiwrap amavisd-new spamassassin nomarch cabextract apt-listchanges libnet-ldap-perl libauthen-sasl-perl zip unzip bzip2 sudo geoip-database libclass-dbi-mysql-perl build-essential autoconf automake libtool flex bison debhelper binutils fail2ban vim-nox iptables-persistent

Устанавливаем почтовый сервер
Устанавливаем FTP сервер pure-ftpd
Устанавливаем DNS сервер
Устанавливаем awstats

Делаем базу данных для phpmyadmin и roundcube
mysql -u root -p
create database phpmyadmin;
grant all on phpmyadmin.* to phpmyadmin@localhost identified by 'phpmyadmindbpasswd';
create database roundcube;
grant all on roundcube.* to roundcube@localhost identified by 'roundcubedbpasswd';
quit

Влючаем журналируемую квоту
vim /etc/fstab:

/dev/sda1 /    ext4  usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv0,user_xattr,acl,errors=remount-ro 0       1

shutdown -r now
quotacheck -avugm
quotaon -avug

vim /etc/php5/apache2/php.ini:

memory_limit = 256M
post_max_size = 16M
upload_max_filesize = 64M
date.timezone = Europe/Moscow

Устаналиваем ssh в chroot
cd /usr/src/
wget http://olivier.sessink.nl/jailkit/jailkit-2.17.tar.gz
cd jailkit-2.17
./debian/rules binary
dpkg -i /usr/src/jailkit_2.17-1_amd64.deb

Настраиваем защиту от взлома по IP для некоторых серверов fail2ban
vim /etc/fail2ban/jail.local

[pureftpd]
enabled  = true
port     = ftp,ftps
filter   = pureftpd
logpath  = /var/log/syslog
maxretry = 3

[dovecot-pop3imap]
enabled = true
filter = dovecot-pop3imap
action = iptables-multiport[name=dovecot-pop3imap, port="pop3,pop3s,imap,imaps", protocol=tcp]
logpath = /var/log/mail.log
maxretry = 5

[postfix-sasl]
enabled  = true
port     = smtp
filter   = postfix-sasl
logpath  = /var/log/mail.log
maxretry = 3

vim /etc/fail2ban/filter.d/pureftpd.conf:

[Definition]
failregex = .*pure-ftpd: \(.*@\) \[WARNING\] Authentication failed for user.*
ignoreregex =

vim /etc/fail2ban/filter.d/dovecot-pop3imap.conf:

[Definition]
failregex = (?: pop3-login|imap-login): .*(?:Authentication failure|Aborted login \(auth failed|Aborted login \(tried to use disabled|Disconnected \(auth failed|Aborted login \(\d+ authentication attempts).*rip=(?P\S*),.*
ignoreregex =

vim /etc/fail2ban/filter.d/postfix-sasl.conf:

ignoreregex =

/etc/init.d/fail2ban restart

Устанавливаем ispconfig
wget http://sourceforge.net/projects/ispconfig/files/ISPConfig%203/ISPConfig-3.0.5.4p8/ISPConfig-3.0.5.4p8.tar.gz
tar xzf ISPConfig-3.0.5.4p8.tar.gz
php -q ispconfig3_install/install/install.php
Installation mode (standard,expert) [standard]: expert

Устанавливаем патч
wget http://www.ispconfig.org/downloads/ispconfig_patch -P /usr/local/ispconfig/server/scripts
chmod 700 /usr/local/ispconfig/server/scripts/ispconfig_patch
ispconfig_patch

Вводим ID патча с http://www.ispconfig.org/page/en/ispconfig/patches.html, который хотите установить

Настраиваем apache
vim /etc/apache2/sites-available/ispconfig.conf:

#<Directory /usr/share/phpMyAdmin/>
#                                Require all granted
#                </Directory>

#<Directory /usr/share/squirrelmail>
#                               Require all granted
#               </Directory>

#<Directory /usr/lib/mailman/cgi-bin>
#                               Require all granted
#               </Directory>

#<Directory /usr/lib/mailman/icons>
#                               Require all granted
#               </Directory>

#<Directory /var/lib/mailman/archives/>
#        Options +FollowSymLinks
#                               Require all granted
#               </Directory>

#NameVirtualHost *:80
#NameVirtualHost *:443

vim /etc/apache2/conf-enabled/phpmyadmin.conf:

Alias /pma /usr/share/phpmyadmin

chown -R www-data:www-data /usr/share/phpmyadmin

Настраиваем roundcube
Заходим в ispconfig (https://example.com:8080 логин и пароль по умолчанию admin)->Система->Удаленные пользователи->Добавить нового пользователя
Логин: roundcube
Пароль: roundcubepasswd
Ставим галочки:

Server functions
Функции клиентов
Функции почтовых пользователей
Функции почтовых алиасов
Функции почтового спам-фильтра
Функции правил почтового спам-фильтра
Функции fetchmail
Mail spamfilter whitelist functions
Mail spamfilter blacklist functions
Функции пользовательских фильтров почты

Внизу «Сохранить»

Устанавливаем плагины для связки с ispconfig
wget https://github.com/w2c/ispconfig3_roundcube/archive/master.zip
unzip master.zip
cp -r ispconfig3_roundcube-master/{ispconfig3_account,ispconfig3_autoreply,ispconfig3_fetchmail,ispconfig3_filter,ispconfig3_forward,ispconfig3_pass,ispconfig3_spam,ispconfig3_wblist} /var/lib/roundcube/plugins/
cp /var/lib/roundcube/plugins/ispconfig3_account/config/config.inc.php.dist /var/lib/roundcube/plugins/ispconfig3_account/config/config.inc.php

vim /var/lib/roundcube/plugins/ispconfig3_account/config/config.inc.php:

$rcmail_config['remote_soap_user'] = 'логин удалённого пользователя';
$rcmail_config['remote_soap_pass'] = 'пароль удалённого пользователя';
$rcmail_config['soap_url'] = 'https://example.com:8080/remote/';

vim /etc/roundcube/debian-db.php:

$dbuser='roundcube';
$dbpass='roundcubedbpasswd';
$dbname='roundcube';

vim /etc/roundcube/main.inc.php:

$rcmail_config['default_host'] = 'mail.example.com';
$rcmail_config['smtp_server'] = 'mail.example.com';
$rcmail_config['smtp_user'] = '%u';
$rcmail_config['smtp_pass'] = '%p';
$rcmail_config['smtp_helo_host'] = 'mail.example.com';
$rcmail_config['force_https'] = true;
$rcmail_config['username_domain'] = 'example.com';
$rcmail_config['mail_domain'] = 'mail.example.com';
$rcmail_config['language'] = 'ru_RU';
$rcmail_config['plugins'] = array('jqueryui', 'ispconfig3_account', 'ispconfig3_autoreply', 'ispconfig3_pass', 'ispconfig3_spam', 'ispconfig3_fetchmail', 'ispconfig3_filter', 'ispconfig3_forward', 'ispconfig3_wblist');

vim /etc/roundcube/apache.conf:

Alias /mail /var/lib/roundcube

chown -R www-data:www-data /var/lib/roundcube/
chown -R www-data:www-data /usr/share/roundcube/
chown -R www-data:www-data /usr/share/tinymce/www/

a2enmod suexec rewrite ssl actions include dav_fs dav auth_digest cgi fastcgi alias
/etc/init.d/apache2 restart

Открываем порты
iptables -I INPUT 1 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -I INPUT 2 -s 192.168.30.0/24 -d 192.168.30.1 -i br0 -p tcp -m state --state NEW -m multiport --dports 80,443,8080,8081 -j ACCEPT
/etc/init.d/netfilter-persistent save

Ubilling на Debian Jessie

Имеем 2 сетевых интерфейса
eth1 100.1.1.1 — интернет
eth0 192.168.10.1 — локальная сеть

Добавляем репозиторий
vim /etc/apt/sources.list:

deb http://ftp.ua.debian.org/debian/ jessie main

aptitude update
aptitude install apache2 bandwidthd expat libapache2-mod-php5 mysql-server libexpat1 libmysqlclient-dev libxmlrpc-c++8 libxmlrpc-c++8-dev php5-cli php5-mysql isc-dhcp-server softflowd sudo wget build-essential openssl iptables-persistent
wget http://ftp.ua.debian.org/debian/pool/main/x/xmlrpc-c/{libxmlrpc-core-c3_1.33.14-0.2_amd64.deb,libxmlrpc-core-c3-dev_1.33.14-0.2_amd64.deb}
dpkg -i libxmlrpc-core-c3_1.33.14-0.2_amd64.deb libxmlrpc-core-c3-dev_1.33.14-0.2_amd64.deb

vim /etc/default/isc-dhcp-server:

INTERFACES="eth0"

service isc-dhcp-server start

vim /etc/bandwidthd/bandwidthd.conf:

htdocs_dir "/var/lib/bandwidthd/htdocs"

vim /etc/apache2/conf-enabled/bandwidthd.conf

Alias /bwd /var/lib/bandwidthd/htdocs/

chown -R www-data:www-data /var/lib/bandwidthd/htdocs/
service bandwidthd restart

visudo

User_Alias BILLING = www-data
BILLING ALL = NOPASSWD: ALL

Устанавливаем шейпер
wget http://sourceforge.net/projects/htbinit/files/HTB.init/0.8.5/htb.init-v0.8.5 -O /etc/init.d/htb
chmod +x /etc/init.d/htb
mkdir /etc/htb
vim /etc/init.d/htb:

#!/bin/bash
### BEGIN INIT INFO
# Provides:          htb init script
# Required-Start:    $remote_fs
# Required-Stop:     $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: start htb
# Description:       enable traffic control
### END INIT INFO
HTB_PATH=${HTB_PATH:-/etc/htb}

Добавляем htb в автозапуск
systemctl enable htb.service

vim /etc/htb/eth0:

DEFAULT=0
R2Q=100

vim /etc/htb/eth1:

DEFAULT=0
R2Q=100

vim /etc/htb/eth0-2.root:

RATE=100Mbit
CEIL=100Mbit

vim /etc/htb/eth1-2.root:

RATE=100Mbit
CEIL=100Mbit

service htb compile
service htb start

vim /etc/default/softflowd:

INTERFACE="eth0"
OPTIONS="-n 192.168.10.1:42111"

service softflowd restart

Устанавливаем stargazer
Добавляем исходник для iptables без него не скомпилируется stargazer (https://git.netfilter.org/iptables/tree/include/linux/netfilter_ipv4/ip_queue.h)
vim /usr/include/linux/netfilter_ipv4/ip_queue.h:

/*
 * This is a module which is used for queueing IPv4 packets and
 * communicating with userspace via netlink.
 *
 * (C) 2000 James Morris, this code is GPL.
 */
#ifndef _IP_QUEUE_H
#define _IP_QUEUE_H

#ifdef __KERNEL__
#ifdef DEBUG_IPQ
#define QDEBUG(x...) printk(KERN_DEBUG ## x)
#else
#define QDEBUG(x...)
#endif  /* DEBUG_IPQ */
#else
#include 
#endif	/* ! __KERNEL__ */

/* Messages sent from kernel */
typedef struct ipq_packet_msg {
	unsigned long packet_id;	/* ID of queued packet */
	unsigned long mark;		/* Netfilter mark value */
	long timestamp_sec;		/* Packet arrival time (seconds) */
	long timestamp_usec;		/* Packet arrvial time (+useconds) */
	unsigned int hook;		/* Netfilter hook we rode in on */
	char indev_name[IFNAMSIZ];	/* Name of incoming interface */
	char outdev_name[IFNAMSIZ];	/* Name of outgoing interface */
	__be16 hw_protocol;		/* Hardware protocol (network order) */
	unsigned short hw_type;		/* Hardware type */
	unsigned char hw_addrlen;	/* Hardware address length */
	unsigned char hw_addr[8];	/* Hardware address */
	size_t data_len;		/* Length of packet data */
	unsigned char payload[0];	/* Optional packet data */
} ipq_packet_msg_t;

/* Messages sent from userspace */
typedef struct ipq_mode_msg {
	unsigned char value;		/* Requested mode */
	size_t range;			/* Optional range of packet requested */
} ipq_mode_msg_t;

typedef struct ipq_verdict_msg {
	unsigned int value;		/* Verdict to hand to netfilter */
	unsigned long id;		/* Packet ID for this verdict */
	size_t data_len;		/* Length of replacement data */
	unsigned char payload[0];	/* Optional replacement packet */
} ipq_verdict_msg_t;

typedef struct ipq_peer_msg {
	union {
		ipq_verdict_msg_t verdict;
		ipq_mode_msg_t mode;
	} msg;
} ipq_peer_msg_t;

/* Packet delivery modes */
enum {
	IPQ_COPY_NONE,		/* Initial mode, packets are dropped */
	IPQ_COPY_META,		/* Copy metadata */
	IPQ_COPY_PACKET		/* Copy metadata + packet (range) */
};
#define IPQ_COPY_MAX IPQ_COPY_PACKET

/* Types of messages */
#define IPQM_BASE	0x10	/* standard netlink messages below this */
#define IPQM_MODE	(IPQM_BASE + 1)		/* Mode request from peer */
#define IPQM_VERDICT	(IPQM_BASE + 2)		/* Verdict from peer */
#define IPQM_PACKET	(IPQM_BASE + 3)		/* Packet from kernel */
#define IPQM_MAX	(IPQM_BASE + 4)

#endif /*_IP_QUEUE_H*/

cd /usr/src/
wget http://stargazer.net.ua/download/server/2.408/stg-2.408.tar.gz
tar xzf stg-2.408.tar.gz
cd stg-2.408/projects/stargazer
./build
make install
cd ../sgconf
./build
make
make install
cd ../sgconf_xml/
./build
make
make install
cd ../stargazer/plugins/configuration/rpcconfig/
make
make install

Создаем скрипт запуска для stargazer
vim /etc/init.d/stg:

#!/bin/bash
### BEGIN INIT INFO
# Provides:          startgazer init script
# Required-Start:    $remote_fs
# Required-Stop:     $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: start startgazer
# Description:       enable startgazer daemon on start system
### END INIT INFO

NAME="startgazer daemon"
BINARYNAME="stargazer"
PIDFILE="/var/run/startgazer.pid"

running() {
    if [ -n "`pgrep -f $BINARYNAME`" ]; then
        return 0
    else
        return 1
    fi
}

start() {
    if ! running; then
        echo -n "Starting the $NAME ... "
        start-stop-daemon --start --exec /usr/sbin/stargazer
        pgrep -f $BINARYNAME > $PIDFILE
        if [ -s $PIDFILE ]; then
            echo "Done"
        else
            echo "Failed"
            rm $PIDFILE
        fi
    else
        echo "The $NAME is already started."
    fi
}

stop() {
    if running; then
        echo -n "Stopping the $NAME ... "
        kill `cat $PIDFILE`
        while running; do
            sleep 1
        done
        rm $PIDFILE
        echo "Done"
    else
        echo "The $NAME is already stopped."
    fi
}

case "$1" in
    start)
        start
    ;;
    stop)
        stop
    ;;
    restart)
        stop
        start
    ;;
    status)
        if running; then
            echo "The $NAME is started."
        else
            echo "The $NAME is stopped."
        fi
    ;;
    *)
        echo "Usage: $0 (start|stop|restart|status)"
        exit 1
esac
exit 0

Добавляем в автозапуск stargazer
insserv -d stg

cp /etc/stargazer/conf-available.d/{store_mysql.conf,mod_rpc.conf,mod_cap_nf.conf,mod_remote_script.conf} /etc/stargazer/conf-enabled.d/
vim /etc/stargazer/stargazer.conf:

LogFile = /var/log/stargazer/stargazer.log
# Store module
# Configure the module that works with the database server

# Warning: Only one store module could be used at the same time!

<IncludeFile "conf-enabled.d/store_mysql.conf">
</IncludeFile>


################################################################################
# Other modules

<Modules>

    <IncludeFile "conf-enabled.d/mod_*.conf">
    </IncludeFile>

    <IncludeFile "conf-enabled.d/mod_ia.conf">
    </IncludeFile>
   <IncludeFile "conf-enabled.d/mod_sg.conf">
    </IncludeFile>

    <IncludeFile "conf-enabled.d/mod_cap_nf.conf">
    </IncludeFile>

    <IncludeFile "conf-enabled.d/mod_rpc.conf">
    </IncludeFile>

    <IncludeFile "conf-enabled.d/mod_remote_script.conf">
    </IncludeFile>

</Modules>

mkdir /var/log/stargazer

vim /etc/stargazer/conf-enabled.d/store_mysql.conf:

Database = stargazer
User = stargazer
Password = stargazerpasswd

vim /etc/stargazer/conf-enabled.d/mod_cap_nf.conf:

TCPPort = 42111
UDPPort = 42111

vim /etc/stargazer/conf-enabled.d/mod_rpc.conf:

Port = 8081
vim /etc/stargazer/conf-enabled.d/mod_remote_script.conf:
SubnetFile = /etc/stargazer/subnets

vim /etc/stargazer/subnets:

192.168.10.0/24 100.1.1.1

chmod 777 /etc/stargazer/subnets

vim /etc/stargazer/rules:

ALL     0.0.0.0/0       DIR0

Делаем базу данных для stargazer
mysql -u root -p
CREATE DATABASE stargazer;
GRANT ALL PRIVILEGES ON stargazer.* TO stargazer@localhost IDENTIFIED BY 'stargazerpasswd';
quit

Запускаем stargazer чтобы он создал свои таблицы в базе данных
/etc/init.d/stg start
Проверяем таблицы
mysql -u stargazer -p stargazer -e "SHOW TABLES"

+---------------------+
| Tables_in_stargazer |
+---------------------+
| admins              |
| messages            |
| stat                |
| tariffs             |
| users               |
+---------------------+

/etc/init.d/stg stop

Устанавливаем ubilling
mkdir /var/www/ubilling
wget http://ubilling.net.ua/ub.tgz
tar fxz ub.tgz -C /var/www/ubilling
chown -R www-data:www-data /var/www/ubilling

Создаем таблицы для ubilling
mysql -u stargazer -p stargazer < /var/www/ubilling/docs/test_dump.sql

vim /var/www/ubilling/config/mysql.ini:

username = "stargazer"
password = "stargazerpasswd"
db = "stargazer"

vim /var/www/ubilling/config/billing.ini

STG_LOGIN=admin
STG_PASSWD=adminpasswd
SUDO=/usr/bin/sudo
RC_DHCPD=/etc/init.d/isc-dhcp-server
GREP=/bin/grep
PING=/bin/ping
LANG = ru
TASKBAR_ICON_SIZE = 64
REGRANDOM_MAC=0

ln -fs /etc/dhcp/ /var/www/ubilling/multinet

vim /var/www/ubilling/config/dhcp/global.template:

option domain-name "example.com";
option domain-name-servers 192.168.10.1;

vim /var/www/ubilling/config/dhcp/subnets.template:

option domain-name "example.com";
option routers 192.168.10.1;
include "/etc/dhcp/{HOSTS}";

cp /var/www/ubilling/docs/presets/Linux/etc/* /etc/stargazer/
chmod +x /etc/stargazer/*

vim /etc/stargazer/config:

username = stargazer
password = stargazerpasswd
database = stargazer

vim /etc/stargazer/OnConnect:

IFUP="eth1"
IFDOWN="eth0"
echo "$cur_date $cur_time CONNECT: ID-$ID;LOGIN-$LOGIN;IP-$IP;CASH-$CASH;SPEED-$SPEED;UPSPEED-$UPSPEED,MAC-$MAC" >> /var/log/stargazer/allconnect.log

vim /etc/stargazer/OnDisconnect:

IFUP="eth1"
IFDOWN="eth0"
echo "$cur_date $cur_time DISCONNECT: ID-$ID;LOGIN-$LOGIN;IP-$IP;CASH-$CASH;SPEED-$SPEED;UPSPEED-$UPSPEED,MAC-$MAC" >> /var/log/stargazer/allconnect.log

vim /etc/stargazer/GetMac:

#!/usr/bin/php

vim /etc/stargazer/GetSpeed:

#!/usr/bin/php

vim /etc/stargazer/GetUpSpeed:

#!/usr/bin/php

Даем права ubilling на папку dhcp чтобы он смог сгенерировать конфигурационный файл для dhcp сервера
chown -R www-data:www-data /etc/dhcp

Включаем пересылку сетевых пакетов
vim /etc/sysctl.conf:

net.ipv4.ip_forward=1

sysctl -p
vim /etc/rc.local:

sysctl -p

vim /etc/stargazer/conf-enabled.d/mod_remote_script.conf:

SubnetFile = /var/www/ubilling/remote_nas.conf

Запускаем stargazer
/etc/init.d/stg start

Генерируем самоподписные сертификаты для SSL
cd /etc/ssl/private
openssl genrsa -des3 -out example.com.key 2048
openssl rsa -in server.key -out example.com.key
openssl req -new -days 36500 -key example.com.key -out example.com.csr
openssl x509 -in example.com.csr -out example.com.crt -req -signkey example.com.key -days 3650
chmod 400 example.com.*

Включаем поддержку SSL на нашем сайте
vim /etc/apache2/sites-available/default-ssl.conf:

SSLEngine on
SSLCertificateFile /etc/ssl/private/example.com.crt
SSLCertificateKeyFile /etc/ssl/private/example.com.key

a2ensite default-ssl

Создаем конфигурационный файл для apache
vim /etc/apache2/conf-enabled/ubilling.conf:

Alias /ubil /var/www/ubilling/
<Directory /var/www/ubilling/>
  DirectoryIndex index.php
  Require all granted
</Directory>

service apache2 reload

Включаем NAT и открываем порты
iptables -I POSTROUTING 1 -s 192.168.10.0/24 -o eth1 -j SNAT --to-source 100.1.1.1
iptables -I INPUT 1 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -I INPUT 2 -s 192.168.10.0/24 -d 192.168.10.1 -i eth0 -p tcp -m state --state NEW -m multiport --dports 80,443,5555,8081,9999,42111 -j ACCEPT
iptables -I INPUT 3 -s 192.168.10.0/24 -d 192.168.10.1 -i eth0 -p udp -m multiport --dports 67,5555,42111 -j ACCEPT
service netfilter-persistent save

Заходим в биллинг https://example.com/ubil
По умолчанию логин admin, пароль demo
Внизу в левом углу заходим в "Права администраторов" и изменяем пароль

Asterisk с веб интерфейсом FreePBX на Debian Jessie

Добавляем репозиторий
vim /etc/apt/sources.list:

deb http://ftp.ua.debian.org/debian/ jessie main

aptitude update
aptitude install asterisk asterisk-dahdi asterisk-mp3 asterisk-core-sounds-ru asterisk-moh-opsound-wav libpri1.4 apache2 mysql-server bind9 bison flex php5 php5-curl php5-cli php5-mysql php-pear php-db php5-gd curl sox libncurses5-dev libssl-dev libmysqlclient-dev mpg123 libxml2-dev libnewt-dev sqlite3 libsqlite3-dev libasound2-dev libogg-dev libvorbis-dev libcurl4-openssl-dev libical-dev libneon27-dev libsrtp0-dev libspandsp-dev libiksemel3 iptables-persistent

Исправляем конфигурационный файл asterisk для logrotate, иначе будет писать ошибку

error: skipping "/var/log/asterisk/..." because parent directory has insecure permissions

vim /etc/logrotate.d/asterisk:

/var/log/asterisk/debug /var/log/asterisk/messages /var/log/asterisk/full /var/log/asterisk/*_log {
        su asterisk asterisk
        size 40M
        missingok
        rotate 20
        compress
        sharedscripts
        create 0640 asterisk asterisk
        postrotate
                /usr/sbin/invoke-rc.d asterisk logger-reload > /dev/null 2> /dev/null
        endscript
}

Запускаем apache от пользователя asterisk
vim /etc/apache2/apache2.conf:

User asterisk
Group asterisk

vim /etc/apache2/envvars:

export APACHE_RUN_USER=asterisk
export APACHE_RUN_GROUP=asterisk

Делаем базу данных для FreePBX
mysql -u root -p
create database asterisk;
create database asteriskcdrdb;
GRANT ALL PRIVILEGES ON asterisk.* TO asterisk@localhost IDENTIFIED BY 'asteriskpasswd';
GRANT ALL PRIVILEGES ON asteriskcdrdb.* TO asterisk@localhost IDENTIFIED BY 'asteriskpasswd';
quit

wget http://mirror.freepbx.org/freepbx-12.0.43.tgz
tar xzf freepbx-12.0.43.tgz
cd freepbx
./start_asterisk restart
./install_amp --installdb --username=asterisk --password=asteriskpasswd --webroot=/var/www/freepbx/
amportal chown
amportal a ma installall
amportal a reload
amportal a ma refreshsignatures
amportal chown

Добавляем в автозапуск FreePBX
vim /etc/rc.local

amportal start

Генерируем самоподписные сертификаты для SSL
cd /etc/ssl/private
openssl genrsa -des3 -out example.com.key 2048
openssl rsa -in server.key -out example.com.key
openssl req -new -days 36500 -key example.com.key -out example.com.csr
openssl x509 -in example.com.csr -out example.com.crt -req -signkey example.com.key -days 3650
chmod 400 example.com.*

Настраиваем FreePBX на виртуальный хост
vim /etc/apache2/sites-available/freepbx.conf:

<VirtualHost *:443>
    ServerName fpbx.example.com
    ServerAdmin admin@example.com
    ErrorLog /var/log/apache2/freepbx-error.log
    CustomLog /var/log/apache2/freepbx-access.log combined
    DocumentRoot /var/www/freepbx
    <Directory /var/www/freepbx>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
    <Directory /var/www/freepbx/admin>
        Require all granted
    </Directory>
    SSLEngine on
    SSLCertificateFile /etc/ssl/private/example.com.crt
    SSLCertificateKeyFile /etc/ssl/private/example.com.key
</VirtualHost>

a2ensite freepbx
invoke-rc.d apache2 restart

Включаем русский язык в FreePBX
vim /usr/share/locale/locale.alias:

#russian         ru_RU.KOI8-R
russian ru
ru ru_RU
ru_RU ru_RU.UTF-8

locale-gen ru_RU.UTF-8

Настраиваем DNS сервер в chroot режиме
vim /etc/default/bind9:

OPTIONS="-u bind -t /var/bind9/chroot -4"

mkdir -p /var/bind9/chroot/{etc,dev,var/cache/bind,var/run/named}
mknod /var/bind9/chroot/dev/null c 1 3
mknod /var/bind9/chroot/dev/random c 1 8
chmod 660 /var/bind9/chroot/dev/{null,random}
mv /etc/bind /var/bind9/chroot/etc
ln -s /var/bind9/chroot/etc/bind /etc/bind
chown -R bind:bind /etc/bind/*
chmod 775 /var/bind9/chroot/var/{cache/bind,run/named}
chgrp bind /var/bind9/chroot/var/{cache/bind,run/named}

vim /etc/init.d/bind9:

PIDFILE=/var/bind9/chroot/var/run/named/named.pid

vim /var/bind9/chroot/etc/bind/named.conf.options:

options {
        directory "/var/cache/bind";
        dnssec-validation auto;
        auth-nxdomain no;
        listen-on-v6 { none; };
        listen-on { 127.0.0.1; 192.168.40.1; };
        allow-query { any; };
        recursion yes;
        allow-recursion { 127.0.0.1;192.168.40.0/24; };
        version "my dns server";
};

vim /etc/rsyslog.d/bind-chroot.conf:

$AddUnixListenSocket /var/bind9/chroot/dev/log

invoke-rc.d rsyslog restart

vim /var/bind9/chroot/etc/bind/named.conf.local:

zone "example.com" IN {
        type master;
        file "/etc/bind/example.com";
        allow-update { none; };
};
include "/etc/bind/zones.rfc1918";

vim /var/bind9/chroot/etc/bind/example.com:

$TTL 3600       ; 1 hour
@               IN      SOA     ns.example.com.      admin.example.com. (
                                2013090608 ; serial
                                3600       ; refresh (1 hour)
                                900        ; retry (15 minutes)
                                360000     ; expire (4 days 4 hours)
                                3600       ; minimum (1 hour)
)
                IN                      NS      ns.example.com.
                IN                      A       192.168.40.1
ns                   IN      A       192.168.40.1
example.com.         IN      A       192.168.40.1
fbpx                 IN      A       192.168.40.1

invoke-rc.d bind9 restart

Переключаемся на свой DNS сервер
vim /etc/resolv.conf:

nameserver 127.0.0.1

FreePBX будет доступен на https://fpbx.example.com

Уменьшаем ограничение на объем своих музыкальных файлов для asterisk
vim /etc/php5/apache2/php.ini:

upload_max_filesize = 40M

Убираем с автозапуска asterisk, так как его запускает FreePBX
insserv -r asterisk

Открываем порты
iptables -I INPUT 1 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -I INPUT 2 -s 192.168.40.0/24 -d 192.168.40.1 -i eth0 -p tcp -m state --state NEW -m multiport --dports 443,2000,5038 -j ACCEPT
iptables -I INPUT 3 -s 192.168.40.0/24 -d 192.168.40.1 -i eth0 -p udp -m multiport --dports 53,2727,4520,4569,5000,5036,5060,10000:20000 -j ACCEPT
invoke-rc.d netfilter-persistent save

Webvirtmgr на Debian Jessie. Веб интерфейс для Linux KVM

Добавляем репозиторий
vim /etc/apt/sources.list:

deb http://ftp.ua.debian.org/debian/ jessie main

aptitude update
aptitude install git python-pip python-libvirt python-libxml2 novnc supervisor qemu-kvm libvirt-bin virtinst sasl2-bin apache2 libapache2-mod-wsgi bridge-utils iptables-persistent

Настраиваем KVM
vim /etc/default/libvirtd:

libvirtd_opts="-d -l"

vim /etc/libvirt/libvirtd.conf:

listen_tls = 0
listen_tcp = 1

invoke-rc.d libvirtd restart

Делаем сетевой мост для KVM
vim /etc/network/interfaces:

auto br0
allow-hotplug br0
iface br0 inet static
        address 192.168.10.1
        gateway 192.168.10.1
        bridge_ports eth0
        bridge_stp off
        bridge_maxwait 0

invoke-rc.d networking stop && invoke-rc.d networking start

Настраиваем webvirtmgr
cd /var/www
git clone git://github.com/retspen/webvirtmgr.git
cd webvirtmgr
pip install -r requirements.txt
./manage.py syncdb
./manage.py collectstatic
vim conf/gunicorn.conf.py:

bind = '0.0.0.0:8000'

chown -R www-data:www-data /var/www/webvirtmgr

Добавляем пользователя, который получит доступ к веб интерфейсу
/var/www/webvirtmgr/manage.py createsuperuser
Потом для того же пользователя
saslpasswd2 -a libvirt user
Статус пользователей
sasldblistusers2 -f /etc/libvirt/passwd.db

vim /etc/supervisor/conf.d/webvirtmgr.conf:

[program:webvirtmgr]
command=/usr/bin/python /var/www/webvirtmgr/manage.py run_gunicorn -c /var/www/webvirtmgr/conf/gunicorn.conf.py
directory=/var/www/webvirtmgr
autostart=true
autorestart=true
stdout_logfile=/var/log/supervisor/webvirtmgr.log
redirect_stderr=true
user=www-data

[program:webvirtmgr-console]
command=/usr/bin/python /var/www/webvirtmgr/console/webvirtmgr-console
directory=/var/www/webvirtmgr
autostart=true
autorestart=true
stdout_logfile=/var/log/supervisor/webvirtmgr-console.log
redirect_stderr=true
user=www-data

invoke-rc.d supervisor restart
invoke-rc.d supervisor restart

invoke-rc.d novnc stop
insserv -r novnc
vim /etc/insserv/overrides/novnc:

#!/bin/sh
### BEGIN INIT INFO
# Provides:          nova-novncproxy
# Required-Start:    $network $local_fs $remote_fs $syslog
# Required-Stop:     $remote_fs
# Default-Start:
# Default-Stop:
# Short-Description: Nova NoVNC proxy
# Description:       Nova NoVNC proxy
### END INIT INFO

Делаем виртуальный хост для webvirtmgr
vim /etc/apache2/sites-available/webvirtmgr.conf:

WSGISocketPrefix /var/run/apache2/wsgi
<VirtualHost *:8000>
    ServerAdmin admin@example.com
    ServerName example.com

    WSGIDaemonProcess webvirtmgr display-name=%{GROUP} python-path=/var/www/webvirtmgr
    WSGIProcessGroup webvirtmgr
    WSGIScriptAlias / /var/www/webvirtmgr/webvirtmgr/wsgi.py

    Alias /static /var/www/webvirtmgr/webvirtmgr/static/
    Alias /media /var/www/webvirtmgr/webvirtmgr/media/

    <Directory /var/www/webvirtmgr/webvirtmgr>
        <Files wsgi.py>
        Require all granted
        </Files>
    </Directory>

    CustomLog ${APACHE_LOG_DIR}/webvirtmgr-access.log common
    ErrorLog ${APACHE_LOG_DIR}/webvirtmgr-error.log
</VirtualHost>

a2ensite webvirtmgr
invoke-rc.d apache2 reload

Открываем порты
iptables -I INPUT 1 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -I INPUT 2 -s 192.168.10.0/24 -d 192.168.10.1 -i eth0 -p tcp -m state --state NEW -m multiport --dports 80,6080,8000,16509 -j ACCEPT
invoke-rc.d netfilter-persistent save

Веб интерфейс будет доступен по адресу http://example.com:8000

TFTP сервер

Открылся бесплатный TFTP сервер
адрес tehnikpc.net
место 1 ГБ

PXE boot сервер на Debian Jessie

Добавляем репозиторий
vim /etc/apt/sources.list:

deb http://ftp.ua.debian.org/debian/ jessie main

aptitude update
aptitude install isc-dhcp-server tftpd-hpa apache2 samba iptables-persistent

Создаём пользователя, под которым будет работать tftp сервер
useradd -d /tftp -s /bin/false -c "tftp-user" -m tftp

Настраиваем tftp сервер
vim /etc/default/tftpd-hpa:

TFTP_USERNAME="tftp"
TFTP_DIRECTORY="/tftp"
TFTP_ADDRESS="0.0.0.0:69"
TFTP_OPTIONS="--ipv4 --secure --create --umask 002 --permissive"

invoke-rc.d tftpd-hpa restart

Подготавливаем файлы для загрузки по сети
wget https://www.kernel.org/pub/linux/utils/boot/syslinux/syslinux-6.03.zip
unzip syslinux-6.03.zip -d syslinux
cp syslinux/bios/core/pxelinux.0 /tftp
cp syslinux/bios/memdisk/memdisk /tftp
cp syslinux/bios/com32/chain/chain.c32 /tftp
cp syslinux/bios/com32/menu/menu.c32 /tftp
cp syslinux/bios/com32/mboot/mboot.c32 /tftp
cp syslinux/bios/com32/elflink/ldlinux/ldlinux.c32 /tftp
cp syslinux/bios/com32/libutil/libutil.c32 /tftp
mkdir -p /tftp/{pxelinux.cfg,images}
mkdir /tftp/images/{centos,debian,opensuse,win7,acronis}

mount -o loop CentOS-7.0-1406-x86_64-DVD.iso /mnt
cp -Rr /mnt/* /tftp/images/centos
umount /mnt

mount -o loop debian-testing-amd64-DVD-1.iso /mnt
cp -Rr /mnt/* /tftp/images/debian
umount /mnt
wget http://ftp.ua.debian.org/debian/dists/jessie/main/installer-amd64/current/images/netboot/debian-installer/amd64/{linux,initrd.gz} -P /tftp/images/debian/isolinux

mount -o loop openSUSE-13.2-DVD-x86_64.iso /mnt
cp -Rr /mnt/* /tftp/images/opensuse
umount /mnt
wget http://download.opensuse.org/distribution/13.2/repo/oss/boot/x86_64/loader/{linux,initrd} -P /tftp/images/opensuse

mount -o loop windows7x64.iso /mnt
cp -r /mnt/* /tftp/images/win7
umount /mnt

Создаём файл ответов для Debian
vim /tftp/images/debian/isolinux/preseed.cfg:

d-i debian-installer/language string ru
d-i debian-installer/country string RU
d-i debian-installer/locale string ru_RU.UTF-8
d-i netcfg/choose_interface select auto
d-i clock-setup/utc boolean false
d-i time/zone string Europe/Moscow
tasksel tasksel/first multiselect standard, desktop
tasksel tasksel/desktop select xfce
d-i pkgsel/upgrade select full-upgrade
popularity-contest popularity-contest/participate boolean false
d-i cdrom-detect/eject boolean false

Генерируем загрузочный образ PXE для Windows 7
Загружаем пакет автоматической установки Windows http://download.microsoft.com/download/9/1/5/9153E40C-13C0-4A12-AB5A-7EB950ED9D6A/KB3AIK_RU.iso и устанавливаем на Windows 7
На Windows 7 запускаем командную строку средств развертывания от администратора и вводим команды:
mkdir c:\winpe
rd c:\winpe
copype.cmd amd64 c:\winpe
imagex /mountrw winpe.wim 1 mount

Редактируем скрипт запуска PXE C:\winpe\mount\Windows\System32\startnet.cmd:

wpeinit
net use z: \\192.168.0.1\pxe
z:\setup.exe

Если у вас стоит пароль к samba

wpeinit
net use z: \\192.168.0.1\pxe вашпароль /user:вашпользователь
z:\setup.exe

В той же командной строке ещё вводим:

imagex /unmoumt mount /commit
copy "c:\Program Files\Windows AIK\Tools\amd64\imagex.exe" c:\winpe\ISO
copy c:\winpe\winpe.wim c:\winpe\ISO\sources\boot.wim
oscdimg -n -bc:\winpe\Etfsboot.com c:\winpe\ISO c:\winpe\win7pex64.iso

Копируем сгенерированный образ c:\winpe\win7pex64.iso в папку для образов /tftp/images/ на tftp сервер

Загружаем какую-нибудь сборку Acronis например
wget http://tehnikpc.net/ftp/rescuecd/acronis/Acronis.2k10.UltraPack.v.3.0.5.iso -P /tftp/images/

Создаём меню загрузки PXE
vim /tftp/pxelinux.cfg/default:

default menu.c32
menu title pxe boot menu
prompt 0
timeout 1200
label Boot from local drive
        localboot
menu begin
menu title os install
label ..
menu exit
label   centos
        kernel images/centos/isolinux/vmlinuz
        append initrd=images/centos/isolinux/initrd.img method=http://192.168.0.1/pxe/centos/ devfs=nomount
label   debian
        kernel images/debian/isolinux/linux
        append priority=critical vga=normal initrd=images/debian/isolinux/initrd.gz ramdisk_size=32768 method=http:/192.168.0.1/pxe/debian/ preseed/url=http://192.168.0.1/pxe/debian/isolinux/preseed.cfg
label   opensuse
        kernel images/opensuse/linux
        append initrd=images/opensuse/initrd ramdisk_size=65536 splash=verbose showopts instmode=http netconfig=dhcp netdevice=eth0 install=http://192.168.0.1/pxe/opensuse/
label windows 7
        kernel memdisk
        append iso initrd=images/win7pex64.iso
menu end
menu begin
menu title utilities
label ..
menu exit
label   acronis
        kernel memdisk
        append iso initrd=images/Acronis.2k10.UltraPack.v.3.0.5.iso
menu end

Открываем доступ к файлам дистрибутивов Linux по HTTP
vim /etc/apache2/conf-enabled/pxe.conf:

Alias /pxe /tftp/images/
<Directory /tftp/images/>
        Options Indexes FollowSymLinks
        Require ip 192.168.0.0/24
</Directory>

invoke-rc.d apache2 reload

Открываем доступ к файлам Windows по SMB
vim /etc/samba/smb.conf:

[pxe$]
        path = /tftp/images/win7
        comment = windows 7 pxe install folder
        read only = yes
        guest ok = yes
        hosts allow = 192.168.0.0/24

invoke-rc.d samba restart

Настраиваем DHCP сервер
vim /etc/dhcp/dhcpd.conf:

authoritative;
option option-128 code 128 = string;
option option-129 code 129 = text;
allow booting;
allow bootp;
option domain-name "tehnikpc.net";
option domain-name-servers 192.168.0.1;
default-lease-time 720000;
max-lease-time 720000;
min-lease-time 720000;
log-facility local6;
subnet 192.168.0.0 netmask 255.255.255.0 {
        option routers 192.168.0.1;
        option subnet-mask 255.255.255.0;
        option broadcast-address 192.168.0.255;
        range dynamic-bootp 192.168.0.2 192.168.0.50;
        next-server 192.168.0.1;
        filename "pxelinux.0";
}

Открываем порты
iptables -I INPUT 1 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -I INPUT 2 -s 192.168.0.0/24 -d 192.168.0.1 -i eth0 -p tcp -m state --state NEW -m multiport --dports 80,445 -j ACCEPT
iptables -I INPUT 3 -s 192.168.0.0/24 -d 192.168.0.1 -i eth0 -p udp -m multiport --dports 67,69 -j ACCEPT
invoke-rc.d netfilter-persistent save

OpenVPN на Debian Jessie

Добавляем репозиторий
vim /etc/apt/sources.list:

deb http://ftp.ua.debian.org/debian/ jessie main

aptitude update
aptitude install openvpn bridge-utils iptables-persistent

Имеем 2 сетевых интерфейса:
eth0 — локальная сеть 192.168.20.1
eth1 — интернет 100.60.1.100
Настраиваем их
vim /etc/network/interfaces:

auto eth1
allow-hotplug eth1
iface eth1 inet static
        address 100.60.1.100
        netmask 255.255.255.0
        gateway 100.60.1.1

auto br0
allow-hotplug br0
iface br0 inet static
        address 192.168.20.1
        gateway 192.168.20.1
        bridge_ports eth0 tap0
        bridge_stp off
        bridge_maxwait 0
        pre-up openvpn --mktun --dev tap0
        post-down openvpn --rmtun --dev tap0

invoke-rc.d networking stop && invoke-rc.d networking start

Генерируем ключи
mkdir /etc/openvpn/easy-rsa
cp /usr/share/easy-rsa/* /etc/openvpn/easy-rsa
cd /etc/openvpn/easy-rsa
vim vars:

export KEY_COUNTRY="UA"
export KEY_PROVINCE="UA"
export KEY_CITY="Kiev"
export KEY_ORG="mycompany"
export KEY_EMAIL="admin@example.com"

source ./vars
./clean-all
./build-ca

Ключ для сервера
./build-key-server example.com

Ключи для клиентов. Для каждого клиента пишем разное значение "Common Name"
./build-key myuser1

Следующий клиент
./build-key myuser2

Ключ Диффи-Хеллман
./build-dh
Ключ для TLS
openvpn --genkey --secret keys/ta.key

Клиентам отдаём ключи
myuser1.crt
myuser1.key
ca.crt
ta.key

Настраиваем сервер
zcat /usr/share/doc/openvpn/examples/sample-config-files/server.conf.gz > /etc/openvpn/server.conf
vim /etc/openvpn/server.conf:

port 1194
proto udp
dev tap0
ca /etc/openvpn/easy-rsa/keys/ca.crt
cert /etc/openvpn/easy-rsa/keys/example.com.crt
key /etc/openvpn/easy-rsa/keys/example.com.key
tls-auth /etc/openvpn/easy-rsa/keys/ta.key 0
cipher DES-EDE3-CBC
dh /etc/openvpn/easy-rsa/keys/dh2048.pem
ifconfig-pool-persist ipp.txt
server-bridge 192.168.20.1 255.255.255.0 192.168.20.2 192.168.20.100
push "redirect-gateway def1 bypass-dhcp"
push "dhcp-option DNS 192.168.20.1"
client-to-client
keepalive 10 120
comp-lzo
max-clients 99
persist-key
persist-tun
status openvpn-status.log
log /var/log/openvpn.log
verb 3

invoke-rc.d openvpn start

Включаем пересылку пакетов в ядре:
vim /etc/sysctl.conf:

net.ipv4.ip_forward=1

sysctl -p
vim /etc/rc.local:

sysctl -p

Открываем порт для openvpn и включаем NAT для openvpn
iptables -I INPUT 1 -s 192.168.20.0/24 -d 192.168.20.1 -i eth0 -p udp --dport 1194 -j ACCEPT
iptables -I INPUT 2 -d 100.60.1.100 -i eth1 -p udp --dport 1194 -j ACCEPT
iptables -t nat -I POSTROUTING 1 -s 192.168.20.0/24 -o eth1 -j SNAT --to-source 100.60.1.100
invoke-rc.d netfilter-persistent save

Настраиваем клиента на Debian
aptitude update
aptitude install openvpn iptables-persistent

Копируем ключи myuser1.crt, myuser1.key, ca.crt и ta.key в /etc/openvpn/
cp /usr/share/doc/openvpn/examples/sample-config-files/client.conf /etc/openvpn
vim /etc/openvpn/client.conf:

client
dev tap0
proto udp
remote example.com 1194
resolv-retry infinite
nobind
persist-key
persist-tun
ca ca.crt
cert myuser1.crt
key myuser1.key
tls-auth ta.key 1
cipher DES-EDE3-CBC
ns-cert-type server
comp-lzo
verb 3
log /var/log/openvpn.log

Открываем порт для openvpn клиента
iptables -I OUTPUT 1 -s вашip -d 100.60.1.100 -o eth0 -p udp --dport 1194 -j ACCEPT
invoke-rc.d netfilter-persistent save

invoke-rc.d openvpn start

Настраиваем клиента на Windows 7
Устанавливаем клиент
Копируем ключи myuser2.crt, myuser2.key, ca.crt и ta.key в C:\Program Files\OpenVPN\config\
Создаём конфигурационный файл C:\Program Files\OpenVPN\config\client.ovpn

remote example.com 1194
client
dev tap0
proto udp
resolv-retry infinite
nobind
persist-key
persist-tun
ca ca.crt
cert myuser2.crt
key myuser2.key
tls-auth ta.key 1
cipher DES-EDE3-CBC
comp-lzo
ns-cert-type server
verb 3

Открываем порт для openvpn клиента
netsh advfirewall firewall add rule name=openvpn dir=out action=allow protocol=udp localport=1194 interface=lan localip=вашip remoteip=100.60.1.100

Запускаем OpenVPN GUI с рабочего стола от имени Администратора
В трее появится серый значок монитор с замком
Правой кнопкой по нему "Подключиться"
Должно появиться сообщение "myuser2 сейчас подключено."
Значок в трее должен стать зелёным.

Открытие игровых серверов.

Arma 2 Combined Operations
tehnikpc.net:2330 — Takistan
tehnikpc.net:2340 — Chernarus

Arma 3
tehnikpc.net:2302

Counter-Strike: Global Offensive
tehnikpc.net:27015

Garry’s Mod
tehnikpc.net:27065

Just Cause 2
tehnikpc.net:7777

Minecraft 1.7.4
tehnikpc.net:25565

Team Fortress 2
tehnikpc.net:27040