pure-ftpd на Debian Jessie

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

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


aptitude update
aptitude install pure-ftpd-mysql openssl iptables-persistent

Создаём группу и пользователя для pure-ftpd
groupadd -g 1001 ftp
useradd -u 1001 -g ftp -s /bin/false -d /ftp -c "ftp-users" ftp

Настраиваем pure-ftpd
echo "no" > /etc/pure-ftpd/conf/NoAnonymous
echo "yes" > /etc/pure-ftpd/conf/ChrootEveryone
echo "yes" > /etc/pure-ftpd/conf/IPV4Only
echo "yes" > /etc/pure-ftpd/conf/UnixAuthentication
echo "yes" > /etc/pure-ftpd/conf/DontResolve
echo "yes" > /etc/pure-ftpd/conf/CreateHomeDir
echo "no" > /etc/pure-ftpd/conf/PAMAuthentication
echo "yes" > /etc/pure-ftpd/conf/VerboseLog
echo "30" > /etc/pure-ftpd/conf/MaxClientsNumber
echo "8" > /etc/pure-ftpd/conf/MaxClientsPerIP
echo "no" > /etc/pure-ftpd/conf/DisplayDotFiles
echo "30" > /etc/pure-ftpd/conf/MaxIdleTime
echo "49152 65535" > /etc/pure-ftpd/conf/PassivePortRange
echo "2048" > /etc/pure-ftpd/conf/AnonymousBandwidth
echo "1000 500" > /etc/pure-ftpd/conf/Quota
echo "90" > /etc/pure-ftpd/conf/MaxDiskUsage
echo "1" > /etc/pure-ftpd/conf/TLS

Генерируем самоподписные сертификаты для pure-ftpd
cd /etc/ssl/private
openssl req -x509 -nodes -newkey rsa:1024 -keyout pure-ftpd.pem -out pure-ftpd.pem
chmod 400 pure-ftpd.pem

Создаем базу данных для pure-ftpd
mysql -u root -p
CREATE DATABASE pureftpd;
GRANT ALL PRIVILEGES ON pureftpd.* TO 'pureftpd'@'localhost' IDENTIFIED BY 'pureftpddbpass';

USE pureftpd;

CREATE TABLE admin (
Username varchar(35) NOT NULL default '',
Password char(32) binary NOT NULL default '',
PRIMARY KEY (Username)
) ENGINE=MyISAM;

INSERT INTO admin VALUES ('admin',MD5('adminpasswd'));

CREATE TABLE `users` (
`User` varchar(16) NOT NULL default '',
`Password` varchar(32) binary NOT NULL default '',
`Uid` int(11) NOT NULL default '14',
`Gid` int(11) NOT NULL default '5',
`Dir` varchar(128) NOT NULL default '',
`QuotaFiles` int(10) NOT NULL default '500',
`QuotaSize` int(10) NOT NULL default '30',
`ULBandwidth` int(10) NOT NULL default '80',
`DLBandwidth` int(10) NOT NULL default '80',
`Ipaddress` varchar(15) NOT NULL default '*',
`Comment` tinytext,
`Status` enum('0','1') NOT NULL default '1',
`ULRatio` smallint(5) NOT NULL default '1',
`DLRatio` smallint(5) NOT NULL default '1',
PRIMARY KEY (`User`),
UNIQUE KEY `User` (`User`)
) ENGINE=MyISAM;
quit

vim /etc/pure-ftpd/db/mysql.conf:

MYSQLUser       pureftpd
MYSQLPassword   pureftpddbpass
MYSQLDatabase   pureftpd
MYSQLCrypt      md5
MYSQLGetPW      SELECT Password FROM users WHERE User="\L" AND status="1" AND (Ipaddress = "*" OR Ipaddress LIKE "\R")
MYSQLGetUID     SELECT Uid FROM users WHERE User="\L" AND status="1" AND (Ipaddress = "*" OR Ipaddress LIKE "\R")
MYSQLGetGID     SELECT Gid FROM users WHERE User="\L"AND status="1" AND (Ipaddress = "*" OR Ipaddress LIKE "\R")
MYSQLGetDir     SELECT Dir FROM users WHERE User="\L"AND status="1" AND (Ipaddress = "*" OR Ipaddress LIKE "\R")
MySQLGetBandwidthUL SELECT ULBandwidth FROM users WHERE User="\L"AND status="1" AND (Ipaddress = "*" OR Ipaddress LIKE "\R")
MySQLGetBandwidthDL SELECT DLBandwidth FROM users WHERE User="\L"AND status="1" AND (Ipaddress = "*" OR Ipaddress LIKE "\R")
MySQLGetQTASZ   SELECT QuotaSize FROM users WHERE User="\L"AND status="1" AND (Ipaddress = "*" OR Ipaddress LIKE "\R")
MySQLGetQTAFS   SELECT QuotaFiles FROM users WHERE User="\L"AND status="1" AND (Ipaddress = "*" OR Ipaddress LIKE "\R")

invoke-rc.d pure-ftpd-mysql restart

Устанавливаем user manager для pure-ftpd
wget http://machiel.generaal.net/files/pureftpd/ftp_v2.1.tar.gz
tar xzf ftp_v2.1.tar.gz -C /var/www
wget http://machiel.generaal.net/files/pureftpd/languages/2.x/russian.php.txt -O /var/www/ftp/language/russian.php
chown -R www-data:www-data /var/www/ftp

vim /var/www/ftp/config.php:

  $LANG = "Russian";
  $LocationImages =  "images";
  $DBHost = "127.0.0.1";
  $DBLogin = "pureftpd";
  $DBPassword = "pureftpddbpass";
  $DBDatabase = "pureftpd";
  $FTPAddress = "example.com:21";
  $DEFUserID = "1001";
  $DEFGroupID = "1001";
  $UsersFile = "/etc/passwd";
  $GroupFile = "/etc/group";
  $StyleSheet = "style/default.css.php";
  $EnableQuota = 1;
  $EnableRatio = 1;

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

short_open_tag = On

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

Alias /ftpmgr /var/www/ftp/
<Directory /var/www/ftp/>
  DirectoryIndex index.php
  Require all granted
</Directory>

invoke-rc.d apache2 restart

Управление пользователями будет доступно на http://example.com/ftpmgr

Открываем порты
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 21,990,49152:65535 -j ACCEPT
invoke-rc.d netfilter-persistent save

Присоединение Debian Jessie к Active Directory Domain Controller

Имеем контроллер домена example.com с IP адресом 192.168.40.1

Устанавливаем необходимые пакеты (https://wiki.debian.org/AuthenticatingLinuxWithActiveDirectory)
Добавляем репозиторий
vim /etc/apt/sources.list:

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


aptitude update
aptitude -y install winbind samba krb5-user libpam-krb5 libpam-winbind libnss-winbind ntp iptables-persistent

Настраиваем сетевой интерфейс
vim /etc/network/interfaces:

auto eth0
allow-hotplug eth0
iface eth0 inet static
        address 192.168.40.2
        gateway 192.168.40.1

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

vim /etc/resolv.conf:

domain example.com
search example.com
nameserver 192.168.40.1

Настраиваем синхронизацию времени с сервером Active Directory
vim /etc/ntp.conf:

server example.com

invoke-rc.d ntp restart

Настраиваем Kerberos
vim /etc/krb5.conf:

[libdefaults]
        default_realm = EXAMPLE.COM
        dns_lookup_realm = false
        dns_lookup_kdc = false
        ticket_lifetime = 24h
        renew_lifetime = 7d
        forwardable = true
[realms]
 EXAMPLE.COM = {
  kdc = example.com
  admin_server = example.com
 }
[domain_realm]
 .example.com = EXAMPLE.COM
 example.com = EXAMPLE.COM

vim /etc/samba/smb.conf:

[global]
        security = ads
        realm = EXAMPLE.COM
        password server = 192.168.40.1
        workgroup = MYADDC
        idmap config * : range = 10000-20000
        idmap config * : backend = tdb
        winbind enum users = yes
        winbind enum groups = yes
        template homedir = /home/%D/%U
        template shell = /bin/bash
        client use spnego = yes
        client ntlmv2 auth = yes
        encrypt passwords = yes
        winbind use default domain = yes
        restrict anonymous = 2
        domain master = no
        local master = no
        preferred master = no
        os level = 0

realm — полное имя контроллера домена
workgroup — короткое имя контроллера домена

invoke-rc.d winbind stop
invoke-rc.d samba restart
invoke-rc.d winbind start

vim /etc/nsswitch.conf:

passwd:         compat winbind
group:          compat winbind

vim /etc/pam.d/common-account:

account sufficient      pam_winbind.so
account required        pam_unix.so

vim /etc/pam.d/common-auth:

auth    sufficient      pam_unix.so
auth    required        pam_winbind.so  use_first_pass

vim /etc/pam.d/common-password:

password   required   pam_unix.so nullok obscure min=4 max=50 md5

vim /etc/pam.d/common-session:

session     required    pam_mkhomedir.so umask=0022 skel=/etc/skel

Открываем порты
iptables -I OUTPUT 1 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -I OUTPUT 2 -s 192.168.40.2 -d 192.168.40.1 -o eth0 -p tcp -m state --state NEW -m multiport --dports 53,88,135,139,389,445,464,636,1024:5000,3268,3269,5353 -j ACCEPT
iptables -I OUTPUT 3 -s 192.168.40.2 -d 192.168.40.1 -o eth0 -p udp -m multiport --dports 88,137,138,389,464,5353 -j ACCEPT
/etc/init.d/netfilter-persistent save

Присоединяемся к Active Directory Domain Controller
net ads join -U Administrator
shutdown -r now

Если установлен gdm, нажимаем «Нет в списке» и вводим
Короткое имя контроллера домена\имя пользователя в домене
Например:
myaddc\user

Active Directory Domain Controller на Debian Stretch совместимый с Microsoft

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

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

aptitude update
aptitude install bind9 ntp build-essential libacl1-dev libattr1-dev libblkid-dev libgnutls-dev libreadline-dev python-dev python-dnspython gdb pkg-config libpopt-dev libldap2-dev dnsutils libbsd-dev attr krb5-user docbook-xsl libcups2-dev acl samba vim winbind iptables-persistent
systemctl disable nmbd
systemctl disable smbd
systemctl disable winbind
systemctl unmask samba-ad-dc
systemctl enable samba-ad-dc
dpkg --configure -a

Настраиваем сетевой интерфейс
vim /etc/network/interfaces:

auto eth0
allow-hotplug eth0
iface eth0 inet static
        address 192.168.40.2
        gateway 192.168.40.1

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

Редактируем /etc/fstab добавляем опции к своим разделам (https://wiki.samba.org/index.php/Samba_4/OS_Requirements#ext3.2Fext4_File_System):
user_xattr
acl
barrier=1
Например:

/dev/sda1   /               ext4    errors=remount-ro,user_xattr,acl,barrier=1   0       1

shutdown -r now

Настраиваем сервер времени:
vim /etc/ntp.conf:

server 0.ua.pool.ntp.org
server 1.ua.pool.ntp.org
server 2.ua.pool.ntp.org
server 3.ua.pool.ntp.org
ntpsigndsocket /var/lib/samba/ntp_signd/
restrict default mssntp

chgrp ntp /var/lib/samba/ntp_signd/
/etc/init.d/ntp restart

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

OPTIONS="-u bind -4"

vim /etc/bind/named.conf:

//include "/etc/bind/named.conf.default-zones";
include "/var/lib/samba/private/named.conf";

vim /etc/bind/named.conf.local:

include "/etc/bind/named.conf.log";

vim /etc/bind/named.conf.options:

options {
        directory "/var/cache/bind";
        auth-nxdomain no;
        listen-on-v6 { none; };
        listen-on { 127.0.0.1; 192.168.40.2; };
        allow-query { any; };
        recursion yes;
        allow-recursion { 127.0.0.1;192.168.40.0/24; };
        version "my dns server";
        allow-update {
                192.168.40.0/24;
                127.0.0.0/8;
        };
        dnssec-enable yes;
        dnssec-lookaside auto;
        dnssec-validation yes;
        tkey-gssapi-keytab "/var/lib/samba/private/dns.keytab";
};

vim /etc/bind/named.conf.log:

logging {
        channel update_debug {
                file "/var/log/bind/update_debug.log" versions 3 size 100k;
                severity debug;
                print-severity  yes;
                print-time      yes;
        };
        channel security_info {
                file "/var/log/bind/security_info.log" versions 1 size 100k;
                severity info;
                print-severity  yes;
                print-time      yes;
        };
        channel bind_log {
                file "/var/log/bind/bind.log" versions 3 size 1m;
                severity info;
                print-category  yes;
                print-severity  yes;
                print-time      yes;
        };

        category default { bind_log; };
        category lame-servers { null; };
        category update { update_debug; };
        category update-security { update_debug; };
        category security { security_info; };
};

mkdir /var/log/bind/
chown -R bind:bind /var/log/bind/

Делаем контроллер домена
rm /etc/samba/smb.conf
samba-tool domain provision --use-rfc2307 --use-xattrs=yes --interactive
Realm: EXAMPLE.COM
Domain: MYADDC
Server Role (dc, member, standalone) [dc]: enter
DNS backend (SAMBA_INTERNAL, BIND9_FLATFILE, BIND9_DLZ, NONE) [SAMBA_INTERNAL]: BIND9_FLATFILE

Здесь опции:
Realm — полное имя контроллера домена
Domain — короткое имя контроллера домена
DNS backend — как контроллер домена будет работать с DNS записями, в нашем случае выбран обычный текстовый файл DNS сервера bind

В конец файла /var/lib/samba/private/dns/example.com.zone добавляем:

samba IN A 192.168.40.2

/etc/init.d/bind9 restart

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

domain example.com
search example.com
nameserver 127.0.0.1

Настраиваем Kerberos
cp /var/lib/samba/private/krb5.conf /etc/

Настраиваем winbind
vim /etc/nsswitch.conf:

passwd: files winbind
group:  files winbind

/etc/init.d/samba-ad-dc restart

Открываем порты (https://wiki.samba.org/index.php/Samba_port_usage#Port_usage_when_Samba_runs_as_DC)
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.2 -i eth0 -p tcp -m state --state NEW -m multiport --dports 53,88,135,139,389,445,464,636,1024:5000,3268,3269,5353 -j ACCEPT
iptables -I INPUT 3 -s 192.168.40.0/24 -d 192.168.40.2 -i eth0 -p udp -m multiport --dports 88,137,138,389,464,5353 -j ACCEPT
/etc/init.d/netfilter-persistent save

PXE boot сервер на CentOS 6.5.

Добавляем репозитории
yum -y install tftp-server syslinux dhcp httpd

vim /etc/xinetd.d/tftp:

service tftp
{
        socket_type             = dgram
        protocol                = udp
        wait                    = yes
        user                    = root
        server                  = /usr/sbin/in.tftpd
        server_args             = -u tftp -c -s /tftpboot
        disable                 = no
        per_source              = 11
        cps                     = 100 2
        flags                   = IPv4
}

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

service xinetd restart
chkconfig xinetd on

Подготавливаем файлы для загрузки по сети:
mkdir -p /tftpboot/{pxelinux.cfg,images}
cp /usr/share/syslinux/{pxelinux.0,menu.c32,memdisk,mboot.c32,chain.c32} /tftpboot
mkdir /tftpboot/images/{centos,debian,opensuse,win7,acronis}

mount -o loop CentOS-6.5-x86_64-bin-DVD1.iso /mnt
cp -Rr /mnt/* /tftpboot/images/centos
umount /mnt

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

mount -o loop openSUSE-13.1-DVD-x86_64.iso /mnt
cp -Rr /mnt/* /tftpboot/images/opensuse
umount /mnt
wget http://tehnikpc.net/ftp/repo/opensuse/{linux,initrd} -P /tftpboot/images/opensuse

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

Создаём файл ответов для Debian:
vim /tftpboot/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/Kiev
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:
Загружаем 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 в папку для образов /tftpboot/images/win7 на tftp сервер

Загружаем какую-нибудь сборку Acronis например http://www.ex.ua/load/98820677 и копируем образ в /tftpboot/images/acronis

Создаём меню загрузки PXE
vim /tftpboot/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/win7/win7pex64.iso
menu end
menu begin
menu title utilities
label ..
menu exit
label   acronis
        kernel memdisk
        append iso initrd=images/acronis/acronis.iso
menu end

Открываем доступ по HTTP к файлам дистрибутивов Linux
vim /etc/httpd/conf.d/pxeboot.conf:

Alias /pxe /tftpboot/images/
<Directory /tftpboot/images/>
        Options Indexes FollowSymLinks
        Order Deny,Allow
        Deny from all
        Allow from 192.168.0.0/24
</Directory>

service httpd restart
chkconfig httpd on

Добавляем общий ресурс в samba
vim /etc/samba/smb.conf:

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

service smb start
chkconfig smb on

Настраиваем 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 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
service iptables save

Squid на CentOS 6.5.

Добавляем репозитории
yum -y install squid sarg httpd

Настраиваем squid на аторизацию по логину/паролю
vim /etc/squid/squid.conf:

visible_hostname example.com
#make web browzing faster
request_header_access Referer deny all
request_header_access X-Forwarded-For deny all
request_header_access Via deny all
request_header_access Cache-Control deny all
#hide IP address
forwarded_for off
#auth user by password
auth_param basic program /usr/lib64/squid/basic_ncsa_auth /etc/squid/internet_users
auth_param basic children 100
#users
acl myuser proxy_auth REQUIRED
acl myuser2 proxy_auth REQUIRED
#acls
acl bad_url url_regex "/etc/squid/acl/badurl"
acl upload url_regex "/etc/squid/acl/uploadurl"
acl filetypes urlpath_regex -i "/etc/squid/acl/filetypes"
acl banners url_regex "/etc/squid/acl/ads"
acl blockkeywords url_regex -i "/etc/squid/acl/keywords"
acl blockip src "/etc/squid/acl/badip"
http_access deny bad_url
http_access deny upload
http_access deny filetypes
http_access deny banners
http_access deny blockkeywords
http_access deny blockip
http_port 8080
error_directory /usr/share/squid3/errors/Russian-1251

Добавляем пользователей squid:
htpasswd -c /etc/squid/internet_users myuser
htpasswd /etc/squid/internet_users myuser2

Настраиваем списки доступа
mkdir /etc/squid/acl
vim /etc/squid/acl/badurl:

facebook.com
twitter.com
vk.com
odnoklassniki.ru
myspace.com
my.mail.ru

vim /etc/squid/acl/uploadurl:

brb.to
ex.ua
depositfiles.com
mediafire.com

vim /etc/squid/acl/filetypes:

.exe
.js
.torrent
.msi

vim /etc/squid/acl/ads:

^http://r\.mail\.ru/(cl)?b[[:digit:]]+
^http://images\.rambler\.ru/upl/
^http://(www\.)?sunradio\.ru/upload/bx/
^http://(www\.)?nnm\.ru/ban/
^http://(www\.)?java2phone\.ru/pict/b
^http://([[:alpha:]]+[[:digit:]]*\.)+bigmir\.net
^http://[[:alpha:]]+[[:digit:]]*\.[[:digit:]]+mdn\.net/viewad/
^http://(www\.)?nasvyazi\.ru/img/banner_
^http://(www\.)?games\.ru/b/
^http://(www\.)?computerra\.ru/upload/bx/
^http://(www\.)?finbs\.ru/Upload/
^http://(www\.)?torrents\.ru/forum/bn/
^http://(www\.)?powerclip\.ru/baner/
^http://(www\.)?nnm\.ru/rec/[[:digit:]]+/banner
^http://[[:alpha:]-]+\.nnm\.ru/rec/[[:digit:]]+/
^http://i\.ru-board\.com/temp/
^http://adserv\.top500\.org/b/
^http://([[:alpha:]-]+\.)+traf\.spb\.ru/(upload|b)/
^http://([[:alpha:]-]+\.)*inf\.by/i/b/
^http://(www\.)?gzt\.ru/files/
^http://([[:alnum:]]+\.)*ru-board\.com/board/temp/
^http://(www\.)?rb\.ru/img/content/ushki/

vim /etc/squid/acl/keywords:

fuck
sex
porno
nud
naked
condon
bitch

vim /etc/squid/acl/badip:

122.99.99.97
195.82.146.115
94.100.180.199

service squid start
chkconfig squid on

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

net.ipv4.ip_forward=1

sysctl -p

Настраиваем анализатор логов squid
vim /etc/sarg/sarg.conf:

graphs yes
graph_days_bytes_bar_color blue
graph_font /usr/share/fonts/dejavu/DejaVuSans-Bold.ttf
title "Squid User Access Reports"
topsites_sort_order BYTES D
max_elapsed 28800000
long_url no
charset UTF-8
exclude_string "127.0.0.1:example.com"

Настраиваем алиас в apache для sarg с авторизацией по логину/паролю:
vim /etc/httpd/conf.d/sarg.conf:

Alias /sarg /var/www/sarg
<Directory /var/www/sarg>
    DirectoryIndex index.html
    Order deny,allow
    Deny from all
    Allow from All
    Options Indexes
    AuthType Digest
    AuthName "sarg"
    AuthUserFile "/var/www/sarg/htpasswd"
    require valid-user
</Directory>

htpasswd -c /var/www/sarg/.htpasswd sarg myuser
При последующем добавлении пользователей ключ -c не нужен

Отчёты squid будут доступны по адресу http://example.com/sarg

service httpd start
chkconfig httpd on

Открываем порт для squid
iptables -A INPUT -s 192.168.0.0/24 -d 192.168.0.1 -i eth0 -p tcp -m state --state NEW --dport 8080 -j ACCEPT
service iptables save

Репозитории для CentOS 64 бита.

wget --no-check-certificate https://tehnikpc.net/ftp/repo/centos/addreporpm
bash addreporpm

Список репозиториев:
rpmforge
epel
remi
centalt
rpmfusion
elrepo
nux-dextop
pptp
puias
russianfedora
atomic
atrpms
passenger

Почтовый сервер на CentOS 6.5.

Имеем:
2 сетевых интерфейса:
eth0 — локальная сеть 192.168.0.1
eth1 — интернет 100.200.1.1
Контроллер домена example.com
Компоненты почтового сервера:
Dovecot — IMAP и POP3 сервер, MDA (mail delivery agent)
Postfix — MTA (mail transfer agent)
Postixadmin — управление почтовыми ящиками

Добавляем репозитории
Настраиваем контроллер домена

Настраиваем dovecot:
yum -y install dovecot dovecot-mysql
vi /etc/dovecot/dovecot.conf:

auth_debug = yes
auth_verbose = yes
service auth {
unix_listener auth-master {
user = vmail
group = mail
mode = 0660
}
inet_listener = { * }
}
mail_debug = yes
protocol lda {
postmaster_address = admin@example.com
mail_plugins = sieve
hostname = mail.example.com
}
passdb {
args = /etc/dovecot/dovecot-mysql.conf
driver = sql
}

userdb {
args = /etc/dovecot/dovecot-mysql.conf
driver = sql
}
protocols = imap pop3 lmtp
listen = *
base_dir = /var/run/dovecot/
instance_name = dovecot
login_greeting = my mail server
dict {
#quota = mysql:/etc/dovecot/dovecot-dict-sql.conf.ext
#expire = sqlite:/etc/dovecot/dovecot-dict-sql.conf.ext
}
!include conf.d/*.conf
!include_try local.conf

vi /etc/dovecot/conf.d/10-auth.conf:

disable_plaintext_auth = no
auth_mechanisms = plain login cram-md5

vi /etc/dovecot/conf.d/10-mail.conf:

mail_location = maildir:/var/spool/mail/%d/%u
mail_uid = vmail
mail_gid = mail
first_valid_uid = 2000
last_valid_uid = 2000
first_valid_gid = 12
last_valid_gid = 12

vi /etc/dovecot/conf.d/10-master.conf:

service imap-login {
inet_listener imap {
port = 143
}
inet_listener imaps {
port = 993
ssl = yes
}
}
service pop3-login {
inet_listener pop3 {
port = 110
}
inet_listener pop3s {
port = 995
ssl = yes
}
}
service lmtp {
unix_listener lmtp {
}
}
service imap {
}
service pop3 {
}
service auth {
unix_listener auth-userdb {
mode = 0600
user = vmail
group = mail
}
unix_listener /var/spool/postfix/dovecot-auth {
mode = 0666
user = postfix
group = postfix
}
}
service auth-worker {
}
service dict {
unix_listener dict {
}

vi /etc/dovecot/conf.d/10-ssl.conf:

ssl = yes
ssl_cert = ssl_key = ssl_parameters_regenerate = 168
ssl_cipher_list = ALL:!LOW:!SSLv2:!EXP:!aNULL

vi /etc/dovecot/conf.d/20-imap.conf:

protocol imap {
imap_client_workarounds = tb-extra-mailbox-sep
mail_plugins = autocreate
}

vi /etc/dovecot/conf.d/20-pop3.conf:

protocol pop3 {
pop3_uidl_format = %08Xu%08Xv
pop3_client_workarounds = outlook-no-nuls oe-ns-eoh
}

vi /etc/dovecot/conf.d/90-plugin.conf:

plugin {
autocreate = INBOX
autocreate2 = Sent
autocreate3 = Trash
autocreate4 = Drafts
autocreate5 = Junk
autosubscribe = INBOX
autosubscribe2 = Sent
autosubscribe3 = Trash
autosubscribe4 = Drafts
autosubscribe5 = Junk
#quota = maildir:User quota
#quota_rule = *:storage=1GB
#quota_rule2 = Trash:storage=+10%% # 10% of 1GB = 100MB
#quota_rule3 = Junk:storage=+10%% # 10% of 1GB = 100MB
#quota_rule4 = Drafts:storage=+10%% # 10% of 1GB = 100MB
}

Делаем файл запроса к mysql серверу vi /etc/dovecot/dovecot-mysql.conf:

driver = mysql
connect = host=/var/lib/mysql/mysql.sock dbname=postfix user=postfix password=postfixdbpass
default_pass_scheme = PLAIN
password_query = SELECT username as user, password, concat('/var/spool/mail/', maildir) as home, concat('maildir:/var/spool/mail/', maildir) as mail, 2000 as uid, 12 as gid FROM mailbox WHERE username = '%u' AND active = '1'
user_query = SELECT concat('/var/spool/mail/', maildir) as home, concat('maildir:/var/spool/mail/', maildir) as mail, 2000 AS uid, 12 AS gid, concat('maildir:storage=', quota) AS quota FROM mailbox WHERE username = '%u' AND active = '1'

Создаём виртуального пользователя, который будет заниматься локальной доставкой почты:
useradd -u 2000 -g mail -d /var/spool/mail -s /sbin/nologin vmail

Настраиваем postfix (по умолчанию должен быть установлен):
vi /etc/postfix/main.cf:

queue_directory = /var/spool/postfix
command_directory = /usr/sbin
daemon_directory = /usr/libexec/postfix
data_directory = /var/lib/postfix
mail_owner = postfix
myhostname = mail.example.com
mydomain = example.com
myorigin = $mydomain
inet_interfaces = all
mydestination = $myhostname, localhost.$mydomain, localhost
local_recipient_maps = $virtual_mailbox_maps, $virtual_alias_maps, $alias_maps
unknown_local_recipient_reject_code = 550
mynetworks_style = subnet
mynetworks = 127.0.0.0/8, 192.168.0.0/24, 100.200.1.0/24
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
recipient_delimiter = +
mail_spool_directory = /var/spool/mail
mailbox_command = /usr/libexec/dovecot/deliver
mailbox_transport = dovecot
smtpd_banner = $myhostname ESMTP
debug_peer_level = 2
debugger_command =
PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin
ddd $daemon_directory/$process_name $process_id & sleep 5
sendmail_path = /usr/sbin/sendmail.postfix
newaliases_path = /usr/bin/newaliases.postfix
mailq_path = /usr/bin/mailq.postfix
setgid_group = postdrop
html_directory = no
manpage_directory = /usr/share/man
sample_directory = /usr/share/doc/postfix-2.11.0/samples
readme_directory = /usr/share/doc/postfix-2.11.0/README_FILES
inet_protocols = ipv4
smtpd_client_restrictions = permit_mynetworks,
permit_sasl_authenticated,
check_client_access hash:/etc/postfix/client_access
# reject_unknown_client_hostname

smtpd_helo_restrictions = check_helo_access hash:/etc/postfix/hello_access,
permit_mynetworks,
permit_sasl_authenticated,
reject_invalid_helo_hostname,
reject_non_fqdn_helo_hostname,
reject_unknown_helo_hostname

smtpd_sender_restrictions = permit_mynetworks,
check_sender_access hash:/etc/postfix/sender_access,
reject_authenticated_sender_login_mismatch,
reject_unknown_sender_domain,
reject_unlisted_sender,
permit_sasl_authenticated
# reject_non_fqdn_sender,
# reject_unverified_sender

smtpd_recipient_restrictions = permit_mynetworks,
permit_sasl_authenticated,
reject_unauth_destination,
reject_unlisted_recipient,
reject_unknown_recipient_domain,
reject_non_fqdn_recipient,
reject_unverified_recipient

smtpd_etrn_restrictions = reject
smtpd_reject_unlisted_sender = yes
disable_vrfy_command = yes
strict_rfc821_envelopes = yes
show_user_unknown_table_name = no
address_verify_sender = <>
unverified_sender_reject_code = 550
smtpd_helo_required = yes
smtp_always_send_ehlo = yes
smtpd_hard_error_limit = 10
smtpd_timeout = 240s
smtp_helo_timeout = 240s
smtp_rcpt_timeout = 300s
#mysql
virtual_mailbox_base = /var/spool/mail
virtual_mailbox_maps = mysql:/etc/postfix/virtual_mailbox_maps.cf
virtual_alias_maps = mysql:/etc/postfix/virtual_alias_maps.cf
virtual_mailbox_domains = mysql:/etc/postfix/virtual_mailbox_domains.cf
#quota
virtual_mailbox_limit = 52428800
virtual_mailbox_limit_inbox = no
virtual_mailbox_limit_maps = mysql:/etc/postfix/virtual_mailbox_limit_maps.cf
virtual_mailbox_limit_override = yes
virtual_mailbox_extended = yes
virtual_create_maildirsize = yes
virtual_minimum_uid = 2000
virtual_uid_maps = static:2000
virtual_gid_maps = static:12
message_size_limit = 100485760
mailbox_size_limit = 524288000

virtual_transport = dovecot
dovecot_destination_recipient_limit=1
smtpd_sasl_auth_enable = yes
smtpd_use_tls = yes
smtpd_tls_cert_file = /etc/pki/dovecot/certs/dovecot.pem
smtpd_tls_key_file = /etc/pki/dovecot/private/dovecot.pem
smtpd_sasl_security_options = noanonymous
broken_sasl_auth_clients = yes
smtpd_sasl_type = dovecot
smtpd_sasl_path = /var/spool/postfix/dovecot-auth

vi /etc/postfix/master.cf:

smtps     inet  n       -       n       -       -       smtpd
#Dovecot LDA
dovecot   unix  -       n       n       -       -       pipe
  flags=DRhu user=vmail:mail argv=/usr/libexec/dovecot/deliver -d ${recipient}

Создаём базу данных для postfix:
mysql -u root -p

create database postfix;
GRANT ALL PRIVILEGES ON postfix.* TO 'postfix'@'localhost' IDENTIFIED BY 'postfixdbpass';
quit;

Создаём файлы postfix для базы данных mysql:
vi /etc/postfix/virtual_mailbox_maps.cf:

user = postfix
password = postfixdbpass
dbname = postfix
hosts = 127.0.0.1
table = users
select_field = maildir
where_field = email
additional_conditions = and enabled = 1

vi /etc/postfix/virtual_alias_maps.cf:

user = postfix
password = postfixdbpass
dbname = postfix
table = alias
select_field = goto
where_field = address
hosts = 127.0.0.1

vi /etc/postfix/virtual_mailbox_domains.cf:

user = postfix
password = postfixdbpass
hosts = localhost
dbname = postfix
query = SELECT domain FROM domain WHERE domain='%s' AND transport <> 'relay' AND active = '1'

vi /etc/postfix/virtual_mailbox_limit_maps.cf:

user = postfix
password = postfixdbpass
dbname = postfix
table = users
select_field = quota
where_field = email
additional_conditions = and enabled = 1
hosts = 127.0.0.1

Создаём базу данных псевдонимов:
newaliases

Создаём файлы базы данных для postfix:
touch /etc/postfix/{client_access,hello_access,sender_access,recipient_access}
postmap /etc/postfix/{client_access,hello_access,sender_access,recipient_access}

Генерируем самоподписные сертификаты для TLS/SSL протоколов:
openssl req -new -x509 -days 3650 -nodes -out /etc/pki/dovecot/certs/dovecot.pem -keyout /etc/pki/dovecot/private/dovecot.pem

service postfix start
chkconfig postfix on

service dovecot start
chkconfig dovecot on

Настраиваем postixadmin:
wget http://www.mirrorservice.org/sites/downloads.sourceforge.net/p/po/postfixadmin/postfixadmin/postfixadmin-2.3.7/postfixadmin-2.3.7.tar.gz
tar xzf postfixadmin-2.3.7.tar.gz
mkdir /var/www/postfixadmin
cp -r postfixadmin-2.3.7/* /var/www/postfixadmin/
chown -R apache:apache /var/www/postfixadmin/
vi /var/www/postfixadmin/config.inc.php:

$CONF['configured'] = true;
$CONF['default_language'] = 'ru';
$CONF['database_type'] = 'mysqli';
$CONF['database_host'] = 'localhost';
$CONF['database_user'] = 'postfix';
$CONF['database_password'] = 'postfixdbpass';
$CONF['database_name'] = 'postfix';
$CONF['database_prefix'] = '';
$CONF['encrypt'] = 'cleartext';

Создаём конфигурационный файл postfixadmin для apache:
vi /etc/httpd/conf.d/postfixadmin.conf:
Alias /pfa /var/www/postfixadmin

DirectoryIndex index.php
Options none
Order Deny,Allow
Deny from All
Allow from All

service httpd restart

Переходим на страницу настройки postfixadmin http://example.com/pfa/setup.php:
Генерируем hash пароля установки
Копируем hash в опцию «$CONF[‘setup_password’]» в /var/www/postfixadmin/config.inc.php
Вводим пароль установки
Логин вводим в виде почтового адреса, например admin@example.com
Пароль администратора
Теперь для управления почтовыми ящиками нужно заходить по адресу http://example.com/pfa

Добавляем записи для почтового сервера в наши файлы зон для внутренней и для внешней сети:
vi /var/named/chroot/etc/master/example.com.lan:
MX 10 mail.example.com.
mail.example.com. A 192.168.0.1

vi /var/named/chroot/etc/master/example.com.wan:
MX 10 mail.example.com.
mail.example.com. A 100.200.1.1

vi /var/named/chroot/etc/master/example.com.wan.rev:
1 IN PTR mail.example.com.

service named restart

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

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 25,110,143,465,993,995 -j ACCEPT
iptables -I INPUT 3 -s ip-адрес-внешних-клиентов -d 100.200.1.1 -i eth1 -p tcp -m state --state NEW -m multiport --dports 25,110,143,465,993,995 -j ACCEPT

service iptables save

DNS сервер на CentOS 6.5.

Имеем 2 сетевых интерфейса:
eth0 — локальная сеть 192.168.0.1
eth1 — интернет 100.200.1.1
Домен example.com

Добавляем репозитории

yum -y install bind-chroot

cp /etc/named.conf /var/named/chroot/etc/
vim /var/named/chroot/etc/named.conf:

options {
listen-on port 53 { 127.0.0.1;100.200.1.1;192.168.0.1; };
listen-on-v6 port 53 { none; };
directory "/var/named";
dump-file "/var/named/data/cache_dump.db";
statistics-file "/var/named/data/named_stats.txt";
memstatistics-file "/var/named/data/named_mem_stats.txt";
allow-query { any; };
recursion yes;
allow-recursion {
127.0.0.1;
192.168.0.0/24;
};
notify yes;
dnssec-enable yes;
dnssec-validation yes;
dnssec-lookaside auto;

/* Path to ISC DLV key */
bindkeys-file "/etc/named.iscdlv.key";
managed-keys-directory "/var/named/dynamic";
version "my dns server";
};
logging {
channel default_debug {
file "data/named.run";
severity dynamic;
};
category lame-servers { null; };
};
#Локальная зона
view "internal" {
match-clients {
127.0.0.1;
192.168.0.0/24;
};
zone "example.com" IN {
type master;
file "/etc/master/example.com.lan";
allow-update { none; };
};
zone "0.168.192.in-addr.arpa" IN {
type master;
file "/etc/master/example.com.lan.rev";
allow-update { none; };
};
zone "." IN {
type hint;
file "named.ca";
};
include "/etc/named.rfc1912.zones";
};
#Интернет зона
view "external" {
match-clients { any; };
allow-query { any; };
zone "example.com" IN {
type master;
file "/etc/master/example.com.wan";
allow-update { none; };
};
zone "1.200.100.in-addr.arpa" IN {
type master;
file "/etc/master/example.com.wan.rev";
allow-update { none; };
};
include "/etc/named.rfc1912.zones";
};

Делаем файлы зон:
mkdir /var/named/chroot/etc/master
vi /var/named/chroot/etc/master/example.com.lan:

$TTL 3600 ; 1 hour
@ IN SOA ns.example.com. admin.example.com. (
2014230201 ; 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.0.1
ns IN A 192.168.0.1
example.com. IN A 192.168.0.1

vi /var/named/chroot/etc/master/example.com.lan.rev:

$TTL 86400
@ IN SOA ns.example.com. admin.example.com. (
2014230201 ;serial
8H ;refresh
4H ;retry
5W ;expire
1D ;minimum
)
IN NS ns.example.com.
IN A 255.255.255.0
1 IN PTR example.com.
1 IN PTR ns.example.com.

vi /var/named/chroot/etc/master/example.com.wan:

$TTL 3600 ; 1 hour
@ IN SOA ns.example.com. admin.example.com. (
2014230201 ; 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 100.200.1.1
ns IN A 100.200.1.1
example.com. IN A 100.200.1.1

vi /var/named/chroot/etc/master/example.com.wan.rev:

$TTL 86400
@ IN SOA ns.example.com. admin.example.com. (
2014230201 ;serial
8H ;refresh
4H ;retry
5W ;expire
1D ;minimum
)
IN NS ns.example.com.
IN PTR example.com.
IN A 255.255.255.0
1 IN PTR example.com.
1 IN PTR ns.example.com.

Открываем порты в фаерволле:
iptables -I INPUT 2 -d 100.200.1.1 -i eth1 -p udp --dport 53 -j ACCEPT
iptables -I INPUT 3 -d 192.168.0.1 -i eth0 -p udp --dport 53 -j ACCEPT
service iptables save

Запускаем и добавляем в автозагрузку:
service named start
chkconfig named on

Переключаемся на свой DNS сервер, редактируем /etc/resolv.conf:

search example.com
nameserver 127.0.0.1

Active Directory Domain Controller на CentOS 6.5 совместимый с Microsoft

Имеем 2 сетевых интерфейса:
eth0 — локальная сеть 192.168.20.1
eth1 — интернет 100.200.1.1
Контроллер домена example.com

Добавляем репозитории

Отключаем SELinux
vim /etc/sysconfig/selinux:

selinux=disabled

setenforce 0

Редактируем /etc/fstab добавляем опции к своим разделам (https://wiki.samba.org/index.php/Samba_4/OS_Requirements#ext3.2Fext4_File_System):
user_xattr
acl
barrier=1

Например:

/dev/sdd1 / ext4 defaults,discard,user_xattr,acl,barrier=1 1 1

shutdown -r now

Устанавливаем зависимости samba 4 (https://wiki.samba.org/index.php/Samba_4/OS_Requirements#Red_Hat_Enterprise_Linux_or_CentOS):
yum update
yum -y install gcc libacl-devel libblkid-devel gnutls-devel readline-devel python-devel gdb pkgconfig krb5-workstation zlib-devel setroubleshoot-server libaio-devel setroubleshoot-plugins policycoreutils-python libsemanage-python setools-libs-python setools-libs popt-devel libpcap-devel sqlite-devel libidn-devel libxml2-devel libacl-devel libsepol-devel libattr-devel keyutils-libs-devel cyrus-sasl-devel cups-devel bind-utils

Настраиваем Kerberos
cp /usr/local/samba/private/krb5.conf /etc/
vi /etc/krb5.conf:

[libdefaults]
default_realm = EXAMPLE.COM
dns_lookup_realm = false
dns_lookup_kdc = true

[kdc]
check-ticket-addresses = false

Устанавливаем последнюю стабильную версию samba 4 на данный момент 4.1.5:
cd /usr/src
wget http://www.samba.org/samba/ftp/stable/samba-4.1.5.tar.gz
tar xzf samba-4.1.5.tar.gz
cd samba-4.1.5
./configure --enable-debug --enable-selftest
make
make install

Делаем контроллер домена:
rm /etc/smb.conf
/usr/local/samba/bin/samba-tool domain provision --realm=EXAMPLE.COM --domain=MYADDC --adminpass=******** --server-role=dc --dns-backend=BIND9_FLATFILE

Здесь опции:
realm — полное имя контроллера домена
domain — короткое имя контроллера домена
adminpass — пароль для учётной записи администратора (Administrator) контроллера домена
dns-backend — как контроллер домена будет работать с DNS записями, в нашем случае выбран обычный текстовый файл DNS сервера bind

Делаем файлы зоны DNS из файла, который сгенерировала samba
Для интернет зоны
mv /usr/local/samba/private/dns/example.com.zone /usr/local/samba/private/dns/example.com.wan
Для локальной зоны
cp /usr/local/samba/private/dns/example.com.wan /usr/local/samba/private/dns/example.com.lan
sed -i ‘s|100.200.1.1|192.168.20.1|g’ /usr/local/samba/private/dns/example.com.lan

vi /etc/named.conf:

options {
listen-on port 53 { 127.0.0.1;100.200.1.1;192.168.20.1; };
listen-on-v6 port 53 { none; };
directory "/var/named";
dump-file "/var/named/data/cache_dump.db";
statistics-file "/var/named/data/named_stats.txt";
memstatistics-file "/var/named/data/named_mem_stats.txt";
allow-query { any; };
recursion yes;
allow-recursion {
127.0.0.1;
192.168.20.0/24;
};
notify yes;
dnssec-enable yes;
dnssec-validation yes;
dnssec-lookaside auto;

/* Path to ISC DLV key */
bindkeys-file "/etc/named.iscdlv.key";
managed-keys-directory "/var/named/dynamic";
version "my dns server";
};
logging {
channel default_debug {
file "data/named.run";
severity dynamic;
};
category lame-servers { null; };
};
tkey-gssapi-keytab "/usr/local/samba/private/dns.keytab";
include "/usr/local/samba/private/named.conf";

vi /usr/local/samba/private/named.conf:

#локальная зона
view "internal" {
match-clients {
127.0.0.1;
192.168.20.0/24;
};
zone "example.com." IN {
type master;
file "/usr/local/samba/private/dns/example.com.lan";
include "/usr/local/samba/private/named.conf.update";
check-names ignore;
};
zone "." IN {
type hint;
file "named.ca";
};
include "/etc/named.rfc1912.zones";
};
#интернет зона
view "external" {
match-clients { any; };
allow-query { any; };
zone "example.com." IN {
type master;
file "/usr/local/samba/private/dns/example.com.wan";
include "/usr/local/samba/private/named.conf.update";
check-names ignore;
};
};

service named restart

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

search example.com
domain example.com
nameserver 127.0.0.1

Делаем скрипт автозапуска samba 4 (http://wiki.samba.org/index.php/Samba4/InitScript):
vi /etc/init.d/samba4:

#!/bin/bash

. /etc/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

prog=samba
prog_dir=/usr/local/samba/sbin/
lockfile=/var/lock/subsys/$prog

start() {
[ "$NETWORKING" = "no" ] && exit 1
# [ -x /usr/sbin/ntpd ] || exit 5

# Start daemons.
echo -n $"Starting samba4: "
daemon $prog_dir/$prog -D
RETVAL=$?
echo
[ $RETVAL -eq 0 ] && touch $lockfile
return $RETVAL
}

stop() {
[ "$EUID" != "0" ] && exit 4
echo -n $"Shutting down samba4: "
killproc $prog_dir/$prog
RETVAL=$?
echo
[ $RETVAL -eq 0 ] && rm -f $lockfile
return $RETVAL
}

# See how we were called.
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status $prog
;;
restart)
stop
start
;;
reload)
echo "Not implemented yet."
exit 3
;;
*)
echo $"Usage: $0 {start|stop|status|restart|reload}"
exit 2
esac

chmod +x /etc/init.d/samba4
chkconfig samba4 on
service samba4 start

Если пишет ошибки, запускаем samba в debug режиме и смотрим на что ругается:
/usr/local/samba/sbin/samba -i --debuglevel=9

Для удобства управления добавляем пути samba в своё окружение
vi /root/.bash_profile:

PATH=$PATH:$HOME:/usr/local/samba/sbin:/usr/local/samba/bin

Устанавливаем сервер времени
yum -y install ntp
vi /etc/ntp.conf:

server 0.ua.pool.ntp.org
server 1.ua.pool.ntp.org
server 2.ua.pool.ntp.org
server 3.ua.pool.ntp.org
ntpsigndsocket /usr/local/samba/ntp_signd/
restrict default mssntp

service ntpd restart
chkconfig ntpd on

Открываем порты в фаерволле (https://wiki.samba.org/index.php/Samba_port_usage#Port_usage_when_Samba_runs_as_DC)

iptables -I INPUT 1 -s 192.168.20.0/24 -d 192.168.20.1 -i eth0 -p tcp -m state --state NEW -m multiport --dports 53,88,135,139,389,445,464,636,1024:5000,3268,3269,5353 -j ACCEPT
iptables -I INPUT 2 -d 100.200.1.1 -i eth1 -p tcp -m state --state NEW -m multiport --dports 53,88,135,139,389,445,464,636,1024:5000,3268,3269,5353 -j ACCEPT
iptables -I INPUT 3 -s 192.168.20.0/24 -d 192.168.20.1 -i eth0 -p udp -m multiport --dports 88,137,138,389,464,5353 -j ACCEPT
iptables -I INPUT 4 -d 100.200.1.1 -i eth1 -p udp -m multiport --dports 88,137,138,389,464,5353 -j ACCEPT
service iptables save