0

SQUID с авторизацией в AD

Встала передо мной задача установить и настроить прокси сервер с авторизацией пользователей в Windows Active Directory (AD). Задача довольно распространенная информации по этой теме столько, что все и не перечитать. Поэтому все опишу довольно кратко для себя, в качестве шаблона.

SAMBA

Первым делом ставлю samba сервер. Оттуда нужен, в принципе, только winbind, но samba в хозяйстве пригодится.
# cd /usr/ports/net/samba36 && make install clean
После установки samba пишу конфигурационный файл для kerberos.
В AD используется система билетов, которые выдаются доверяемым хостам, включенным в домен. Для реализации этого механизма и правлю /etc/krb5.conf:

[libdefaults]
    default_realm = DOMAIN.LC

[realms]
    DOMAIN.LC = {
        kdc = DOMAIN.LC
        admin_server = DOMAIN.LC
    }

[domain_realm]
    .domain.lc = DOMAIN.LC

[logging]
    kdc = FILE:/var/log/krb5kdc.log
    admin_server = FILE:/var/log/kadmin.log
    default = FILE:/var/log/krb5lib.log

Говорю, что для проверки пользователей и паролей надо использовать winbind. Добавляю в /etc/nsswitch.conf

group: files winbind
passwd: files winbind

Теперь правлю smb.conf

[global]

# workgroup = NT-Domain-Name or Workgroup-Name, eg: MIDEARTH
workgroup = DOMAIN.LC

# server string is the equivalent of the NT Description field
server string =

# Security mode. Defines in which mode Samba will operate. Possible
# values are share, user, server, domain and ads. Most people will want
# user level security. See the Samba-HOWTO-Collection for details.
security = ADS

# This option is important for security. It allows you to restrict
# connections to machines which are on your local network. The
# following example restricts access to two C class networks and
# the "loopback" interface. For more examples of the syntax see
# the smb.conf man page
hosts allow = 10.73. 127.

# If you want to automatically load your printer list rather
# than setting them up individually then you′ll need this
load printers = no

# this tells Samba to use a separate log file for each machine
# that connects
log file = /var/log/samba/log.%m

# Put a capping on the size of the log files (in Kb).
max log size = 50

# Use password server option only with security = server
# The argument list may include:
# password server = My_PDC_Name [My_BDC_Name] [My_Next_BDC_Name]
# or to auto-locate the domain controller/s
# password server = *
; password server = 
password server = DC.DOMAIN.LC

passdb backend = tdbsam

# Use the realm option only with security = ads
# Specifies the Active Directory realm the host is part of
realm = DOMAIN.LC

# Configure Samba to use multiple interfaces
# If you have multiple network interfaces then you must list them
# here. See the man page for details.
; interfaces = 192.168.12.2/24 192.168.13.2/24

# Browser Control Options:
# set local master to no if you don′t want Samba to become a master
# browser on your network. Otherwise the normal election rules apply
; local master = no

# OS Level determines the precedence of this server in master browser
# elections. The default value should be reasonable
; os level = 33

# Domain Master specifies Samba to be the Domain Master Browser. This
# allows Samba to collate browse lists between subnets. Don′t use this
# if you already have a Windows NT domain controller doing this job
; domain master = yes
domain master = no

# Preferred Master causes Samba to force a local browser election on startup
# and gives it a slightly higher chance of winning the election
; preferred master = yes
preffered master = no

# Enable this if you want Samba to be a domain logon server for
# Windows95 workstations.
; domain logons = yes
domain logons = no

# WINS Support - Tells the NMBD component of Samba to enable its WINS Server
; wins support = yes
wins support = no

display charset = koi8-r
unix charset = koi8-r
dos charset = 866

# DNS Proxy - tells Samba whether or not to try to resolve NetBIOS names
# via DNS nslookups. The default is NO.
dns proxy = no

idmap uid = 10000-20000
idmap gid = 10000-20000
winbind use default domain = yes

;[homes]
; comment = Home Directories
; browseable = no
; writable = yes

; BONUS
[all]
comment =
path = /shares/all
read list = "@DOMAIN\Пользователи домена"
write list = "@DOMAIN\Пользователи домена"
admin users = "@DOMAIN\Администраторы домена"
read only = no
map acl inherit = yes
map archive = no
map read only = no
create mask = 0660
directory mask = 0770
force unknown acl user = yes
delete readonly = yes

Для получения тикета кербероса выполняю:
# kinit egoad
где egoad — пользователь в домене. Теперь ввожу машину в домен:
# net join -U egoad
при этом egoad должен иметь права для ввода машин в домен (обычно администраторы домена).
Проверяю, получает ли winbind информацию о пользователях домена:
# id egoad

 uid=10000(egoad) gid=10004(пользователи домена) groups=10004(пользователи домена)

Создаю директорию для шар и задаю ей права:
# mkdir /shares && mkdir /shares/all && chown -R egoad:"Администраторы домена" /shares
Прописываю самбу в rc.conf и стартую ее:
# echo 'samba_enable="YES"' >> /etc/rc.conf
# /usr/local/etc/rc.d/samba start

Для тонкой настройки придется идти на samba.org или что нибудь близкое по наполнению =)

SQUID

Теперь перехожу непосредственно к Squid:
# cd /usr/ports && make search name=squid3
Port: squid-3.1.15_1
Path: /usr/ports/www/squid31
Info: HTTP Caching Proxy
Maint:
B-deps: perl-5.12.4_2
R-deps: perl-5.12.4_2
WWW: http://www.squid-cache.org/

Обязательно:
# chown root:squid /var/db/samba/winbindd_privileged
Теперь конфиг /usr/local/etc/squid/squid.conf:

auth_param ntlm program /usr/local/bin/ntlm_auth --helper-protocol=squid-2.5-ntlmssp
auth_param ntlm children 5
auth_param ntlm keep_alive on
authenticate_cache_garbage_interval 15 minute
authenticate_ttl 5 minute
auth_param basic program /usr/local/bin/ntlm_auth --helper-protocol=squid-2.5-basic
auth_param basic children 5
auth_param basic realm Squid Proxy-Server
auth_param basic credentialsttl 20 minute
auth_param basic casesensitive off

#acl USERS proxy_auth REQUIRED
external_acl_type nt_group %LOGIN /usr/local/libexec/squid/wbinfo_group.pl

#
# Recommended minimum configuration:
#
acl manager proto cache_object
acl localhost src 127.0.0.1/32 ::1
acl to_localhost dst 127.0.0.0/8 0.0.0.0/32 ::1

# Example rule allowing access from your local networks.
# Adapt to list your (internal) IP networks from where browsing
# should be allowed
acl localnet src 10.0.0.0/8 # RFC1918 possible internal network
acl localnet src 172.16.0.0/12 # RFC1918 possible internal network
acl localnet src 192.168.0.0/16 # RFC1918 possible internal network
acl localnet src fc00::/7 # RFC 4193 local private network range
acl localnet src fe80::/10 # RFC 4291 link-local (directly plugged) machines

acl SSL_ports port 443
acl Safe_ports port 80 # http
acl Safe_ports port 21 # ftp
acl Safe_ports port 443 # https
acl Safe_ports port 70 # gopher
acl Safe_ports port 210 # wais
acl Safe_ports port 1025-65535 # unregistered ports
acl Safe_ports port 280 # http-mgmt
acl Safe_ports port 488 # gss-http
acl Safe_ports port 591 # filemaker
acl Safe_ports port 777 # multiling http
acl CONNECT method CONNECT

# __ USERS ACL __/
acl inet_all external nt_group OIT

#
# Recommended minimum Access Permission configuration:
#
# Only allow cachemgr access from localhost
http_access allow manager localhost
http_access deny manager

# Deny requests to certain unsafe ports
http_access deny !Safe_ports

# Deny CONNECT to other than secure SSL ports
http_access deny CONNECT !SSL_ports

# We strongly recommend the following be uncommented to protect innocent
# web applications running on the proxy server who think the only
# one who can access services on "localhost" is a local user
http_access deny to_localhost
 
#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#

# Example rule allowing access from your local networks.
# Adapt localnet in the ACL section to list your (internal) IP networks
# from where browsing should be allowed
#http_access allow localnet
http_access allow localhost

# __ ACCESS TO INET __/
http_access allow inet_all

# And finally deny all other access to this proxy
http_access deny all

# Squid normally listens to port 3128
http_port 3128

# Uncomment and adjust the following to add a disk cache directory.
#cache_dir ufs /var/squid/cache 100 16 256

# Leave coredumps in the first cache dir
coredump_dir /var/squid/cache

# Add any of your own refresh_pattern entries above these.
refresh_pattern ^ftp: 1440 20% 10080
refresh_pattern ^gopher: 1440 0% 1440
refresh_pattern -i (/cgi-bin/|?) 0 0% 0
refresh_pattern . 0 20% 4320

Из всего описанного выше хочу выделить

auth_param ntlm program /usr/local/bin/ntlm_auth --helper-protocol=squid- 2.5-ntlmssp
auth_param ntlm children 5
auth_param ntlm keep_alive on
authenticate_cache_garbage_interval 15 minute
authenticate_ttl 5 minute
auth_param basic program /usr/local/bin/ntlm_auth --helper-protocol=squid-2.5-basic
auth_param basic children 5
auth_param basic realm Squid Proxy-Server
auth_param basic credentialsttl 20 minute
auth_param basic casesensitive off

Первые пять строк отвечают за прозрачную авторизацию, а вторые пять строк за авторизацию тех, кто так не умеет.
Далее внимание:

external_acl_type nt_group %LOGIN /usr/local/libexec/squid/wbinfo_group.pl

Скрипт проверяет группу пользователя в AD.
Далее AD группу OIT обзываю inet_all

acl inet_all external nt_group OIT

Прописываю доступ для inet_all

# __ ACCESS TO INET __/
http_access allow inet_all

Проверяю access.log squid:
# cat /var/log/squid/access.log
1318230036.779 0 10.73.116.160 TCP_DENIED/407 4381 GET http://ya.ru/ - NONE/- text/html
1318230036.795 0 10.73.116.160 TCP_DENIED/407 4650 GET http://ya.ru/ - NONE/- text/html
1318230036.925 115 10.73.116.160 TCP_MISS/200 7518 GET http://ya.ru/ egoad DIRECT/87.250.250.3 text/html

Сначала идет два отказа, затем успешное получение.
Судя по wiki SQUID такое положение дел есть норма…
Кроме того в том же wiki SQUID говорится:

Note that when using NTLM authentication,
you will see two "TCP_DENIED/407" entries in access.log for every request.
This is due to the challenge-response process of NTLM.

Ну дальше у меня остается тонкая настройка squid и более тонкая настройка прав доступа в инет.

P.S.
Кстати,samba ругалась на cups. Т.к. сервер печати мне пока не нужен, пересобрал ее без поддержки cups.

Alexey Egorychev

FreeBSD and Linux sysadmin. Know many systems like mailsystems, DB, WWW stack. Automation with salt, ansible. Monitoring with nagios, zabbix.