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