Nginx как проксирующий фронт-енд к Apache #2

В продолжение темы о связке nginx + apache + directadmin решил все же написать хоть что то 🙂

Данная фича писалась “на коленке” и никоим образом не претендует на полноценное и законченное решение, однако на протяжении года проработало на shared-хостинге, обслуживая более 1000 доменов.

Суть заключается в том, что nginx полностью отвечает за отдачу всей статики (картинки, архивы, файлы стилей и т.д.), а апач занимается обработкой скриптов. Для снижения нагрузки апач не ведет access_log (только error_log),  логи так же ведет nginx. За SSL тоже отвечает nginx.

nginx выступает в роли фронт-енда, в то время как апач – в роли бек-енда. nginx слушает внешние IP адреса, апач – только один, например, 127.0.0.1:80

Read more Nginx как проксирующий фронт-енд к Apache #2

CSF FireWall + DirectAdmin

ConfigServer сделали интеграцию CSF фаирвола с панелью управления хостингом DirectAdmin.

При установке скрипт проверяет необходимые параметры и сам интегрируется в администртивную часть DirectAdmin-а. Все просто и удобно. Настройки CSF фаирвола будут доступны для редактирования в административной части хостинг-панели.

Итак, устанавливаем:

wget http://www.configserver.com/free/csf.tgz
tar -xzf csf.tgz
cd csf
sh install.sh

После установки запускем скрипт для проверки необходимых модулей в iptables:

# perl /etc/csf/csftest.pl
Testing ip_tables/iptable_filter…OK
Testing ipt_LOG…OK
Testing ipt_multiport/xt_multiport…OK
Testing ipt_REJECT…OK
Testing ipt_state/xt_state…OK
Testing ipt_limit/xt_limit…OK
Testing ipt_recent…OK
Testing ipt_owner…OK
Testing iptable_nat/ipt_REDIRECT…OK

RESULT: csf should function on this server

При установке скрипт автоматически делает преднастройку первоначального конфигурационного файла.
После инсталляции можно приступить к более тонкой настройке параметров либо прямо в файле /etc/csf.conf, либо в панели управления.
Скиншоты GUI посмотреть можно тут, тут и тут

CSF великолепно работает как с панелями так и без них, CSF Firewall интегрируется в такие панели как: Cpanel, DirectAdmin, Webmin

Exim + greylist

I want to share how i reduce spam in my box.

Maybe not perfect solution but  works 🙂
Always make backup and use it at your own risk !

Tested on CentOS 5

Install Greylist:

# rpm -Uvh http://dl.atrpms.net/el5-i386/atrpms/stable/greylistd-0.8.3.2-8.0.el5.noarch.rpm

Now you need to change permissions:

# chown -R mail.mail /etc/greylistd/
# chown -R mail.mail /var/run/greylistd/
# chown -R mail.mail /var/lib/greylistd/
# chown -R mail.mail /usr/sbin/greylist*

start greylistd:

# /usr/bin/su mail -c /usr/sbin/greylistd &

I use original SpamBlocker2 (thanks to Jeff )

######################################################################
# SpamBlocker.exim.conf.2.1.1-release                                #
# 05-Jun-2007                                                        #
# Runtime configuration file for DirectAdmin/Exim 4.24 and above     #
# Requires exim.pl dated 20-Apr-2007 17:09 or later                  #

You will need to edit /etc/exim.conf
Add

acl_smtp_connect = acl_connect
acl_smtp_helo = check_helo

just before:

acl_smtp_rcpt = check_recipient
acl_smtp_data = check_message

Find

######################################################################
# ACLs #
######################################################################
begin acl

add after:

###############################
# ACL connect
###############################
acl_connect:
accept hosts = +whitelist_hosts_ip : +relay_hostsdrop message = Your IP Blacklisted - see http://www.domain.com/
hosts = +bad_sender_hosts_ip

# We do not receive mails from orange, hinet... etc
drop message = Sender Blacklisted - http://www.yourdomain.tld/blocked.html?$sender_host_name
condition = ${if match{$sender_host_name} \
{hinet-ip|hinet|orange|asianet.co.th} \
{yes}{no}}

# Delay. (Spammers doesn't like to wait while connecting
# Better do not use on high load servers because it will hold too many open connection
# to 587 port accept connection without delay
accept condition = ${if eq {$interface_port}{587}{yes}{no}}

accept
logwrite = Delay 10s for $sender_host_address ($sender_host_name)
delay = 10s

###############################
# ACL HELO/EHLO
###############################
check_helo:

accept condition = ${if eq {$interface_port}{587}{yes}{no}}
accept hosts = +whitelist_hosts: +whitelist_hosts_ip : +relay_hosts

# for some cases this rule may need to comment
deny message = rejected due to forged HELO name - $sender_helo_name
condition = ${if match {$sender_helo_name} \
{\N^[^.].*\.[^.]+$\N} \
{no}{yes}}
!hosts = +whitelist_hosts: +whitelist_hosts_ip : +relay_hosts

drop message = HELO/EHLO cannot be numbers only
condition = ${if match{$sender_helo_name}{\N^\d+$\N}{yes}{no}}

# If remote host greets with an IP address, reject connection:
drop message = IP address not allowed in HELO/EHLO
condition = ${if isip {$sender_helo_name}{true}{false}}

drop message = This is my IP. Go away
condition = ${if eq{$sender_helo_name}{$interface_address} {yes}{no}}

deny message = HELO/EHLO required by SMTP RFC.
condition = ${if eq{$sender_helo_name}{}{yes}{no}}

accept

Find:

#require verify = sender

Add after:

drop message = Use your provider SMTP. Email blocked
condition = ${if match{$sender_host_name} \
{adsl|dialup|pool|peer|dhcp|dsl|broadband|ppp|dynamic|cable} \
{yes}{no}}
hosts = !+relay_hosts
domains = +use_rbl_domains
!authenticated = *

find:

# accept if address is in a local domain as long as recipient can be verified
accept domains = +local_domains
endpass
message = "Unknown User"

Add before:

# Perform greylisting.
defer message = $sender_host_address is greylisted. Please try again later.
log_message = greylisted.
domains = +relay_domains : +local_domains
!senders = : postmaster@*
!hosts = : +relay_hosts : \
${if exists {/etc/greylistd/whitelist-hosts}\
{/etc/greylistd/whitelist-hosts}{}} : \
${if exists {/etc/virtual/whitelist-hosts}\
{/etc/virtual/whitelist-hosts}{}}verify = recipient/callout=5s,use_sender,defer_ok
condition = ${readsocket{/var/run/greylistd/socket}\
{--grey $sender_host_address $sender_address $local_part@$domain}{5s}{}{false}}

Save exim.conf and restart exim:
# service exim restart

That’s All.
Now you can check maillog and see something like below :

2008-03-17 09:20:03 H=(pentium) [84.21.226.22] rejected EHLO or HELO pentium: rejected due to forged HELO name - pentium
2008-03-17 12:22:28 Delay 10s for 59.93.211.220 ()
2008-03-17 12:22:35 H=(59.94.122.15) [59.94.122.15] rejected EHLO or HELO 59.94.122.15: IP address not allowed in HELO/EHLO
2008-03-17 12:22:52 H=cpc1-neww3-0-0-cust845.cdif.cable.ntl.com (home-ad73427dc5) [82.11.227.78] F= rejected RCPT : Use your provider SMTP. Email blocked
2008-03-17 12:28:23 H=n4a.bullet.mail.ac4.yahoo.com [76.13.13.67] rejected connection in "connect" ACL: Sender Blacklisted
2008-03-17 13:05:17 H=hore.iptelecom.net.ua [212.xx.224.8] F=<ins> temporarily rejected RCPT : greylisted.<code>2008-03-17 13:09:48 H=ppp85-140-xx-38.pppoe.mtu-net.ru (mtu-net.ru) [85.140.xx.38] F= rejected RCPT : Use your provider SMTP. Email blocked

Also you can check greylisting stats:

# greylist stats
Statistics since Sun Mar 16 23:18:21 2008 (14 hours and 53 minutes ago)
-----------------------------------------------------------------------
146 items, matching 171 requests, are currently whitelisted
0 items, matching 0 requests, are currently blacklisted
155 items, matching 156 requests, are currently greylistedOf 146 items that were initially greylisted:
- 146 (100.0%) became whitelisted
- 0 ( 0.0%) expired from the greylist
-----------------------------------------------------------------------

I hope this small How-To will help you to reduce incoming spam.

Nginx как проксирующий фронт-енд к Apache

Что имеем:

Самый обычный набор namebased хостинг-провайдера:
– apache 1.3.x
– DirectAdmin
– на сервер на базе CentOS 5.x и тормоза при отдаче страниц клиентам

Что получим:
Nginx в качестве фронт-енда для Апачи
– автосоздание конфигов для виртуал.хостов из Directadmin
– ограничение количества коннектов с одного IP
– ощутимое снижение нагрузки на сервер и на Apache

Установка nginx.
Скачиваем стабильную ветку (на момент написания 0.6.32 – последняя стабильная версия) :
# wget http://sysoev.ru/nginx/nginx-0.6.32.tar.gz
# tar -zxvf ./nginx-0.6.32.tar.gz
# cd nginx-0.6.32

в файле configure указываем нужные модули, а неиспользуемые лучше отключить. Большое количество модулей немного замедляет работу nginx.
У меня nginx собирается такой:

cat ./myconfigure
#!/bin/sh
./configure \
--prefix=/usr/local/nginx \
--sbin-path=/usr/bin \
--without-http_ssi_module \
--without-http_auth_basic_module \
--without-mail_pop3_module \
--without-mail_imap_module \
--without-mail_smtp_module \
--user=apache \
--group=apache \
--with-http_stub_status_module \
--with-http_realip_module \
--without-http_charset_module \
--without-http_memcached_module \
--without-http_upstream_ip_hash_module \
--without-http_browser_module \
--with-http_flv_module \
--with-http_sub_module \
--error-log-path=/var/log/nginx/error.log \
--http-log-path=/var/log/nginx/access.log

# ./myconfigure
….
# make ; make install

Далее надо будет настроить конфиг nginx и шаблоны апачевского конфига от директадмина

Будет больше времени, допишу как это все это сделал….