- Squid
- Contents
- Installation
- Configuration
- Accessing services on local hostnames
- Starting
- Content Filtering
- Frontend
- Squid 4.x not supported in Webmin
- Ad blocking with adzapper
- Installation
- Configuration
- Transparent web proxy
- iptables
- Shorewall
- HTTP Authentication
- Hide Browser’s Real IP Address
- SSL Bumping
- Create Self-Signed Root CA Certificate
- Create a DER-encoded certificate to import into users’ browsers
- Modify Squid Configuration File
- Create and initialize TLS certificates cache directory
- Ubuntu Documentation
- Introduction
- Installation
- Key File Locations
- Configurations
- Squid Configuration
- Service Administration
- Defining the Cache Space
- Customize Squid Error Pages
- Установка и настройка Squid на Ubuntu
- Установка и базовая настройка
- Проверка
- Прозрачный прокси
- Авторизация по логину и паролю
- Слушаем на определенном интерфейсе
- Исходящий сетевой интерфейс
- Настройка цепочки прокси-серверов
Squid
This article or section needs language, wiki syntax or style improvements. See Help:Style for reference.
Squid is a caching proxy for HTTP, HTTPS and FTP, providing extensive access controls.
Contents
Installation
Configuration
By default, the cache directories will be created in /var/cache/squid , and the appropriate permissions set up for those directories. However, for greater control, we need to delve into /etc/squid/squid.conf .
The following options might be of some use to you. If you do not have the option present in your configuration file, add it!
- http_port — Sets the port that Squid binds to on your local machine. You can have Squid bind to multiple ports by specifying multiple http_port lines. By default, Squid binds to port 3128.
- http_access — This is an access control list for who is allowed to use the proxy. By default only localhost is allowed to access the proxy. For testing purposes, you may want to change the option http_access deny all to http_access allow all , which will allow anyone to connect to your proxy. If you wanted to just allow access to your subnet, you can do:
- cache_mgr — This is the email address of the cache manager.
- shutdown_lifetime — Specifies how long Squid should wait when its service is asked to stop. If you are running squid on your desktop PC, you may want to set this to something short.
- cache_mem — This is how much memory you want Squid to use to keep objects in memory rather than writing them to disk. Squid’s total memory usage will exceed this! By default this is 8MB, so you might want to increase it if you have lots of RAM available.
- visible_hostname — hostname that will be shown in status/error messages
- cache_peer — If you want your Squid to go through another proxy server, rather than directly out to the Internet, you need to specify it here.
- login — Use this option if the parent proxy requires authentication.
- never_direct — Tells the cache to never go direct to the internet to retrieve a page. You will want this if you have set the option above.
- maximum_object_size — The largest size of a cached object. By default this is 4 MB, so if you have a lot of disk space you will want to increase the size of it to something reasonable.
- cache_dir — This is your cache directory, where all the cached files are stored. There are many options here, but the format should generally go like:
So, in the case of a school’s internet proxy:
If you change the cache directory from defaults, you must set the correct permissions on the cache directory before starting Squid, else it will not be able to create its cache directories and will fail to start.
Accessing services on local hostnames
If you plan to access web servers on the LAN using hostnames that are not fully-defined (e.g. http://mywebapp), you may need to enable the dns_defnames option. Without this option, Squid will make a DNS request for the hostname verbatim ( mywebapp ), which may fail, depending on your LAN’s DNS setup. With the option enabled, Squid will append any domain configured in /etc/resolv.conf when making the request (e.g. mywebapp.company.local ).
Starting
Once you have finished your configuration, you should check that your configuration file is correct:
Then create your cache directories:
Then you can start/enable squid.service .
Content Filtering
If you are looking for a content filtering solution to work with Squid, you should check out the very powerful DansGuardian.
Frontend
If you would like a web-based frontend for managing Squid, Webmin is your best bet.
Squid 4.x not supported in Webmin
If you receive an error indicating your version of webmin is unsupported:
you will need to modify the file /opt/webmin/squid/index.cgi (see issue #952)
Ad blocking with adzapper
Adzapper is a plugin for Squid. It catches ads of all sorts (even Flash animations) and replaces them with an image of your choice, so the layout of the page is not altered very much.
Installation
AdZapper is not presently in the official repositories or the AUR. The script itself, and detailed information on configuration and usage, can be found at http://adzapper.sourceforge.net.
Configuration
If you want, you can edit /etc/adzapper/adzapper.conf to configure adzapper to your liking. The configuration out of the box works wonderfully well though.
Transparent web proxy
Transparency happens by redirecting all www requests eth0 picks up, to Squid. You will need to add a port with an intercept (for squid 3.2) parameter. Note that at least one port must be available without the intercept parameter:
iptables
From a terminal with root privileges, run:
Then start the iptables.service systemd unit.
Replace SQUIDIP with the public IP(s) which squid may use for its listening port and outbound connections.
Shorewall
Edit /etc/shorewall/rules and add
Restart the shorewall systemd unit.
HTTP Authentication
Squid can be configured to require a user and password in order to use it. We will use digest http auth
First create a users file with htdigest -c /etc/squid/users MyRealm username . Enter a password when prompted.
Then add these lines to your squid.conf :
And restart squid. Now you will be prompted to enter a username and password when accessing the proxy.
You can add more users with htdigest /etc/squid/users MyRealm newuser . You probably would like to install Apache package, which contains htdigest tool.
Set up samba and winbindd and test it with
Grant r-x access to /var/cache/samba/winbindd_privileged/ directory for squid user/group
Then add something like this to squid.conf:
Hide Browser’s Real IP Address
SSL Bumping
Create Self-Signed Root CA Certificate
Create a DER-encoded certificate to import into users’ browsers
openssl x509 -in myCA.pem -outform DER -out myCA.der
The result file (myCA.der) should be imported into the ‘Authorities’ section of users’ browsers. For example, in FireFox:
Modify Squid Configuration File
Create and initialize TLS certificates cache directory
/usr/lib/squid/security_file_certgen -c -s /var/cache/squid/ssl_db -M 4MB
Источник
Ubuntu Documentation
Introduction
Squid is a Proxy server
This howto describes the process of setting up Squid as a Proxy Server
Squid is a proxy server, HTTP requests are sent to Squid instead of being sent directly to the internet. Note: in many of the examples below, you may need to change «squid» to «squid3». The squid.conf file for Squid 3.x is still named squid.conf, however for Squid 3.x, the path defaults to /etc/squid3/ instead of /etc/squid/.
Installation
Key File Locations
File
Purpose
/etc/squid3/squid.conf
Squid (3) configuration file
/var/log/squid3/access.log
Squid (3) access log file
/var/spool/squid3
Squid (3) cache_dir
Configurations
Squid Configuration
The squid.conf file is huge, with hundreds of options. In this howto we will only be changing a few settings.
Open the squid.conf file for editing
Turn on line numbers in gedit (Edit > Preferences)
Find the http_port tag (should be on or around line 53, its currently Line 89 in 7.10 release) By default it reads # http_port 3128 This is the default port that Squid will listen on for requests. If you want to change it, uncomment the line and set to the changed port. If you want Squid to listen only on one specific NIC (for a server with multiple NICs), you can also change the IP address – for example 192.168.1.5:3128
Now we’ll setup who is allowed access to the proxy. Find the http_access section (should start around line 1860,line 2589 in 7.04 and line 2608 in 7.10 release) Uncomment these 2 lines:
You’ll need to change 192.168.1.0/24 to match your network (like 192.168.0.0/24, or 10.0.0.0/8) Unless you have a second subnet you can delete 192.168.2.0/24
Above, the first four sets of numbers, separated by periods («.»), form the IP address of your local area network. The last number, after the slash («/»), is the netmask of your network and depends on your router settings. This is usually 24, meaning that the first three sets of numbers in the IP address only correspond to computers in your network while all others exist outside of it. Other netmasks are explained here.
if you get a startup error :- ‘FATAL: Could not determine fully qualified hostname. Please set visible_hostname’ you will also need to modify the visible_hostname tag (around line 2909 in 7.10) to:-
NOTE: this needs to be added as a new line in 7.10 (not sure about other releases) as there is no commented out line re-introduce.
Save the file and close gedit
Service Administration
If it is not running you can use (change «squid» to «squid3» if using a Squid 3.x version):-
then this will work
Squid caches the web pages it serves. If the cache expiration time of the web page is specified, Squid seems to obey it. If you are serving some of the pages, update your page in the Apache directory, Squid won’t fetch the new version, instead relying on its cached version until its default expiration time. To flush the Squid cache
Defining the Cache Space
At this point, Squid is running, but it is not actually caching. A google search of «squid not caching» will show that this is not an uncommon problem. The first reason for this is that the cache directory is not defined or built.
In /etc/squid3/squid.conf uncomment; (Note that this is for a 100 meg cache.)
A 1 gig cache would be;
Another problem is that not everything on the web has cache friendly expire tags, and the refresh patterns by default are somewhat conservative. Adding this line to /etc/squid3/squid.conf can help.
This will force squid to cache all the images listed above for at least and hour, and up to half a day.
After it has been running for a while you can see if it is cacheing with this command;
Customize Squid Error Pages
Squid can be customized. Learn how to do this here.
Источник
Установка и настройка Squid на Ubuntu
Данную инструкцию можно также применять для установки SQUID на Debian. В качестве клиентов могут использоваться Windows, Linux, Mac OS и любые браузеры.
Установка и базовая настройка
Устанавливаем прокси-сервер следующей командой:
apt-get install squid
Открываем на редактирование конфигурационный файл:
Если сеть клиентских компьютеров отличается от стандартной (192.168.0.0/16, 172.16.0.0/12, 10.0.0.0/8), необходимо ее добавить в acl, например:
# TAG: acl
.
acl localnet src 217.66.157.0/24
# TAG: acl
.
acl localnet src «/etc/squid/acl_localnet»
* кавычки обязательны
** после необходимо создать файл /etc/squid/acl_localnet и с каждой строчки перечислить разрешенные IP-адреса.
С точки зрения безопасности, лучше закомментировать все подсети, которые не используются в нашей локальной сети, например:
# TAG: acl
.
#acl localnet src 0.0.0.1-0.255.255.255
#acl localnet src 10.0.0.0/8
#acl localnet src 100.64.0.0/10
#acl localnet src 169.254.0.0/16
#acl localnet src 172.16.0.0/12
acl localnet src 192.168.0.0/16
#acl localnet src fc00::/7
#acl localnet src fe80::/10
* в данном примере мы оставили только подсеть 192.168.0.0/16.
Разрешаем доступ для локальных сетей, которые заданы опцией acl localnet:
# TAG: http_access
.
http_access allow localnet
* данную опцию нужно либо раскомментировать, либо вставить выше опции http_access deny all.
Настраиваем директорию для кэша:
# TAG: cache_dir
.
cache_dir ufs /var/spool/squid 4096 32 256
* где ufs — файловая система (ufs для SQUID является самой подходящей); /var/spool/squid — директория хранения кэша; 4096 — объем пространства в мегабайтах, которое будет выделено под кэш; 32 — количество каталогов первого уровня, которое будет создано для размещение кэша; 256 — количество каталогов второго уровня, которое будет создано для размещение кэша.
systemctl stop squid
Создаем структуру папок под кэш следующей командой:
Запускаем squid и разрешаем его автозапуск:
systemctl enable squid —now
Проверка
Заходим в настройки браузера и настраиваем использование прокси-сервера. Например, в Mozilla Firefox настройки нужно выставить такими:
* где 192.168.163.166 — IP-адрес моего прокси-сервера.
Теперь открываем сайт 2ip.ru. После его загрузки мы увидим внешний IP-адрес — он должен соответствовать той сети, от которой работает настроенный SQUID.
Прозрачный прокси
Прозрачный прокси позволяет автоматически использовать прокси-сервер, не настраивая при этом браузер компьютера. Пользователи могут даже не знать, что трафик идет через squid.
Открываем конфигурационный файл:
# TAG: http_port
.
http_port 3128
И приводим ее к следующему виду:
# TAG: http_port
.
http_port 3128 transparent
И перезапускаем конфигурацию squid:
squid -k reconfigure
Авторизация по логину и паролю
Открываем конфигурационный файл:
# TAG: auth_param
.
auth_param basic program /usr/lib/squid/basic_ncsa_auth /etc/squid/auth_users
auth_param basic children 25
auth_param basic realm SQUID PROXY
auth_param basic credentialsttl 3 hours
* где /usr/lib/squid/basic_ncsa_auth — расположение ncsa_auth (в зависимости от системы может находиться в другом каталоге); /etc/squid/auth_users — файл с логинами и паролями; children 25 разрешает 25 одновременных подключений; SQUID PROXY — произвольная фраза для приветствия; credentialsttl 3 hours будет держать сессию 3 часа, после потребуется повторный ввод логина и пароля.
Создаем acl для пользователей, которые прошли регистрацию. Сделаем регистрацию обязательной:
# TAG: acl
.
acl auth_users proxy_auth REQUIRED
http_access deny !Safe_ports
И после нее добавляем:
http_access allow auth_users
Устанавливаем утилиту apache2-utils:
apt-get install apache2-utils
Создаем файл с пользователями и создаем первую пару логина и пароля:
htpasswd -c /etc/squid/auth_users user1
Создаем второго пользователя:
htpasswd /etc/squid/auth_users user2
И перечитываем конфигурацию squid:
squid -k reconfigure
Слушаем на определенном интерфейсе
По умолчанию, squid будет слушать запросы на всех сетевых интерфейсах, которые доступны серверу. Чтобы указать конкретный, добавляем его IP к http_port:
# TAG: http_port
.
http_port 192.168.1.15:3128
* в данном примере squid будет слушать на адресе 192.168.1.15.
И перечитываем конфигурацию squid:
squid -k reconfigure
Исходящий сетевой интерфейс
На нашем сервере может быть несколько внешний IP-адресов. По умолчанию, все исходящие запросы будут работать через интерфейс со шлюзом по умолчанию. Чтобы иметь возможность работы со squid через разные интерфейсы в настройку вносим:
acl 217_66_157_33 localip 217.66.157.33
tcp_outgoing_address 217.66.157.33 217_66_157_33
acl 217_66_157_34 localip 217.66.157.34
tcp_outgoing_address 217.66.157.34 217_66_157_34
* в данном примере, при подключении к прокси через IP 217.66.157.33, исходящие пакеты будут от IP 217.66.157.33; аналогично для IP 217.66.157.34.
Перечитываем конфигурацию squid:
squid -k reconfigure
Настройка цепочки прокси-серверов
Мы можем передать запрос на другой прокси-сервер. Для этого открываем конфигурационный файл:
Настраиваем передачу запроса на другой прокси сервер:
# TAG: cache_peer
.
cache_peer 10.11.12.13 parent 3128 3128 proxy-only
* в данном примере мы передадим запрос на сервер 10.11.12.13. Синтаксис для cache_peer — cache_peer [options]:
- hostname — другой сервер, на который мы будем передавать запрос.
- type — тип «родства» другого сервера. Могут быть варианты:
- parent
- sibling
- multicast
- http-port — номер порта, на котором партнер принимает HTTP-запросы.
- icp-port — порт для запроса кэша.
- options — дополнительный опции.
* более подробное описание можно найти в самом конфигурационном файле SQUID.
Если на прокси, к которому мы подключаемся, необходима авторизация, добавляем опцию login:
cache_peer 10.11.12.13 parent 3128 3128 proxy-only login=loginname:password
Запрещаем использование нашего прокси-сервера напрямую (не через cache_peer):
# TAG: never_direct
.
never_direct allow all
Источник