Инструменты пользователя

Инструменты сайта


service:squid

Различия

Показаны различия между двумя версиями страницы.

Ссылка на это сравнение

Предыдущая версия справа и слеваПредыдущая версия
Следующая версия
Предыдущая версия
service:squid [22.03.2021 10:58] – [/etc/squid/squid.conf] viacheslavservice:squid [30.07.2024 19:21] (текущий) – внешнее изменение 127.0.0.1
Строка 1: Строка 1:
 +====== Squid ======
 +Задача: сделать прокси-сервер с прозрачной аутентификацией и авторизацией доменных пользователей через Kerberos. Если Kerberos недоступен, то basic-аутентификация и авторизация через LDAP. Точно такая же схема для веб-статистики. В результате доступ раздаётся через группы в AD.
 +
 +===== На контроллере домена =====
 +FIXME **- для LDAP учётки не надо, LDAP вообще надо выкинуть и забыть про него. По поводу пароля для учётки - неплохо бы генерировать случайный пароль прямо из ktpass.**
 +
 +Создаётся 2 учётки - одна для Kerberos, вторая для LDAP. Учётка Kerberos связана с сервером squid, поэтому удобнее называть её с включением имени сервера в имя учётки, например, sa_proxy. Учётка LDAP, например, будет sa_ldap - она должна быть максимально бесправной, имеет смысл создать группу в AD, например, LDAP-users, добавить эту учётку туда и сделать её основной группой для sa_ldap, а группу Domain Users убрать. Возможно, то же нужно сделать и для учётки Kerberos. В обеих учётках задаётся максимально длинный и сложный пароль, ставятся галки "пароль никогда не истекает" и "пользователь не имеет права менять пароль".
 +
 +Весьма рекомендуется включить LDAPS в домене, для большей безопасности.
 +
 +Керберос на сквиде работает через файл .keytab, который создаётся на контроллере домена.
 +<code powershell>
 +# Создать keytab-файл для работы с Kerberos
 +# Запросить пароль во время создания ключа, при вооде отображаться не будет
 +ktpass -princ HTTP/proxy.domain.ru@DOMAIN.RU -mapuser sa_proxy -crypto all -ptype KRB5_NT_PRINCIPAL -pass * -out C:\temp\proxy.keytab
 +# Посмотреть присвоенные SPN учётке sa_proxy
 +setspn -L sa_proxy
 +</code>
 +Параметр -pass может сам задавать пароль учётке, так как этот пароль нигде не вводится, это может быть полезным, не изучал вопрос.
 +
 +https://winitpro.ru/index.php/2020/07/13/sozdat-keytab-fajl-spn-kerberos-autentifikacya-ad/\\
 +https://www.altlinux.org/%D0%A1%D0%BE%D0%B7%D0%B4%D0%B0%D0%BD%D0%B8%D0%B5_SPN_%D0%B8_Keytab_%D1%84%D0%B0%D0%B9%D0%BB%D0%B0 
 +
 +Скопировать полученный файл на сервер Squid (WinSCP и т. п.). Этот файл критически важен, при малейшей компрометации необходимо пересоздавать его, менять пароли и т. п.
 +
 +==== Несколько SPN у одной учётки ====
 +FIXME** - плохая практика. SPN у учётки должен быть один.**
 +
 +С помощью setspn можно сделать несколько SPN у одной учётки, а потом объединить файлы .keytab, возможно, пригодится. Не тестировал.
 +
 +2nd command to add additional SPN to same keytab file with options **-mapOp add** and also you need to use **-in** and **-out** options.
 +
 +<color #ed1c24>When you use the ktpass.exe tool the account's userPrincipalName attribute changes to become as given by princ argument from the last invocation of ktpass command</color>
 +
 +Then the second SPN is added without updating kvno (using -in option the second SPN is added to the first one and the resulting keytab file contains both SPNs). The command also needs the previous option (-setpass) to avoid the increment of the kvno and the invalidation of the previous keytab. Basically using the command is executed using -setpass and -setupn, those options inform to not update the account password and the principal name respectively but the former has the collateral effect of not changing the kvno (the previous keytab is still valid)
 +
 +<color #ed1c24>If you create additional SPN to the same keytab for the host add -setpass -setupn for the above command to prevent resetting the password (thus changing kvno) and to prevent overwriting the UPN
 +</color>
 +
 +The password of the account for which the keytab file will be generated will be reset with the provided value. **Unless specified otherwise with the parameter -SetPass.**
 +
 +If the userPrincipalName of the account in Active Directory is different than the one specified in the command line, then it will be updated. **Unless you set the parameter -SetUPN.**
 +
 +https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/ktpass 
 +
 +<code powershell>
 +ktpass -princ HTTP/proxy2.domain.ru@DOMAIN.RU -mapuser sa_proxy -mapOp add -crypto all -ptype KRB5_NT_PRINCIPAL -pass * -in C:\temp\proxy.keytab -out C:\temp\proxy-all.keytab
 +</code>
 +[[https://www.ibm.com/mysupport/s/question/0D50z00005q4HNoCAM/how-do-you-add-multiple-spns-to-the-same-keytab-file-for-spnego-or-kerberos-configuration-in-was?language=en_US|How do you add multiple SPNs to the same keytab file]]
 +
 +===== На сервере squid =====
 +==== Примерная настройка сети ====
 +/etc/netplan/00-installer-config.yaml
 +<code bash>
 +network:
 +  ethernets:
 +    eth0:
 +      addresses:
 +      - 192.168.1.254/16
 +      nameservers:
 +        addresses:
 +        - 192.168.1.1
 +        - 192.168.1.2
 +        - 192.168.1.3
 +        search:
 +        - domain.ru
 +    eth1:
 +      addresses:
 +      - 10.1.0.254/24
 +      gateway4: 10.1.0.1
 +  version: 2
 +</code>
 +
 +==== Установка, первичная проверка ====
 +
 +<code bash>
 +apt install squid krb5-user libsasl2-modules-gssapi-mit ldap-utils
 +
 +# Права на keytab-файл
 +chown proxy:proxy /etc/proxy.keytab
 +chmod 440 /etc/proxy.keytab
 +
 +# Проверка Kerberos - получение билета
 +kinit -kV -p HTTP/proxy.domain.ru@DOMAIN.RU -t /etc/proxy.keytab
 +# Удалить билет
 +kdestroy
 +</code>
 +https://support.kaspersky.com/KWTS/6.1/en-US/166440.htm\\
 +https://www.altlinux.org/Squid/AD-auth
 +
 +==== Для использования NTLM совместно с Kerberos ====
 +<code bash>
 +# Install Samba and Winbind
 +apt install samba winbind samba-common-bin
 +# Stop the samba and winbind daemons
 +systemctl stop smb winbind
 +# edit /etc/samba/smb.conf
 +cp /etc/samba/smb.conf /etc/samba/smb.conf.old
 +nano /etc/samba/smb.conf
 +</code>
 +
 +<file /etc/samba/smb.conf>
 +[global]
 +workgroup = DOMAIN
 +security = ads
 +realm = DOMAIN.RU
 +
 +winbind uid = 10000-20000
 +winbind gid = 10000-20000
 +winbind use default domain = yes
 +winbind enum users = yes
 +winbind enum groups = yes
 +</file>
 +
 +<code>
 +# Now join the proxy to the domain.
 +net ads join -U Administrator
 +# Start samba and winbind and test acces to the domain.
 +wbinfo -t
 +
 +# This command should output something like this:
 +checking the trust secret for domain EXAMPLE via RPC calls succeeded
 +wbinfo -a EXAMPLE\\testuser%'password'
 +# Output should be similar to this.
 +plaintext password authentication succeeded
 +challenge/response password authentication succeeded
 +
 +# Set Permissions so the proxy user account can read /var/run/samba/winbindd_privileged
 +gpasswd -a proxy winbindd_priv
 +
 +# append the following to cron to regularly change the computer account password (Samba might do this automatically, check Samba documentation)
 +# change the computer account PROXY password in AD
 +5 4 * * *       root    net rpc changetrustpw -d 1 | logger -t changetrustpw
 +
 +</code>
 +https://wiki.squid-cache.org/ConfigExamples/Authenticate/WindowsActiveDirectory#ntlm
 +
 +В ''squid.conf'', вместо строки с ''negotiate_kerberos_auth'':
 +<file /etc/squid.conf>
 +auth_param negotiate program /usr/lib/squid/negotiate_wrapper_auth --ntlm /usr/bin/ntlm_auth --helper-protocol=squid-2.5-ntlmssp --domain=DOMAIN.RU --kerberos /usr/lib/squid/negotiate_kerberos_auth -s HTTP/proxy.domain.ru@DOMAIN.RU -t none
 +</file>
 +==== /etc/krb5.conf ====
 +
 +<code>
 +[libdefaults]
 +        default_realm = DOMAIN.RU
 +        default_keytab_name = /etc/proxy.keytab
 +
 +[realms]
 +        DOMAIN.RU = {
 +                kdc = vmws-dc1.domain.ru
 +                kdc = vmws-dc2.domain.ru
 +                kdc = ws-dc3.domain.ru
 +                admin_server = ws-dc3.domain.ru
 +                default_domain = domain.ru
 +        }
 +
 +[domain_realm]
 +        .domain.ru = DOMAIN.RU
 +        domain.ru = DOMAIN.RU
 +</code>
 +
 +==== /etc/squid/squid.conf ====
 +<code bash>
 +# Аутентификация Kerberos
 +# auth_param negotiate program /usr/lib/squid/negotiate_kerberos_auth -s HTTP/proxy.domain.ru@DOMAIN.RU -t none
 +auth_param negotiate program /usr/lib/squid/negotiate_wrapper_auth --ntlm /usr/bin/ntlm_auth --helper-protocol=squid-2.5-ntlmssp --domain=DOMAIN.RU --kerberos /usr/lib/squid/negotiate_kerberos_auth -s HTTP/proxy.domain.ru@DOMAIN.RU -t none
 +auth_param negotiate children 300 startup=50 idle=10
 +auth_param negotiate keep_alive on
 +
 +# Аутентификация Basic
 +auth_param basic program /usr/lib/squid/basic_ldap_auth -d -P -R -b "dc=domain,dc=ru" -D ldap@domain.ru -W "/etc/squid/sa_ldap_pass.txt" -f sAMAccountName=%s -h ws-dc3.domain.ru
 +auth_param basic children 20 startup=10 idle=5
 +auth_param basic realm proxy
 +# auth_param basic credentialsttl 9 hours
 +
 +# Авторизация по группам через Kerberos. Справка по хэлперу: /usr/lib/squid/ext_kerberos_ldap_group_acl -h
 +external_acl_type ext_anon_access grace=15 %LOGIN /usr/lib/squid/ext_kerberos_ldap_group_acl -g GRP-Inet-Anon -D DOMAIN.RU
 +external_acl_type ext_blocked_access grace=15 %LOGIN /usr/lib/squid/ext_kerberos_ldap_group_acl -g GRP-Inet-Blocked -D DOMAIN.RU
 +external_acl_type ext_restricted_access grace=15 %LOGIN /usr/lib/squid/ext_kerberos_ldap_group_acl -g GRP-Inet-Restricted -D DOMAIN.RU
 +external_acl_type ext_full_access grace=15 %LOGIN /usr/lib/squid/ext_kerberos_ldap_group_acl -g GRP-Inet-Full -D DOMAIN.RU
 +external_acl_type ext_standard_access grace=15 %LOGIN /usr/lib/squid/ext_kerberos_ldap_group_acl -g GRP-Inet-Standard -D DOMAIN.RU
 +external_acl_type ext_vk_access grace=15 %LOGIN /usr/lib/squid/ext_kerberos_ldap_group_acl -g GRP-Inet-VK -D DOMAIN.RU
 +
 +
 +################################################################
 +### acl (http://www.squid-cache.org/Versions/v4/cfgman/acl.html)
 +### https://wiki.squid-cache.org/SquidFaq/SquidAcl
 +################################################################
 +# Авторизованные пользователи
 +acl auth_users proxy_auth REQUIRED
 +# Списки доступа по группам
 +acl anon_access         external ext_anon_access        GRP-Inet-Anon
 +acl blocked_access      external ext_blocked_access     GRP-Inet-Blocked
 +acl restricted_access   external ext_restricted_access  GRP-Inet-Restricted
 +acl full_access         external ext_full_access        GRP-Inet-Full
 +acl standard_access     external ext_standard_access    GRP-Inet-Standard
 +# Без авторизации
 +acl unauth_access       src     "/etc/squid/unauth_access.txt"
 +# Доступ ко Вконтакте
 +acl vk_access           external ext_vk_access          GRP-Inet-VK
 +
 +### Сайты
 +# Заблокированные сайты, которые не пишутся в логи (например, телеметрия, засоряющая логи)
 +acl     nolog_blocked_sites     dstdomain "/etc/squid/nolog_blocked_sites.txt"
 +# Разрешённые сайты для restricted_access (кому запрещено всё остальное)
 +acl     allowed_sites           dstdomain "/etc/squid/allowed_sites.txt"
 +# Заблокированные сайты для стандартного доступа
 +acl     blocked_sites           dstdomain "/etc/squid/blocked_sites.txt"
 +# Сайты, куда можно всем без авторизации
 +acl     unrestricted_sites      dstdomain "/etc/squid/unrestricted_sites.txt"
 +# Нелогируемые сайты
 +acl     nolog_sites             dstdomain "/etc/squid/nolog_sites.txt"
 +# Некэшируемые сайты
 +acl     nocache_sites           dstdomain "/etc/squid/nocache_sites.txt"
 +# Сайты Вконтакте
 +acl     vk_sites                dstdomain .vk.com .vkontakte.ru
 +
 +### Локальные сети
 +acl     localnet        src     10.1.0.0/16
 +# Доступ к статистике
 +acl     stat_access src 10.1.22.0/24
 +
 +### Порты
 +acl     Safe_ports port 80 21 443 1025-65535
 +# 9443 - Сбербанк-бизнес, 2443 - МирБизнесБанк
 +acl     SSL_ports port 443 2443 9443
 +acl     CONNECT method CONNECT
 +
 +################################################################
 +### Правила (http://www.squid-cache.org/Versions/v4/cfgman/http_access.html)
 +################################################################
 +# Доступ к серверу только из локальных сетей
 +http_access allow localhost to_localhost
 +http_access deny !localnet to_localhost
 +#http_access allow SSL_Ports to_localhost
 +# Разрешить подключение к только к указанным портам (стандартная настройка)
 +http_access deny !Safe_ports
 +http_access deny CONNECT !SSL_ports
 +# Доступ к статистике (стандартная настройка), только подсети stat_access
 +# https://wiki.squid-cache.org/Features/CacheManager
 +http_access allow localhost manager
 +http_access allow stat_access manager
 +http_access deny manager
 +# Разрешить трафик с локалхоста
 +http_access allow localhost
 +# Запретить доступ к сайтам и не логировать их
 +http_access deny nolog_blocked_sites
 +# Не кэшировать nocache_sites
 +cache deny nocache_sites
 +# Разрешить доступ к определённым сайтам и серверам без авторизации
 +http_access allow nolog_sites
 +http_access allow unrestricted_sites
 +# IP (исходящие) с доступом без авторизации
 +http_access allow unauth_access
 +# Далее запрещаем весь неавторизованный доступ
 +http_access deny !auth_users
 +# Заблокированные пользователи
 +http_access deny blocked_access
 +# Доступ группе анонимусов и полный доступ
 +http_access allow anon_access
 +http_access allow full_access
 +# Ограниченный доступ - только к разрешённым сайтам
 +http_access allow restricted_access allowed_sites
 +# Доступ к Вконтакте
 +http_access allow vk_access vk_sites
 +# Стандартный доступ, исключая запрещённые сайты
 +http_access allow standard_access !blocked_sites
 +# Нижнее правило - блокировать всё, что не разрешено выше
 +http_access deny all
 +
 +################################################################
 +### Прочие настройки
 +################################################################
 +# http://www.squid-cache.org/Versions/v4/cfgman/http_port.html
 +http_port 3128
 +# http://www.squid-cache.org/Versions/v4/cfgman/access_log.html
 +access_log daemon:/var/log/squid/access.log squid !anon_access !nolog_sites !nolog_blocked_sites
 +# http://www.squid-cache.org/Versions/v4/cfgman/httpd_suppress_version_string.html
 +httpd_suppress_version_string on
 +# http://www.squid-cache.org/Versions/v4/cfgman/visible_hostname.html
 +visible_hostname proxy.domain.ru
 +# http://www.squid-cache.org/Versions/v4/cfgman/error_directory.html
 +error_directory /usr/share/squid/errors/ru
 +# http://www.squid-cache.org/Versions/v4/cfgman/error_default_language.html
 +error_default_language ru
 +# http://www.squid-cache.org/Versions/v4/cfgman/dns_v4_first.html
 +dns_v4_first on
 +# WARNING! Your cache is running out of filedescriptors
 +# https://aacable.wordpress.com/2012/03/22/squid-your-cache-is-running-out-of-filedescriptors-solution/
 +# https://erickoo.wordpress.com/2015/05/19/squid-warning-your-cache-is-running-out-of-filedescriptors/
 +# http://www.squid-cache.org/Versions/v4/cfgman/max_filedescriptors.html
 +max_filedescriptors 8192
 +# Limit connections from a single IP
 +# http://www.squid-cache.org/Doc/config/client_ip_max_connections/
 +client_ip_max_connections 150
 +### Anonymizing traffic
 +# http://www.squid-cache.org/Versions/v4/cfgman/forwarded_for.html
 +forwarded_for delete
 +via off
 +
 +##################
 +### Cache
 +##################
 +# http://www.squid-cache.org/Versions/v4/cfgman/cachemgr_passwd.html
 +# cachemgr_passwd P@ssw0rd all
 +cachemgr_passwd disable config offline_toggle shutdown
 +cache_mgr proxy@domain.ru
 +
 +# http://www.squid-cache.org/Versions/v4/cfgman/cache_mem.html
 +cache_mem 1 GB
 +# http://www.squid-cache.org/Versions/v4/cfgman/maximum_object_size_in_memory.html
 +maximum_object_size_in_memory 2 MB
 +# http://www.squid-cache.org/Versions/v4/cfgman/cache_dir.html
 +cache_dir ufs /var/cache/squid 15000 16 256
 +# http://www.squid-cache.org/Versions/v4/cfgman/maximum_object_size.html
 +maximum_object_size 100 MB
 +</code>
 +
 +Применение настроек Squid:
 +<code bash>
 +squid -k reconfigure
 +</code>
 +
 +http://www.squid-cache.org/Versions/v4/cfgman/\\
 +http://timp87.blogspot.com/2014/02/squid-ad.html\\
 +https://www.k-max.name/linux/avtorizaciya-autentifikaciya-squid/
 +
 +==== Кэш ====
 +<code bash>
 +# Создать каталоги под кэш
 +mkdir /var/cache/squid
 +chown proxy:proxy /var/cache/squid
 +squid -z
 +</code>
 +
 +==== WARNING! Your cache is running out of filedescriptors ====
 +Предупреждение в cache.log после подачи нагрузки на прокси (примерно 350 человек).
 +Решение:
 +<code bash>
 +# добавить строку в /etc/security/limits.conf
 +* – nofile 8192
 +# добавить в /etc/squid/squid.conf
 +max_filedescriptors 8192
 +# перечитать конфиг
 +squid -k reconfigure
 +</code>
 +https://aacable.wordpress.com/2012/03/22/squid-your-cache-is-running-out-of-filedescriptors-solution/\\
 +https://erickoo.wordpress.com/2015/05/19/squid-warning-your-cache-is-running-out-of-filedescriptors/\\
 +http://www.squid-cache.org/Versions/v4/cfgman/max_filedescriptors.html
 +
 +==== Высокая загрузка процессора при использовании auth_param negotiate ====
 +> Kerberos can keep a replay cache to detect the reuse of  Kerberos  tickets  (usually  only
 +> possible  in  a  5  minute  window) . If squid is under high load with Negotiate(Kerberos)
 +> proxy authentication requests the replay cache checks can create high  CPU  load.  If  the
 +> environment  does not require high security the replay cache check can be disabled for MIT
 +> based Kerberos implementations by adding the below to the startup script  or  use  the ''-t none'' option.
 +
 +<code>
 +auth_param negotiate program /usr/lib/squid/negotiate_kerberos_auth -s HTTP/proxy.domain.ru@DOMAIN.RU -t none
 +</code>
 +===== lightsquid =====
 +http://lightsquid.sourceforge.net/
 +
 +==== Установка ====
 +<code bash>
 +# Требования
 +apt install apache2 perl libcgi-session-perl libgd-perl #libapache2-mod-perl2
 +wget https://sourceforge.net/projects/lightsquid/files/lightsquid/1.8/lightsquid-1.8.tgz
 +mkdir /var/www/html/stat
 +tar xzf lightsquid-1.8.tgz --strip=1 -C /var/www/html/stat
 +chown -R www-data:www-data /var/www/html
 +
 +nano /etc/apache2/apache2.conf
 +<Directory "/var/www/html/stat">
 +   AddHandler cgi-script .cgi
 +   AllowOverride All
 +</Directory>
 +
 +nano /var/www/html/stat/lightsquid.cfg
 +</code>
 +http://lightsquid.sourceforge.net/Installs.html
 +
 +==== Файл преобразований имён ====
 +/var/www/html/stat/ip2name/ip2name.UsersAndHostNames
 +Ссылка на этот файл должна быть в конфиге lightsquid, чтобы корректно работало отображение имён и групп. Взял из интернета как есть, работает нормально.
 +<code bash>
 +#contributor: crux
 +#do nothing
 +#simple version
 +
 +use Socket;
 +
 +sub StartIp2Name() {
 +}
 +
 +sub Ip2Name($$$) {
 +  # $Lhost,$user,$Ltimestamp
 +  my ($ip, $user) = @_;
 +  return $user if $user ne "-";
 +  if (!defined $hIP{$ip}) {
 +
 +    my $iaddr = inet_aton($ip);
 +    my $user  = scalar gethostbyaddr($iaddr, AF_INET);
 +    $user =~ s/\..+$// if defined $user;
 +    $user = uc($user) if defined $user;
 +
 +    # if gethostbyaddr failed to get host, use ip
 +    $user = $ip unless defined $user;
 +
 +    $hIP{$ip}=$user;
 +  }
 +  return $hIP{$ip};
 +
 +}
 +
 +sub StopIp2Name() {
 +}
 +
 +#warning !!!
 +1;
 +
 +</code>
 +https://blog.it-kb.ru/2014/06/30/forward-proxy-squid-3-3-on-ubuntu-server-14-04-lts-part-9-lightsquid-reports-patched/
 +
 +==== Формирование списков пользователей и групп ====
 +/etc/squid/userslist.sh
 +
 +Идея в получении всей информации из AD и автоматическом формировании списков. Необходимо иметь номера подразделений в атрибуте departmentNumber, названия подразделений в атрибуте Department. В конце идёт перекодировка в CP1251, чтобы корректно отображалось на веб-странице.
 +<code bash>
 +#!/bin/bash
 +
 +realnamecfgUTF8="/var/www/html/stat/realname.cfg.utf8";
 +realnamecfg="/var/www/html/stat/realname.cfg";
 +groupcfgUTF8="/var/www/html/stat/group.cfg.utf8";
 +groupcfg="/var/www/html/stat/group.cfg";
 +rm -f $realnamecfgUTF8 $realnamecfg $groupcfgUTF8 $groupcfg && touch $realnamecfgUTF8 $realnamecfg $groupcfgUTF8 $groupcfg
 +
 +kinit HTTP/proxy.domain.ru -k
 +
 +for i in `ldapsearch -H ldap://vmws-dc1.domain.ru -b dc=domain,dc=ru -LLLQ -o ldif-wrap=no "(&(objectclass=person)(primaryGroupID=513)(!(samaccountname=*mailbox*))(!(UserAccountControl:1.2.840.113556.1.4.803:=2)))" sAMAccountName |grep 'sAMAccountName: ' |sed 's/sAMAccountName: //'`;
 +do
 +nameRaw=`ldapsearch -H ldap://vmws-dc1.domain.ru -b dc=domain,dc=ru -LLLQ -o ldif-wrap=no "(sAMAccountName=$i)" name |grep 'name:'`;
 +depRaw=`ldapsearch -H ldap://vmws-dc1.domain.ru -b dc=domain,dc=ru -LLLQ -o ldif-wrap=no "(sAMAccountName=$i)" department |grep 'department:'`;
 +depNum=`ldapsearch -H ldap://vmws-dc1.domain.ru -b dc=domain,dc=ru -LLLQ -o ldif-wrap=no "(sAMAccountName=$i)" departmentNumber |grep 'departmentNumber:' |sed "s/departmentNumber: //"`;
 +
 +if [[ $nameRaw =~ '::' ]]
 +then
 +name=`echo $nameRaw |sed "s/name:: //" |base64 -d`
 +else
 +name=`echo $nameRaw |sed "s/name: //"`
 +fi
 +
 +if [[ $depRaw =~ '::' ]]
 +then
 +dep=`echo $depRaw |sed "s/department:: //" |base64 -d`
 +else
 +dep=`echo $depRaw |sed "s/department: //"`
 +fi
 +
 +loginLow=`echo $i |tr "[:upper:]" "[:lower:]"`
 +if [[ $depNum =~ [0-9] ]]
 +then
 +login=`echo "$loginLow@domain.ru"`
 +echo -e "$login\t$depNum\t$dep" >> $groupcfgUTF8
 +else
 +login=`echo "$loginLow"`
 +fi
 +
 +
 +#echo -e "$loginRaw\t$nameRaw\t$depRaw"
 +#echo -e "$login\t$name\t$dep"
 +#echo -e "$login\t$name\t$depNum\t$dep"
 +
 +echo -e "$login\t$name" >> $realnamecfgUTF8
 +
 +done
 +
 +iconv -f utf-8 -t cp1251 -o $realnamecfg $realnamecfgUTF8
 +iconv -f utf-8 -t cp1251 -o $groupcfg $groupcfgUTF8
 +</code>
 +ldapsearch выдаёт результаты с двумя двоеточиями, это показывает, что значение неанглийское и его нужно декодировать из base64. Необходимо выключать перенос строк при получении данных из AD (-o ldif-wrap=no), чтобы всё корректно работало.
 +
 +https://www.opennet.ru/docs/RUS/ldap_apacheds/ch14/#ldapsearch\\
 +https://www.opennet.ru/docs/RUS/ldap_apacheds/apa/search.html\\
 +https://www.f-notes.info/linux:ldap_ad\\
 +
 +
 +==== /etc/crontab ====
 +<code bash>
 +# lightparser reads logs 3 times an hour
 +19,39,59 * * * *        root    /var/www/html/stat/lightparser.pl today
 +
 +# users and groups lists creation for lightparser
 +0 23 * * *      root    /etc/squid/userslist.sh
 +</code>
 +
 +===== Контроль доступа к Apache =====
 +В куче источников используют libapache2-mod-auth-kerb, но он [[https://bugzilla.altlinux.org/show_bug.cgi?id=39063|сильно устарел]]. Поэтому ставим [[https://github.com/gssapi/mod_auth_gssapi|gssapi]]
 +<code bash>
 +apt install libapache2-mod-auth-gssapi
 +# Для сертификата надо в качестве FQDN указывать "proxy" без домена,
 +# иначе Керберос не будет работать, если потом заходить на https://proxy.domain.ru/stat.
 +# Если заходить на https://proxy/stat, то работает. Почему - непонятно.
 +openssl req -x509 -sha256 -nodes -days 3650 -newkey rsa:4096 -keyout /etc/ssl/cert.key -out /etc/ssl/cert.crt
 +chmod 0600 /etc/ssl/cert.key
 +a2enmod ssl authnz_ldap
 +a2ensite  default-ssl.conf
 +</code>
 +
 +==== /etc/apache2/sites-available/000-default.conf ====
 +<code bash>
 +<VirtualHost *:80>
 +ServerAdmin webmaster@localhost
 +ServerName proxy
 +DocumentRoot /var/www/html
 +
 +Redirect / https://proxy/stat
 +
 +</VirtualHost>
 +</code>
 +
 +==== /etc/apache2/sites-available/default-ssl.conf ====
 +<code bash>
 +<IfModule mod_ssl.c>
 +  <VirtualHost _default_:443>
 +    ServerAdmin webmaster@localhost
 +    ServerName proxy
 +
 +    DocumentRoot /var/www/html
 +
 +    ErrorLog ${APACHE_LOG_DIR}/error.log
 +    CustomLog ${APACHE_LOG_DIR}/access.log combined
 +
 +    SSLEngine on
 +    SSLCertificateFile      /etc/ssl/cert.crt
 +    SSLCertificateKeyFile /etc/ssl/cert.key
 +#   SSLCertificateFile      /etc/ssl/domain/domain.crt
 +#   SSLCertificateChainFile /etc/ssl/domain/domain-int.crt
 +#   SSLCertificateKeyFile /etc/ssl/domain/domain.key
 +
 +# Set Forward Secrecy
 +    SSLProtocol -all +TLSv1.2 +TLSv1.3
 +    SSLHonorCipherOrder on
 +    SSLCipherSuite HIGH:!aNULL:!MD5:!3DES
 +# Strict transport security
 +    <IfModule mod_headers.c>
 +    Header always set Strict-Transport-Security "max-age=15768000; includeSubDomains"
 +    Header always set Referrer-Policy "no-referrer-when-downgrade"
 +    </IfModule>
 +# Stapling
 +    SSLUseStapling on
 +
 +# Default settings
 +<FilesMatch "\.(cgi|shtml|phtml|php)$">
 +  SSLOptions +StdEnvVars
 +</FilesMatch>
 +<Directory /usr/lib/cgi-bin>
 +  SSLOptions +StdEnvVars
 +</Directory>
 +
 +# Keytab можно не указывать, если он прописан в krb5.conf
 +# Если не сработает прозрачная, включится GssapiBasicAuth
 +<Location /stat>
 +AuthType GSSAPI
 +AuthName "Enter your login and password"
 +# GssapiCredStore keytab:/etc/proxy.keytab
 +GssapiBasicAuth On
 +AuthLDAPUrl ldap://vmws-dc1.domain.ru:389/dc=domain,dc=ru?userPrincipalName?sub
 +AuthLDAPBindDN CN=sa_ldap,OU=ServiceAccounts,DC=domain,DC=ru
 +AuthLDAPBindPassword VerySecurePasswordHere123456
 +Require ldap-group CN=GRP-Inet-Stat,OU=Internet,DC=domain,DC=ru
 +</Location>
 +
 +</VirtualHost>
 +SSLStaplingCache shmcb:/tmp/stapling_cache(128000)
 +</IfModule>
 +</code>
 +https://github.com/gssapi/mod_auth_gssapi\\
 +https://httpd.apache.org/docs/2.4/mod/mod_authnz_ldap.html\\
 +https://danieljamesscott.org/all-articles/10-articles/configuration-guides/9-apache-kerberos-and-ldap-integration.html
 +
 +===== Мониторинг =====
 +Штатная страница статуса - ''/cgi-bin/cachemgr.cgi'', можно зайти через браузер.\\
 +Может быть запрошена из командной строки
 +<code bash>
 +# Список страниц
 +squidclient mgr:menu
 +
 + index                  Cache Manager Interface                 public
 + menu                   Cache Manager Menu                      public
 + offline_toggle         Toggle offline_mode setting             disabled
 + shutdown               Shut Down the Squid Process             disabled
 + reconfigure            Reconfigure Squid                       hidden
 + rotate                 Rotate Squid Logs                       hidden
 + pconn                  Persistent Connection Utilization Histograms    public
 + mem                    Memory Utilization                      public
 + diskd                  DISKD Stats                             public
 + squidaio_counts        Async IO Function Counters              public
 + config                 Current Squid Configuration             disabled
 + client_list            Cache Client List                       public
 + comm_epoll_incoming    comm_incoming() stats                   public
 + ipcache                IP Cache Stats and Contents             public
 + fqdncache              FQDN Cache Stats and Contents           public
 + idns                   Internal DNS Statistics                 public
 + redirector             URL Redirector Stats                    public
 + store_id               StoreId helper Stats                    public
 + negotiateauthenticator Negotiate User Authenticator Stats      public
 + basicauthenticator     Basic User Authenticator Stats          public
 + external_acl           External ACL stats                      public
 + http_headers           HTTP Header Statistics                  public
 + info                   General Runtime Information             public
 + service_times          Service Times (Percentiles)             public
 + filedescriptors        Process Filedescriptor Allocation       public
 + objects                All Cache Objects                       public
 + vm_objects             In-Memory and In-Transit Objects        public
 + io                     Server-side network read() size histograms      public
 + counters               Traffic and Resource Counters           public
 + peer_select            Peer Selection Algorithms               public
 + digest_stats           Cache Digest and ICP blob               public
 + 5min                   5 Minute Average of Counters            public
 + 60min                  60 Minute Average of Counters           public
 + utilization            Cache Utilization                       public
 + histograms             Full Histogram Counts                   public
 + active_requests        Client-side Active Requests             public
 + username_cache         Active Cached Usernames                 public
 + openfd_objects         Objects with Swapout files open         public
 + store_digest           Store Digest                            public
 + store_log_tags         Histogram of store.log tags             public
 + storedir               Store Directory Stats                   public
 + store_io               Store IO Interface Stats                public
 + store_check_cachable_stats     storeCheckCachable() Stats              public
 + refresh                Refresh Algorithm Statistics            public
 + delay                  Delay Pool Levels                       public
 + forward                Request Forwarding Statistics           public
 + cbdata                 Callback Data Registry Contents         public
 + sbuf                   String-Buffer statistics                public
 + events                 Event Queue                             public
 + netdb                  Network Measurement Database            public
 + asndb                  AS Number Database                      public
 + carp                   CARP information                        public
 + userhash               peer userhash information               public
 + sourcehash             peer sourcehash information             public
 + server_list            Peer Cache Statistics                   public
 +
 +</code>
 +
 +<code bash>
 +# Используемые дескрипторы (Shell parameter expansion для обработки строки)
 +fd=`squidclient mgr:info |grep 'Number of file desc currently in use:'`&& echo ${fd/*: /}
 +</code>
 +===== Прочее =====
 +==== Проверка соединения с интернетом Windows ====
 +Называется Microsoft NCSI или Network Connectivity Status Indicator. Чтобы это работало через прокси, нужно добавить в список ресурсов, разрешённых для доступа без авторизации:
 +<code>
 +.msftconnecttest.com
 +.msftncsi.com
 +</code>
 +https://serverfault.com/a/300507
 +
 +==== Показать список пользователей в access.log ====
 +<code bash>
 +cat /var/log/squid/access.log |awk '{print $8}' |sort -u
 +</code>
 +
 +===== Ошибки =====
 +Типичные ошибки в логах:
 +
 +  * <color #ed1c24>krb5_get_init_creds_password() failed: Cannot contact any KDC for requested realm</color>: make sure that DC in /etc/krb5.conf kdc communicates on port 88: <code bash>telnet dc.company.cz 88</code>
 +  * <color #ed1c24>krb5_get_init_creds_password() failed: Client not found in Kerberos database</color>: the given user doesn't exist in AD (nothing wrong with configuration)
 +  * <color #ed1c24>krb5_get_init_creds_password() failed: Preauthentication failed</color>: the given user has different password.
 +  * <color #ed1c24>gss_accept_sec_context() failed: No credentials were supplied, or the credentials were unavailable or inaccessible (, Unknown error)</color>: the client doesn't trust the address of IdM, i.e. it isn't in Trusted sites in Internet Explorer.
 +  * <color #ed1c24>gss_accept_sec_context() failed: An unsupported mechanism was requested (, Unknown error)</color>: the client doesn't trust the address of IdM, i.e. it isn't in Trusted sites in Internet Explorer (probably)
 +  * <color #ed1c24>failed to verify krb5 credentials: Key table entry not found</color>: something is wrong with the keytab. Try to compare its version (KVNO) and the version of Kerberos ticket:<code>$ klist -k /etc/httpd/keytabs/idm.company.keytab 
 +Keytab name: FILE:/etc/httpd/keytabs/idm.company.keytab
 +KVNO Principal
 +---- --------------------------------------------------------------------------
 +   5 HTTP/idm.company@COMPANY.CZ
 +   5 HTTP/idm.company@COMPANY.CZ
 +   5 HTTP/idm.company@COMPANY.CZ
 +   5 HTTP/idm.company@COMPANY.CZ
 +   5 HTTP/idm.company@COMPANY.CZ
 +
 +$ kinit -k -t /etc/httpd/keytabs/idm.company.keytab HTTP/idm.company@COMPANY.CZ
 +$ kvno HTTP/idm.company@COMPANY.CZ
 +HTTP/idm.company@COMPANY.CZ: kvno = 5</code>
 +  * <color #ed1c24>krb5_rd_req() failed when verifying KDC</color> followed by <color #ed1c24>failed to verify krb5 credentials: Permission denied</color>: Bad permissions on the keytab file. All httpd processes must have read access to the keytab.
 +
 +[[https://wiki.czechidm.com/tutorial/adm/sso_ad_domain#troubleshooting|CzechIdM Identity Manager - Troubleshooting]]
 +
 +===== Литература =====
 +
 +[[https://wiki.squid-cache.org/ConfigExamples/Authenticate/WindowsActiveDirectory|Configuring a Squid Server to authenticate against Active Directory via Kerberos]]\\
 +[[https://serverfault.com/questions/793412/error-authenticating-squid-with-active-directory-and-kerberos|Error authenticating squid with Active Directory and Kerberos]]\\
 +[[https://docs.diladele.com/administrator_guide_stable/active_directory/index.html|Integration with Microsoft Active Directory]]\\
 +[[https://support.kaspersky.com/KWTS/6.1/en-US/166440.htm|Configuring the Squid service for Kerberos authentication]]
 +
  

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki