Настройка Прокси Сервера Squid.


Преамбула о прокси Серверах.
Прокси-сервер, осуществляющий доступ в Интернет, предоставляет следующие возможности:

Пример файла конфигурации /etc/squid/squid.conf:

#Установим объем памяти, доступный squid, и каталог для кэша.
cache_mem 16 MB
cache_dir ufs /mnt/media/cache/squid 512 16 256

#Укажем хосты, с которых разрешен доступ к прокси
acl localhost src 127.0.0.1/255.255.255.255

acl all src 0.0.0.0/0.0.0.0
#Все возможные IP адреса

# Откроем доступ к прокси-серверу с клиентов
# из нашей подсети (192.16.0.0/255.255.0.0)
acl mynetwork src 192.168.1.0/255.255.255.0 #

#разрешенные SSL порты:
#acl SSL_ports port 443 563

#запретим метод CONNECT для всех портов, кроме указанных в acl SSL_ports:
#http_access deny CONNECT !SSL_ports

#пропишем пользователей, которым разрешено пользоваться squid (den, admin, developer):
http_access allow mynetwork
# Дать доступ адресам типа 192.168.1.ххх
http_access allow localhost
# Дать доступ адресу 127.0.0.1 (acl localhost)
http_access deny all
# Всем остальным доступ закрыть (acl all)

####################
#Параметры сети:
http_port 192.168.1.10:5781 transparent
#5442

#Если соседей (peer) нет, установите:
icp_port 0
htcp_port 0
######################################################
# Отключим кеширование динамически загружаемых страниц
acl QUERY urlpath_regex cgi-bin \?
no_cache deny QUERY

acl XYZZY url_regex ^http://letitbit.net/^
no_cache deny XYZZY

# Отключим бесполезный лог менеджера кеша
cache_store_log none

# Пароль для анонимного ftp-соединения
#ftp_user ano@nim.ru
#Настройки фтп через прокси
#ftp_user anonymous@
ftp_list_width 32
ftp_passive on
ftp_sanitycheck on

cache_swap_high 95
#При достижение этого уровня заполнения кэша (в процентном соотношении) #начинается ускоренный процесс удаления старых объектов.

cache_swap_low 90
#Процесс удаления прекращается при достижении этого уровня.

maximum_object_size 4096 KB
#Максимальный размер кэшируемого объекта.

minimum_object_size 0 KB
#Файлы меньшего размера не сохраняются

#################

cache_effective_user nobody
#При запуске squid от имени root изменить UID на указанный
cache_effective_group nogroup
#Аналогично для GID
#Укажем имя нода на котором стоит squid.
visible_hostname INNAME-Serv


################
#Отказ от рекламы
#redirect_program /etc/squid/bin/redirector
#redirect_program /etc/adzapper/squid_redirect

###############
## Проверка антивируссом
#redirect_program /usr/sbin/squidclamav
redirect_children 4

29.09.2009 Итог показал, что для домашнего использования, и при выделенной линии, при слабой машине Pentium 166 mmx, эффективность кешируещего сервера очень низкая, большие задержки в отправке и приёме запроса, и различные баннеро резки и антивурусные проверки, ещё больше снижают работу. Эффективней сделать на сервере, NAT про броску.

14.06.2010.
###################
Отключения кеширования

cache deny all
cache_dir null /tmp

И при установке должен быть включен ключь:

--enable-storeio=null,...

Для проверки антивирусом Clamav необходимо собрать с USE="icap-client". И собрать пакет C_Icap:

# mkdir -p /usr/portage/net-misc/c-icap/files
# cd /usr/portage/net-misc/c-icap/
# wget -r --no-parent http://portage.org.ua/portage/net-misc/c-icap/
# mv portage.org.ua/portage/net-misc/c-icap/* .
# rm -rf ./portage.org.ua/

формируем файл manifest

# ebuild /usr/portage/net-misc/c-icap/c-icap-190309.ebuild manifest

собираем c-icap

# emerge c-icap

создем или приводим к следующему виду конфигурационный файл c-icap.conf

# nano /etc/c-icap/c-icap.conf

PidFile /var/run/c-icap/c-icap.pid
CommandsSocket /var/run/c-icap/c-icap.sock
Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
## set KeepAliveTimeout to -1 for no timeout
KeepAliveTimeout 600
StartServers 5
MaxServers 20
MinSpareThreads 15
MaxSpareThreads 30
ThreadsPerChild 15
MaxRequestsPerChild 0

Port 1344
User nobody
Group nobody

#ServerAdmin you@your.address # Not implemented yet
#ServerName localhost:1344 # Not implemented yet

TmpDir /tmp
MaxMemObject 131072

ServerLog /var/log/c-icap/server.log
AccessLog /var/log/c-icap/access.log
DebugLevel 1

ModulesDir /usr/lib/c_icap
Module logger sys_logger.so
#Module perl_handler perl_handler.so

sys_logger.Prefix "C-ICAP:"
sys_logger.Facility local1

##Specify wich logger to use......
#Logger sys_logger
Logger file_logger

## AclControlers example. The default_acl is the buildin acl controller
## To load an extrernal access controller named my_acl.so use:
#Module access_controller my_acl.so

## This parameter needed to specify the order of used acl controllers
## If not specified access control will be disabled
#AclControllers default_acl

## An example of acl lists for default_acl controller.
## acl and icap_access are aliases for default_acl.acl and default_acl.icap_access
#acl localnet_options src 192.168.1.0/255.255.255.0 type options
#acl localnet_respmod src 192.168.1.0/255.255.255.0 type respmod
#acl localnet src 192.168.1.0/255.255.255.0
##Use the folllowing to demand use of username ......
##acl localnet src 192.168.1.0/255.255.255.0 user *
#acl externalnet src 0.0.0.0/0.0.0.0
#acl barbarian src 192.168.1.5

acl externalnet src 0.0.0.0/0.0.0.0
acl localsquid_respmod src 127.0.0.1 type respmod
acl localsquid src 127.0.0.1
icap_access allow localsquid_respmod
icap_access allow localsquid

##An example to specify access to server
#icap_access deny barbarian
#icap_access allow localnet_options
#icap_access allow localnet_respmod
#icap_access allow localnet
## http_auth mean that the icap server must try to authenticate the request
## using the http headers ....
#icap_access http_auth localnet
#icap_access deny externalnet

#Also you can specify which hosts to log or not.
# Comment out the folowing two lines to log only the external net
#icap_access nolog localnet
#icap_access log externalnet

##An example for authentication methods ....
## To load an extarnal authentication method module named my_authmethod.so use:
#Module auth_method my_authmethod.so

##The following parameter needed to specify the order of authenticators for
##specific authentication method. file_basic is a buildin authenticator
##for buildin basic authentication method (Not implemented yet......) ......
#AuthMethod basic file_basic

ServicesDir /usr/lib/c_icap
Service echo_module srv_echo.so
Service url_check_module srv_url_check.so
Service antivirus_module srv_clamav.so

##Adding the alias avscan for srv_clamav service.
ServiceAlias avscan srv_clamav?allow204=on&sizelimit=off&mode=simple

# Antivirus module settings
# For allowed file types or groups of file types look at c-icap.magic
srv_clamav.ScanFileTypes TEXT DATA EXECUTABLE ARCHIVE GIF JPEG MSOFFICE
#The percentage of data to sent if the downloaded file exceeds the StartSendPercentDataAfter size
srv_clamav.SendPercentData 5
srv_clamav.StartSendPercentDataAfter 2M

##Comment out the following line to enable 204 responces outside previews for srv_clamav
## if your icap client support it. For squid let it off
#srv_clamav.Allow204Responces on
# The Maximum object to be scanned.
srv_clamav.MaxObjectSize 5M
#The directory which clamav library will use as temporary.
srv_clamav.ClamAvTmpDir /tmp
#Sets the maximum number of files in archive.)i Set it to 0 to disable it
srv_clamav.ClamAvMaxFilesInArchive 0
#Sets the maximal archived file size. Set it to 0 to disable it.
srv_clamav.ClamAvMaxFileSizeInArchive 100M
#The maximal recursionl.Set it to 0 to disable it.
srv_clamav.ClamAvMaxRecLevel 5

# And here the viralator-like mode.
# where to save documents
srv_clamav.VirSaveDir /var/www/htdocs/download
# from where the documents can be retrieved (you can find the get_file.pl script in contrib dir)
srv_clamav.VirHTTPServer "http://fortune/cgi-bin/get_file.pl?usename=%f&remove=1&file="
# The refresh rate....
# srv_clamav.VirUpdateTime 15
# For which filetypes the "virelator like mode" will be used.
# srv_clamav.VirScanFileTypes ARCHIVE EXECUTABLE

#c_icap - для проверки антивирусом
icap_enable on
icap_preview_enable on
icap_preview_size 128
icap_send_client_ip on

icap_service service_avi_req reqmod_precache 0 icap://localhost:1344/srv_clamav
icap_service service_avi respmod_precache 1 icap://localhost:1344/srv_clamav

icap_class class_antivirus service_avi service_avi_req
icap_access class_antivirus allow all

Обновляем базы clamav (сам ClamAV запускать не стоит) и запускаем c-icap

# freshclam # /etc/init.d/c-icap start

Источники:

  • http://daevy.uzps.mh.ru/?p=262
  • http://www.nixp.ru/articles/Использование-SquidPlusClamAVPlusc-icap-для-проверки-web-трафика-на-вирусы.html
  • Hosted by uCoz