Несколько TeamSpeak серверов на Debian Buster

Создаём группу и пользователя для TeamSpeak

groupadd ts3
useradd -g ts3 -d /srv/srv3 -s /bin/bash -m ts3
passwd ts3

Установку делаем под пользователем TeamSpeak

su ts3
cd /srv/ts3/
wget http://dl.4players.de/ts/releases/3.0.13.8/teamspeak3-server_linux_amd64-3.0.13.8.tar.bz2
tar xjf teamspeak3-server_linux_amd64-3.0.13.8.tar.bz2
cp -r teamspeak3-server_linux_amd64/* .

Создаём файл настройки

./ts3server createinifile=1

В папке появится файл ts3server.ini

Меняем стандартные порты

vim ts3server.ini:

default_voice_port=9988
filetransfer_port=30034
query_port=10012

Переименовываем сервер чтобы не пересекался с основным

mv ts3server ts3server2


vim ts3server_startscript.sh:

COMMANDLINE_PARAMETERS="inifile=ts3server.ini"
BINARYNAME="ts3server2"


vim ts3server_minimal_runscript.sh:

./ts3server2 $@


./ts3server_minimal_runscript.sh inifile=ts3server.ini

Записываем куда-нибудь логин, пароль и токен
Нажимаем ctrl + c

Настраиваем системный скрипт для запуска сервера
vim /etc/init.d/ts3server:

#! /bin/sh
### BEGIN INIT INFO
# Provides:          teamspeak
# Required-Start:    networking
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      S 0 1 6
# Short-Description: TeamSpeak Server Daemon
# Description:       Starts/Stops/Restarts the TeamSpeak Server Daemon
### END INIT INFO

set -e

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DESC="Team Speak Server"
NAME=ts3server
USER=ts3
DIR=/srv/ts3/
DAEMON=$DIR/ts3server_startscript.sh
SCRIPTNAME=/etc/init.d/$NAME

test -x $DAEMON || exit 0

cd $DIR
sudo -u ts3 ./ts3server_startscript.sh $1


chmod u+x /etc/init.d/ts3server

Добавляем в автозагрузку

systemctl enable ts3server


/etc/init.d/ts3server start

Устанавливаем службу для фаерволла

aptitude update
aptitude install iptables-persistent

Открываем порты

iptables -I INPUT 1 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -I INPUT 2 -d 100.1.1.1 -i eth0 -p udp --dport 9988 -j ACCEPT
iptables -I INPUT 3 -d 100.1.1.1 -i eth0 -p tcp -m state --state NEW -m multiport --dports 10012,30034 -j ACCEPT

Сохраняем правила

/etc/init.d/netfilter-persistent save

Подключаемся к серверу TeamSpeak с логином и паролем, выданными ранее при запуске ts3server_minimal_runscript.sh
Вводим ключ привилегий (токен)
В клиенте TeamSpeak заходим Инструменты -> Идентификаторы
Правой кнопкой «По умолчанию» -> Экспортировать
Резервируем файл привилегий администратора сервера в надёжное место

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
Внизу в левом углу заходим в "Права администраторов" и изменяем пароль