squid + active directory + dansguardian + sarg

Ceci est l’intégration rapide d’un serveur mandataire Squid 3 avec un environnement Active Directory. Le but de l’intégration est d’utiliser l’annuaire pour gérer les utilisateurs et les droits. Je ne me tarderai pas sur la partie AD.

La démarche est la suivante:

  • intégrer le serveur proxy sous debian gnu/linux au domaine M$
  • authentifier les utilisateurs contre les serveurs de domaine avec NTLM
  • installer Squid
  • configurer le serveur mandataire selon votre politique
  • filtrer avec Dansguardian et Clamav
  • générer les statistiques et suivre avec Sarg
  • configuration automatique des navigateurs

Dans les manipulations suivantes, il est déjà prévu que la partie configuration du serveur AD est déjà faite.
Le nom de domaine est company.local .
Le nom du contrôleur de domaine est winsrv et son adresse IP est 10.10.1.1 dans l’exemple .
Le serveur mandataire sera proxy.company.local

Utiliser comme serveur de nom du système le contrôleur de domaine en modifiant le fichier /etc/resolv.conf :

search company.local
nameserver 10.10.1.1

Modifier la ligne de /etc/hosts pour la compatibilité avec la config dans l’AD :

...
127.0.1.1	proxy proxy.company.local
...

Installer les paquets pour l’intégration dans l’AD :

aptitude install samba krb5-user libpam-krb5 winbind
 

Synchroniser l’heure du système avec le contrôleur de domaine ou un autre serveur NTP mais l’important c’est qu’ils ont à peu près la même heure.
Si vous utilisez un serveur ntp sur votre réseau :

aptitude install ntpdate
ntpdate -b -p 8 -u 10.10.1.1

Sinon le plus simple via sntp du serveur windows :

aptitude install rdate
rdate -n winsrv

Configurer Kerberos avec le fichier /etc/krb5.conf, je montre ici que les parties importantes :

[libdefaults]
        default_realm = COMPANY.LOCAL
        dns_lookup_realm = false
        ticket_lifetime = 3600
        krb4_config = /etc/krb.conf
        krb4_realms = /etc/krb.realms
        kdc_timesync = 1
        ccache_type = 4
        forwardable = true
        proxiable = true
        v4_instance_resolve = false
        v4_name_convert = {
                host = {
                        rcmd = host
                        ftp = ftp
                }
                plain = {
                        something = something-else
                }
         }
         fcc-mit-ticketflags = true

[realms]
        COMPANY.LOCAL = {
                             kdc = winsrv.company.local
        }

[domain_realm]
        .company.local = winsrv.company.local
        company.local = winsrv.company.local

[login]
        krb4_convert = true
        krb4_get_tickets = false

Tester la config Kerberos :

S’authentifier sur le controlleur avec un login déjà existant :

root@proxy:/etc# kinit mylogin
Password for mylogin@COMPANY.LOCAL:

Normalement, il n’y pas de message d’erreur, vérifier avec :

root@proxy:/etc# klist
Ticket cache: FILE:/tmp/krb5cc_0
Default principal: mylogin@COMPANY.LOCAL

Valid starting     Expires            Service principal
06/02/11 12:34:59  06/02/11 13:34:59  krbtgt/COMPANY.LOCAL@COMPANY.LOCAL

Configurer samba si tout se passe bien, le fichier de config principal est /etc/samba/smb.conf, je ne montre ici que la section ‘global’ :

[global]
   workgroup = COMPANY
   realm = COMPANY.LOCAL
   netbios name = PROXY
   server string = %h server
   dns proxy = no
   log file = /var/log/samba/log.%m
   max log size = 1000
   syslog = 0
   panic action = /usr/share/samba/panic-action %d
   security = ads
   password server = winsrv
   client use spnego = yes
   client ntlmv2 auth = yes
   encrypt passwords = true
   passdb backend = tdbsam
   obey pam restrictions = yes
   unix password sync = yes
   passwd program = /usr/bin/passwd %u
   passwd chat = *Enter\snew\s*\spassword:* %n\n *Retype\snew\s*\spassword:* %n\n *password\supdated\ssuccessfully* .
   pam password change = yes
   domain master = no
   idmap uid = 10000-20000
   idmap gid = 10000-20000
   winbind enum groups = yes
   winbind enum users = yes
   winbind use default domain = yes

Redémarrer les services avant de joindre la machine au domaine :

root@proxy:/etc/samba# invoke-rc.d samba restart
Stopping Samba daemons: nmbd smbd.
Starting Samba daemons: nmbd smbd.
root@proxy:/etc/samba# invoke-rc.d winbind restart
Stopping the Winbind daemon: winbind.
Starting the Winbind daemon: winbind.

Joindre le serveur au domaine :

root@proxy:~# net join -U Administrateur -S winsrv
Enter Administrateur's password:
Using short domain name -- COMPANY
Joined 'PROXY' to realm 'company.local'

Tester :

root@proxy:/etc/samba# wbinfo -t
checking the trust secret for domain COMPANY via RPC calls succeeded

Tester d’authentifier un utilisateur :

root@proxy:/etc/samba# /usr/bin/ntlm_auth --username=mylogin
password:
NT_STATUS_OK: Success (0x0)

Modifier le système à utiliser le domaine pour authentifier aussi un utilisateur en modifier le NSS (Name Service Switch) avec son fichier de config /etc/nsswitch.conf :

...
passwd:      compat winbind
group:         compat winbind
...

Installer et configurer Squid 3

aptitude install squid3

Ajouter l’utilisateur qui lance squid pour accéder au service winbind, il doit accéder au répertoire /var/run/samba/winbindd_privileged

usermod -a -G winbindd_priv proxy

Maintenant, il faut définir votre politique pour l’accés à l’Internet, dans mon cas :
– seuls les utilisateurs membres d’un groupe ‘GInternet’ dans l’AD y ont accès
– l’utilisateur ne peut se connecter qu’à partir d’un poste pour éviter le partage de mot de passe

Avec un grep -v « ^# » /etc/squid3/squid.conf | sed -e ‘/^$/d’ ça donne :

auth_param ntlm program /usr/bin/ntlm_auth --helper-protocol=squid-2.5-ntlmssp
auth_param ntlm children 50
auth_param ntlm keep_alive on
auth_param basic program /usr/bin/ntlm_auth --helper-protocol=squid-2.5-basic
auth_param basic children 50
auth_param basic realm COMPANY proxy-caching web server
auth_param basic credentialsttl 2 hours
authenticate_ttl 2 hours
authenticate_ip_ttl 2 hours
external_acl_type nt_group ttl=3600 %LOGIN /usr/lib/squid3/wbinfo_group.pl
acl manager proto cache_object
acl localhost src 127.0.0.1/32 ::1
acl mynetwork src 10.10.0.0/16
acl to_localhost dst 127.0.0.0/8 0.0.0.0/32 ::1
acl internet_group external nt_group ginternet
acl ntlm_users proxy_auth REQUIRED
acl uniq_user_ip max_user_ip -s 1
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
http_access allow manager localhost
http_access deny manager
http_access deny !Safe_ports
http_access deny CONNECT !SSL_ports
http_access deny uniq_user_ip
http_access deny !ntlm_users
http_access deny !internet_group
http_access allow localhost
http_access allow mynetwork
http_access deny all
http_port 3128
hierarchy_stoplist cgi-bin ?
maximum_object_size_in_memory 2048 KB
cache_dir aufs /cache1 30000 16 256
cache_dir aufs /cache2 30000 16 256
maximum_object_size 8192 KB
coredump_dir /var/spool/squid3
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
cache_mgr sysadmin@company.mg

Si vous voulez que l’utilisateur soit simplement authentifié, vous supprimez les lignes :

http_access deny uniq_user_ip
http_access deny !internet_group

N’oublier pas les lignes avec mynetwork dans la config, le port que vous voulez utiliser et les régles de firewall correspondantes .

Redémarrer Squid3 :

invoke-rc.d squid3 restart

Passons à l’intégration avec dansguardian :

C’est un peu pareil que mon post ici il y a 2 ans mais différent au niveau :
– antivirus qui n’utilise plus havp
– le repository volatile n’existe plus

Ajouter la ligne suivante dans votre /etc/apt/sources.list , changer le XX par le code de votre pays .

deb http://ftp.XX.debian.org/debian squeeze-updates main contrib non-free

Installer les paquets :

root@proxy:~# aptitude update
root@proxy:~# aptitude install dansguardian clamav clamav-freshclam clamav-base libclamav6

Mon /etc/dansguardian/dansguardian.conf

root@proxy:~# grep -v '^#' /etc/dansguardian/dansguardian.conf | sed -e '/^$/d'
reportinglevel = 3
languagedir = '/etc/dansguardian/languages'
language = 'french'
loglevel = 2
logexceptionhits = 2
logfileformat = 3
loglocation = '/var/log/dansguardian/access.log'
statlocation = '/var/log/dansguardian/stats'
filterip =
filterport = 8080
proxyip = 127.0.0.1
proxyport = 3128
accessdeniedaddress = 'http://YOURSERVER.YOURDOMAIN/cgi-bin/dansguardian.pl'
nonstandarddelimiter = on
usecustombannedimage = on
custombannedimagefile = '/usr/share/dansguardian/transparent1x1.gif'
filtergroups = 1
filtergroupslist = '/etc/dansguardian/lists/filtergroupslist'
bannediplist = '/etc/dansguardian/lists/bannediplist'
exceptioniplist = '/etc/dansguardian/lists/exceptioniplist'
showweightedfound = on
weightedphrasemode = 2
urlcachenumber = 1000
urlcacheage = 900
scancleancache = on
phrasefiltermode = 2
preservecase = 0
hexdecodecontent = off
forcequicksearch = off
reverseaddresslookups = off
reverseclientiplookups = off
logclienthostnames = off
createlistcachefiles = on
maxuploadsize = -1
maxcontentfiltersize = 256
maxcontentramcachescansize = 2000
maxcontentfilecachescansize = 20000
filecachedir = '/tmp'
deletedownloadedtempfiles = on
initialtrickledelay = 20
trickledelay = 10
downloadmanager = '/etc/dansguardian/downloadmanagers/fancy.conf'
downloadmanager = '/etc/dansguardian/downloadmanagers/default.conf'
contentscanner = '/etc/dansguardian/contentscanners/clamav.conf'
contentscannertimeout = 60
contentscanexceptions = off
authplugin = '/etc/dansguardian/authplugins/proxy-ntlm.conf'
recheckreplacedurls = off
forwardedfor = on
usexforwardedfor = off
logconnectionhandlingerrors = on
logchildprocesshandling = off
maxchildren = 180
minchildren = 32
minsparechildren = 8
preforkchildren = 10
maxsparechildren = 32
maxagechildren = 500
maxips = 0
ipcfilename = '/tmp/.dguardianipc'
urlipcfilename = '/tmp/.dguardianurlipc'
ipipcfilename = '/tmp/.dguardianipipc'
nodaemon = off
nologger = off
logadblocks = off
loguseragent = off
softrestart = off
mailer = '/usr/sbin/sendmail -t'

Mon /etc/dansguardian/dansguardianf1.conf

root@proxy:~# grep -v '^#' /etc/dansguardian/dansguardianf1.conf | sed -e '/^$/d'
groupmode = 1
bannedphraselist = '/etc/dansguardian/lists/bannedphraselist'
weightedphraselist = '/etc/dansguardian/lists/weightedphraselist'
exceptionphraselist = '/etc/dansguardian/lists/exceptionphraselist'
bannedsitelist = '/etc/dansguardian/lists/bannedsitelist'
greysitelist = '/etc/dansguardian/lists/greysitelist'
exceptionsitelist = '/etc/dansguardian/lists/exceptionsitelist'
bannedurllist = '/etc/dansguardian/lists/bannedurllist'
greyurllist = '/etc/dansguardian/lists/greyurllist'
exceptionurllist = '/etc/dansguardian/lists/exceptionurllist'
exceptionregexpurllist = '/etc/dansguardian/lists/exceptionregexpurllist'
bannedregexpurllist = '/etc/dansguardian/lists/bannedregexpurllist'
picsfile = '/etc/dansguardian/lists/pics'
contentregexplist = '/etc/dansguardian/lists/contentregexplist'
urlregexplist = '/etc/dansguardian/lists/urlregexplist'
blockdownloads = off
exceptionextensionlist = '/etc/dansguardian/lists/exceptionextensionlist'
exceptionmimetypelist = '/etc/dansguardian/lists/exceptionmimetypelist'
bannedextensionlist = '/etc/dansguardian/lists/bannedextensionlist'
bannedmimetypelist = '/etc/dansguardian/lists/bannedmimetypelist'
exceptionfilesitelist = '/etc/dansguardian/lists/exceptionfilesitelist'
exceptionfileurllist = '/etc/dansguardian/lists/exceptionfileurllist'
headerregexplist = '/etc/dansguardian/lists/headerregexplist'
bannedregexpheaderlist = '/etc/dansguardian/lists/bannedregexpheaderlist'
naughtynesslimit = 250
categorydisplaythreshold = 0
embeddedurlweight = 0
enablepics = off
bypass = 0
bypasskey = ''
infectionbypass = 0
infectionbypasskey = ''
infectionbypasserrorsonly = on
disablecontentscan = off
deepurlanalysis = off
usesmtp = on
mailfrom = 'dansguardian@company.mg'
avadmin = 'sysadmin@company.mg'
contentadmin = 'sysadmin@company.mg'
avsubject = 'dansguardian virus block'
contentsubject = 'dansguardian violation'
notifyav = off
notifycontent = off
thresholdbyuser = off
violations = 0
threshold = 0

Modifier votre /etc/squid3/squid.conf comme :

root@proxy:~# grep -v '^#' /etc/squid3/squid.conf | sed -e '/^$/d'
auth_param ntlm program /usr/bin/ntlm_auth --helper-protocol=squid-2.5-ntlmssp
auth_param ntlm children 50
auth_param ntlm keep_alive on
auth_param basic program /usr/bin/ntlm_auth --helper-protocol=squid-2.5-basic
auth_param basic children 50
auth_param basic realm COMPANY proxy-caching web server
auth_param basic credentialsttl 2 hours
authenticate_ttl 2 hours
authenticate_ip_ttl 2 hours
external_acl_type nt_group ttl=3600 %LOGIN /usr/lib/squid3/wbinfo_group.pl
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
acl internet_group external nt_group ginternet
acl ntlm_users proxy_auth REQUIRED
acl uniq_user_ip max_user_ip -s 1
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
http_access allow manager localhost
http_access deny manager
http_access deny !Safe_ports
http_access deny CONNECT !SSL_ports
http_access deny uniq_user_ip
http_access deny !ntlm_users
http_access deny !internet_group
http_access allow localhost
http_access deny all
http_port 127.0.0.1:3128
hierarchy_stoplist cgi-bin ?
maximum_object_size_in_memory 2048 KB
cache_dir aufs /cache1 30000 16 256
cache_dir aufs /cache2 30000 16 256
maximum_object_size 8192 KB
coredump_dir /var/spool/squid3
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
cache_mgr sysadmin@company.mg

Mettre à jour le blacklist de DG en téléchargeant depuis ce site http://urlblacklist.com/?sec=download

Installer un outil pour les statistiques comme Sarg :

aptitude install sarg apache2-mpm-prefork libapache2-mod-php5

Nous utilisons les fichiers de journal de DG car c’est plus intéressant, j’ai déjà mis au format squid (cf dansguardian.conf) ci-dessus.

Voici mon fichier de config de sarg /etc/sarg/sarg.conf

root@proxy:/etc/sarg# grep -v '^#' /etc/sarg/sarg.conf | sed -e '/^$/d'
access_log /var/log/dansguardian/access.log
graphs yes
graph_days_bytes_bar_color orange
graph_font /usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf
title "Squid User Access Reports"
font_face Tahoma,Verdana,Arial
header_color darkblue
header_bgcolor blanchedalmond
font_size 9px
background_color white
text_color #000000
text_bgcolor lavender
title_color green
temporary_dir /tmp
output_dir /var/lib/sarg
resolve_ip
user_ip no
topuser_sort_field BYTES reverse
user_sort_field BYTES reverse
exclude_users /etc/sarg/exclude_users
exclude_hosts /etc/sarg/exclude_hosts
date_format e
lastlog 0
remove_temp_files yes
index yes
index_tree file
overwrite_report yes
records_without_userid ip
use_comma yes
mail_utility mailx
topsites_num 100
topsites_sort_order CONNECT D
index_sort_order D
exclude_codes /etc/sarg/exclude_codes
max_elapsed 28800000
report_type topusers topsites sites_users users_sites date_time denied auth_failures site_user_time_date downloads
usertab /etc/sarg/usertab
long_url no
date_time_by bytes
charset Latin1
show_successful_message no
show_read_statistics no
topuser_fields NUM DATE_TIME USERID CONNECT BYTES %BYTES IN-CACHE-OUT USED_TIME MILISEC %TIME TOTAL AVERAGE
user_report_fields CONNECT BYTES %BYTES IN-CACHE-OUT USED_TIME MILISEC %TIME TOTAL AVERAGE
topuser_num 0
dansguardian_conf /etc/dansguardian/dansguardian.conf
show_sarg_info no
show_sarg_logo no
download_suffix "zip,arj,bzip,gz,ace,doc,iso,adt,bin,cab,com,dot,drv$,lha,lzh,mdb,mso,ppt,rtf,src,shs,sys,exe,dll,mp3,avi,mpg,mpeg"

 

root@proxy:/etc/sarg# grep -v '^#' /etc/sarg/sarg-reports.conf | sed -e '/^$/d'
       SARG=/usr/bin/sarg
     CONFIG=/etc/sarg/sarg.conf
    HTMLOUT=/var/lib/sarg
  PAGETITLE="Access Reports on $(hostname)"
    LOGOIMG=/sarg/images/sarg.png
   LOGOLINK="http://10.10.1.6/"
      DAILY=Daily
     WEEKLY=Weekly
    MONTHLY=Monthly
EXCLUDELOG1="SARG: No records found"
EXCLUDELOG2="SARG: End"

Pour l’affichage des stats, je genère chaque heure et je garde les traces d’un an :

rm /etc/cron.daily/sarg
rm /etc/cron.monthly/sarg
rm /etc/cron.weekly/sarg
cd /var/www
ln -s /var/lib/sarg sarg

J’ai créé un autre /etc/cron.hourly/sarg qui contient :

#!/bin/sh
if [ -x /usr/sbin/sarg-reports ]; then
  /usr/sbin/sarg-reports today
fi

J’ai modifié le logrotate de dansguardian /etc/logrotate.d/dansguardian

/var/log/dansguardian/access.log {
        rotate 12
        monthly
        compress
        delaycompress
        prerotate
                /etc/init.d/dansguardian stop > /dev/null 2>&1 || true
                /usr/sbin/sarg-reports weekly > /dev/null 2>&1 || true
                /usr/sbin/sarg-reports monthly > /dev/null 2>&1 || true
        endscript
        postrotate
                /etc/init.d/dansguardian start > /dev/null 2>&1
        endscript
}

Vous pouvez consulter les logs sur le site http://10.10.1.6/sarg/ vous pouvez restreindre l’accès via .htaccess si vous voulez .

Créer un script qui configure automatiquement les navigateurs pour vous et en cas de changement c’est plus facile vous aussi. Le script sera /var/www/proxy.pac et contient :

function FindProxyForURL(url, host)
{
    if (
       dnsDomainIs(host, ".company.local")
    || dnsDomainIs(host, "proxy.company.local")
    || (isInNet(host, "10.10.0.0", "255.255.0.0"))
    )
    {
       return "DIRECT";
     } else {
       return "PROXY 10.10.1.6:8080";
     }
}

Puis via GPO ou manuel, vous utiliserez le script de configuration automatique :
http://proxy.company.local/proxy.pac

Si vous avez des remarques ou des questions postez-les!

Vita tompoko!

13 réactions sur “squid + active directory + dansguardian + sarg

      • En fait je souhaite pouvoir gérer plusieurs groupent Active Directory.

    • re,

      Dans squid il y a ça http://wiki.squid-cache.org/SquidFaq/SquidAcl

      Donc tu crées pour chaque groupe une ligne :

      acl internet_group1 external nt_group groupe1
      acl internet_group2 external nt_group groupe2

      Puis :

      http_access deny !internet_group1 AND !internet_group2

      Je crois que ça marche avec ça mais il faut tester.

      A mon avis il est plus simple de gérer ça avec un seul groupe dans la config squid et on ajoute les groupes utilisateurs dans un groupe comme Ginternet ; )

      • Merci c’est ok pour les Groupe Acitive Directory.
        Maintenant je dois leurs mettre des droits différents.

        Groupe 1 les sites a.com et b.com
        Groupe 2 un surf sans risque avec les blacklists
        Groupe 3 Full Web

        Merci de ton aide.

  1. Bonjour,

    Le tuto fonctionne très bien un grand merci !

    Par contre quand la session n’est pas dans le domaine une boite de dialogue apparait pour ce connecté mon problème c’est que je ne trouve pas sous quel forme je dois renseigner le login.

    « User@domaine.lan » ne fonctionne pas

    Pouvez vous me dire sous quel forme vous entez le login ?

    Merci d’avance.

  2. Pingback: Bloquer le réseau Tor sur son proxy Squid | 'Gasy geek

  3. bonjour j’ai ce problème:  » utils/net_ads.c:1147(net_update_dns_internal net_update_dns_internal: Failed to connect to our DC!
    DNS update failed! « .. Pouvez vous m’aider svp.. Merçi 🙂

Répondre à hasina Annuler la réponse.