19
Implantação de Sistemas Linux Descrição: Estes procedimentos foram criados para facilitar a implantação de Firewall, Proxy, Relatórios de acessos e Monitor de link. A implantação desses sistemas é livre da cobrança de licencimanto, visto que os sistemas Linux são conhecidos pelas versões Freeware – OpenSource. Requisitos mínimos : Microcomputador com as seguintes característica: 1 GB DE RAM / HD 80GB / Processador 2.0 GHZ (Intel / AMD) CD de instalação Debian 6.0 Conhecimentos básicos de Linux Objetivo: Proteger a rede interna e ter total gerência sobre os recursos disponibilizados aos usuários Prover e gerenciar todos os acessos internos e externos e criar rotas para utilização de internet Gerar relatórios dos acessos feitos a internet Gerenciar o link de utilização de internet e rede interna Proxy Transparente: Squid Este recurso serve para o compartilhamento de internet na rede interna da empresa (rede local), ele faz o gerenciamento de velocidade e controle de acessos a internet, também provém a liberação de acessos e proibição por filtro de bloqueio / conteúdo, a sites indesejados. Exemplo: Pornografia Firewall : Iptables Este recurso serve para liberar e bloquear os acessos a internet, mapeando todas as portas de acesso a rede interna e internet, como já sabemos o firewall é uma barreira que ajuda na contenção de vírus, trojans, spam e afins ele é um dos principais responsáveis pela segurança da rede contra todas ameaças externas, mantendo a rede interna segura, é um item fundamental dentro de uma rede. Relatórios de acessos: Sarg Este recurso serve para proteger a empresa caso aja algum uso indesejado da rede para fins ilícitos como a prática de crimes virtuais. Ele grava tudo que é acessado e a máquina que acessou ou seja grava quem acessou, o que acessou, e o tempo de acesso, gerando ranking de sites mais acessados, entre outros. Monitor de tráfego de redes / Link (Internet): Mrtg Este recurso serve para monitorarmos os links de internet e também o tráfego de dados na rede interna, ajuda na verificação de gargalo de rede e link. Gragalo de rede e link é quando a placa de rede está trabalhando com muito trafego de dados isso pode causar lentidão na rede, com este monitor é possível evitarmos esse problema pois ele monitora full-time e podemos anteciparmos com ações preventivas evitando o gargalo de rede e link. Procedimentos de Implantação Instalando e configurando o Squid3: 17/07/2012 Página 1 Por: Tiago Rocha – [email protected]

Instalação e Configuração de Sistemas Linux

Embed Size (px)

Citation preview

Page 1: Instalação e Configuração de Sistemas Linux

Implantação de Sistemas Linux

Descrição: Estes procedimentos foram criados para facilitar a implantação de Firewall, Proxy, Relatórios de acessos e Monitor de link.A implantação desses sistemas é livre da cobrança de licencimanto, visto que os sistemas Linux são conhecidos pelas versões Freeware – OpenSource.

Requisitos mínimos :

Microcomputador com as seguintes característica: 1 GB DE RAM / HD 80GB / Processador 2.0 GHZ (Intel / AMD) CD de instalação Debian 6.0 Conhecimentos básicos de Linux

Objetivo: Proteger a rede interna e ter total gerência sobre os recursos disponibilizados aos usuários Prover e gerenciar todos os acessos internos e externos e criar rotas para utilização de internet Gerar relatórios dos acessos feitos a internet Gerenciar o link de utilização de internet e rede interna

Proxy Transparente: Squid

Este recurso serve para o compartilhamento de internet na rede interna da empresa (rede local), ele faz o gerenciamento de velocidade e controle de acessos a internet, também provém a liberação de acessos e proibição por filtro de bloqueio / conteúdo, a sites indesejados. Exemplo: Pornografia

Firewall : Iptables

Este recurso serve para liberar e bloquear os acessos a internet, mapeando todas as portas de acesso a rede interna e internet, como já sabemos o firewall é uma barreira que ajuda na contenção de vírus, trojans, spam e afins ele é um dos principais responsáveis pela segurança da rede contra todas ameaças externas, mantendo a rede interna segura, é um item fundamental dentro de uma rede.

Relatórios de acessos: Sarg

Este recurso serve para proteger a empresa caso aja algum uso indesejado da rede para fins ilícitos como a prática de crimes virtuais. Ele grava tudo que é acessado e a máquina que acessou ou seja grava quem acessou, o que acessou, e o tempo de acesso, gerando ranking de sites mais acessados, entre outros.

Monitor de tráfego de redes / Link (Internet): Mrtg

Este recurso serve para monitorarmos os links de internet e também o tráfego de dados na rede interna, ajuda na verificação de gargalo de rede e link. Gragalo de rede e link é quando a placa de rede está trabalhando com muito trafego de dados isso pode causar lentidão na rede, com este monitor é possível evitarmos esse problema pois ele monitora full-time e podemos anteciparmos com ações preventivas evitando o gargalo de rede e link.

Procedimentos de Implantação

Instalando e configurando o Squid3:

Executar os procedimentos como ROOT (superusuário) Atualizar o arquivo /etc/apt/source.list - repositórios:

deb http://ftp.br.debian.org/debian/ squeeze maindeb-src http://ftp.br.debian.org/debian/ squeeze maindeb http://security.debian.org/ squeeze/updates main deb-src http://security.debian.org/ squeeze/updates maindeb http://volatile.debian.org squeeze-updates maindeb-src http://volatile.debian.org squeeze-updates main

17/07/2012 Página 1Por: Tiago Rocha – [email protected]

Page 2: Instalação e Configuração de Sistemas Linux

# apt-get updateApós concluída a tarefa, vamos instalar o pacote Squid 3:

# apt-get install squid3Concluída esta tarefa, vamos a configuração do Squid.

O principal arquivo do Squid fica em /etc/squid3/squid.conf, onde vamos fazer o backup do mesmo e em seguida trabalhar suas configurações. Quando for abrir este arquivo, use seu editor de texto preferido, eu utilizo o pico, portanto substitua pelo que preferir.

Backup do squid.conf original:# cp -v /etc/squid3/squid.conf /etc/squid3/squid.conf.BACKUP

Apagar o arquivo original:# rm -v /etc/squid3/squid.conf

Criando nossa configuração em um novo squid.conf (use seu editor preferido):# pico /etc/squid3/squid.conf

Cole este script de configuração que criei, você deve modifica-lo de acordo com sua rede, e também adicionando novas regrasse assim preferir.

Arquivo squid.conf# Para se tornar transparente, basta adicionar ao lado da porta " transparent " #http_port 3128 # Se não colocar o tranparent, você deve configurar o navegador

#### Configuracoes do cache ####cache_mem 256 MB cache_swap_low 90cache_swap_high 95 maximum_object_size 4096 mbmaximum_object_size_in_memory 64 KB #### Logs de configuracao e acessos ######access_log /var/log/squid3/access.log squidcache_log /var/log/squid3/cache.logcache_store_log /var/log/squid3/store.logcache_dir ufs /var/log/spool/squid3 1000 32 256 mime_table /usr/share/squid3/mime.conf refresh_pattern ^ftp: 1440 20% 10080refresh_pattern ^gopher: 1440 0% 1440refresh_pattern (cgi-bin|\?) 0 0% 0refresh_pattern . 0 20% 4320quick_abort_max 16 KBquick_abort_pct 95quick_abort_min 16 KBrequest_header_max_size 20 KBreply_header_max_size 20 KBrequest_body_max_size 0 KB ### ACL - Controles de acesso - com as AS conseguimos definir grupos de acesso, black list, todo tipo de controle ##/ rede de acesso acl manager proto cache_objectacl localhost src 127.0.0.1/32acl to_localhost dst 127.0.0.0/8acl sluiz src 192.168.0.0/24 # Representa a sua rede e respectiva máscara de sub-rede###acl vlan1 src 172.18.28.0/24 # Se voce tiver mais de uma rede lan - wi-fi ou vlan deve ser adiciona

### ACLs de bloqueio de sites e acessos indevidos ### Se nao tiver os diretorios voce deve cria-los e adicionar um arquivo com os sites de bloqueioacl blacklist url_regex -i "/etc/squid3/regras/blacklist.txt"

#acl withlist url_regex -i "/etc/squid3/regras/withlist.txt"#http_access allow withlist

17/07/2012 Página 2Por: Tiago Rocha – [email protected]

Page 3: Instalação e Configuração de Sistemas Linux

### Limitar velocidade de Download ###delay_pools 2delay_class 1 1delay_class 2 2delay_parameters 1 512000/512000 # 4Mbpsdelay_parameters 2 512000/512000 6250/64000 # 4Mbps de agregado, 50K de banda com rajada de 64K.#acl semlimitedonwload src "/etc/squid3/regras/semlimitedonwload.txt" # colocar usuarios sem limitador#acl horas_livres time MTWQF 14:00-23:00 # colocar horario para liberacao fullacl limitados urlpath_regex .*\.mp3 .*\.avi .*\.zip .*\.exe .*\rar .*\msi#delay_access 1 allow semlimitedownload#delay_access 1 allow horas_livresdelay_access 1 deny limitadosdelay_access 1 allow alldelay_access 2 allow all

### Liberacao das port para acesso e navegacaoacl SSL_ports port 443 563acl Safe_ports port 80 # httpacl Safe_ports port 21 # ftpacl Safe_ports port 443 563 1863 # httpsacl Safe_ports port 70 # gopheracl Safe_ports port 210 # waisacl Safe_ports port 1025-65535 # unregistered portsacl Safe_ports port 280 # http-mgmtacl Safe_ports port 488 # gss-httpacl Safe_ports port 591 # filemakeracl Safe_ports port 777 # multiling httpacl CONNECT method CONNECT

cache_effective_user proxycache_effective_group proxy http_access deny blacklisthttp_access allow manager localhosthttp_access deny managerhttp_access deny !Safe_portshttp_access deny CONNECT !SSL_ports http_access allow sluiz#http_access allow vlan1 - outra rede

visible_hostname fwsl01

error_directory /usr/share/squid3/errors/Portuguese/ # Configurado - Tiago Rocha - [email protected] / [email protected] #

Criar um usuário "proxy", sendo que altere no squid.conf:# useradd proxy

Dê propriedade à pasta de log do Squid para o usuário que você criou, no Debian e outras distros fica em /var/log/squid3:# chown proxy.proxy /var/log/squid3/

Instalando e configurando o Iptables:

Agora vamos criar o arquivo /etc/init.d/firewall com seu editor de texto preferido:# pico /etc/init.d/firewall

Copie e cole o script abaixo dentro do arquivo criado:

#!bin/bash

echo 1 > /proc/sys/net/ipv4/ip_forward#iptables -Fiptables -Xiptables -t nat -Fiptables -t nat -Xiptables -t mangle -F

17/07/2012 Página 3Por: Tiago Rocha – [email protected]

Page 4: Instalação e Configuração de Sistemas Linux

iptables -t mangle -Xiptables -P INPUT DROPiptables -P FORWARD DROPiptables -P OUTPUT ACCEPTiptables -A INPUT -i lo -j ACCEPTiptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPTiptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT

# Proxy Transparenteiptables -t nat -A POSTROUTING -o eth1 -j MASQUERADEiptables -t nat -A PREROUTING -s 192.168.0.0/255.255.255.0 -p tcp --dport 80 -j REDIRECT --to-port 3128

# Limite contra ping da morte e DoSiptables -A INPUT -p icmp --icmp-type echo-request -m limit --limit 1/s -j ACCEPTiptables -A INPUT -p icmp --icmp-type echo-reply -m limit --limit 1/s -j DROP

# Exemplo de redirecionamento de porta, neste caso redirecionamento para Terminal Serveriptables -A FORWARD -p tcp --dport 3389 -d 187.93.80.18 -j ACCEPTiptables -t nat -A PREROUTING -i eth0 -p tcp --dport 3389 -j DNAT --to 192.168.0.102

# Liberando portas SSH a partir de qualquer interfaceiptables -A INPUT -p tcp --dport 4515 -j ACCEPT

#### Tiago Rocha - [email protected] / [email protected] ###

Adicione as seguintes linhas ao arquivo /etc/init.d/bootmisc.sh:# pico /etc/init.d/bootmisc.sh

if [ -x /etc/init.d/firewall ]; then    . /etc/init.d/firewallfi

Então salvamos e damos permissão para que o script IPTABLES seja executado pelo sistema:# chmod +x /etc/init.d/firewall

Adicione ao arquivo /etc/rc.local a seguinte linha:sh -e /etc/init.d/firewall

Salve o arquivo e dê as permissões:# chmod +x /etc/init.d/firewall

Dica: Para visualizar regras do IPTABLES, basta no terminal digitar:# iptables -L# iptables -t nat –L

Instalando e configurando o Sarg: Primeiro instalaremos o Apache.

# apt-get install apache2

Testaremos o Apache de qualquer máquina. Estando na mesma rede é só abrir o browser e digitar o IP da máquina na qual funcionará o Apache. Aparecerá a seguinte mensagem: "it works!". Sendo assim o seu Apache está funcionando perfeitamente. O Apache será necessário pois ele será o responsável por exibir os relatórios que o Sarg irá gerar. Agora instalaremos o Sarg:

# apt-get install sargO Sarg será instalado dentro de /etc/sarg - Iremos agora até o arquivo de configuração do Sarg, que é o sarg.conf.# cd /etc/sarg# pico sarg.confToda a configuração será feita no sarg.conf. A linha mais importante do Sarg é a que você indica o arquivo de log do Squid, que fica em /var/log/squid/access.log. O arquivo do Sarg deve ficar assim depois de descomentado: (copie e cole este script observe os caminhos /var/www/sarg)

# sarg.conf#

17/07/2012 Página 4Por: Tiago Rocha – [email protected]

Page 5: Instalação e Configuração de Sistemas Linux

# TAG: access_log file# Where is the access.log file# sarg -l file#access_log /var/log/squid3/access.log

# TAG: graphs yes|no# Use graphics where is possible.# graph_days_bytes_bar_color blue|green|yellow|orange|brown|red#graphs yesgraph_days_bytes_bar_color orange

# TAG: graph_font# The full path to the TTF font file to use to create the graphs. It is required# if graphs is set to yes.#graph_font /usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf

# TAG: title# Especify the title for html page.#title "Relatorio de acessos usuarios / sites"

# TAG: font_face# Especify the font for html page.#font_face Tahoma,Verdana,Arial

# TAG: header_color# Especify the header color#header_color darkblue

# TAG: header_bgcolor# Especify the header bgcolor#header_bgcolor blanchedalmond

# TAG: font_size# Especify the text font size#font_size 9px

# TAG: header_font_size# Especify the header font size##header_font_size 9px

# TAG: title_font_size# Especify the title font size##title_font_size 11px

# TAG: background_color# TAG: background_color# Html page background color#background_color white

# TAG: text_color# Html page text color#text_color #000000

# TAG: text_bgcolor# Html page text background color#text_bgcolor lavender

# TAG: title_color# Html page title color#

17/07/2012 Página 5Por: Tiago Rocha – [email protected]

Page 6: Instalação e Configuração de Sistemas Linux

title_color green

# TAG: logo_image# Html page logo.##logo_image none

# TAG: logo_text# Html page logo text.##logo_text ""

# TAG: logo_text_color# Html page logo texti color.##logo_text_color #000000

# TAG: logo_image_size# Html page logo image size. # width height##image_size 80 45

# TAG: background_image# Html page background image##background_image none

# TAG: password# User password file used by Squid authentication scheme# If used, generate reports just for that users.##password none

# TAG: temporary_dir# Temporary directory name for work files# sarg -w dir#temporary_dir /tmp

# TAG: output_dir# The reports will be saved in that directory# sarg -o dir#output_dir /var/www/sarg#output_dir /var/lib/sarg

# TAG: output_email# Email address to send the reports. If you use this tag, no html reports will be generated.# sarg -e email##output_email none

# TAG: resolve_ip yes/no# Convert ip address to dns name# sarg -nresolve_ip

# TAG: user_ip yes/no# Use Ip Address instead userid in reports.# sarg -puser_ip yes

# TAG: topuser_sort_field field normal/reverse# Sort field for the Topuser Report.# Allowed fields: USER CONNECT BYTES TIME#topuser_sort_field BYTES reverse

# TAG: user_sort_field field normal/reverse# Sort field for the User Report.# Allowed fields: SITE CONNECT BYTES TIME#

17/07/2012 Página 6Por: Tiago Rocha – [email protected]

Page 7: Instalação e Configuração de Sistemas Linux

user_sort_field BYTES reverse

# TAG: exclude_users file# users within the file will be excluded from reports.# you can use indexonly to have only index.html file.#exclude_users /etc/sarg/exclude_users

# TAG: exclude_hosts file# Hosts, domains or subnets will be excluded from reports.## Eg.: 192.168.10.10 - exclude ip address only# 192.168.10.0/24 - exclude full C class# s1.acme.foo - exclude hostname only# *.acme.foo - exclude full domain name#exclude_hosts /etc/sarg/exclude_hosts

# TAG: useragent_log file# useragent.log file patch to generate useragent report.##useragent_log none

# TAG: date_format# Date format in reports: e (European=dd/mm/yy), u (American=mm/dd/yy), w (Weekly=yy.ww)# date_format u

# TAG: per_user_limit file MB# Saves userid on file if download exceed n MB.# This option allow you to disable user access if user exceed a download limit.# #per_user_limit none

# TAG: lastlog n# How many reports files must be keept in reports directory.# The oldest report file will be automatically removed.# 0 - no limit.#lastlog 0

# TAG: remove_temp_files yes# Remove temporary files: geral, usuarios, top, periodo from root report directory.#remove_temp_files yes

# TAG: index yes|no|only# Generate the main index.html.# only - generate only the main index.html#index yes

# TAG: index_tree date|file# How to generate the index.#index_tree file

# TAG: overwrite_report yes|no# yes - if report date already exist then will be overwrited.# no - if report date already exist then will be renamed to filename.n, filename.n+1#overwrite_report yes

# TAG: records_without_userid ignore|ip|everybody# What can I do with records without user id (no authentication) in access.log file ?## ignore - This record will be ignored.# ip - Use ip address instead. (default)# everybody - Use "everybody" instead.#records_without_userid ip

# TAG: use_comma no|yes

17/07/2012 Página 7Por: Tiago Rocha – [email protected]

Page 8: Instalação e Configuração de Sistemas Linux

# Use comma instead point in reports.# Eg.: use_comma yes => 23,450,110# use_comma no => 23.450.110#use_comma yes

# TAG: mail_utility mail|mailx# Mail command to use to send reports via SMTP#mail_utility mailx

# TAG: topsites_num n# How many sites in topsites report.#topsites_num 100

# TAG: topsites_sort_order CONNECT|BYTES A|D# Sort for topsites report, where A=Ascendent, D=Descendent#topsites_sort_order CONNECT D

# TAG: index_sort_order A/D# Sort for index.html, where A=Ascendent, D=Descendent#index_sort_order D

# TAG: exclude_codes file# Ignore records with these codes. Eg.: NONE/400# Write one code per line. Lines starting with a # are ignored.# Only codes matching exactly one of the line is rejected. The# comparison is not case sensitive.#exclude_codes /etc/sarg/exclude_codes

# TAG: replace_index string# Replace "index.html" in the main index file with this string# If null "index.html" is used ##replace_index <?php echo str_replace(".", "_", $REMOTE_ADDR); echo ".html"; ?>

# TAG: max_elapsed milliseconds# If elapsed time is recorded in log is greater than max_elapsed use 0 for elapsed time.# Use 0 for no checking #max_elapsed 28800000# 8 Hours

# TAG: report_type type# What kind of reports to generate.# topusers - users, sites, times, bytes, connects, links to accessed sites, etc# topsites - site, connect and bytes report# sites_users - users and sites report# users_sites - accessed sites by the user report# date_time - bytes used per day and hour report# denied - denied sites with full URL report# auth_failures - autentication failures report# site_user_time_date - sites, dates, times and bytes report# downloads - downloads per user report## Eg.: report_type topsites denied ##report_type topusers topsites sites_users users_sites date_time denied auth_failures site_user_time_date downloadsreport_type topusers topsites sites_users users_sites date_time denied auth_failures site_user_time_date downloads

# TAG: usertab filename# You can change the "userid" or the "ip address" to be a real user name on the reports.# If resolve_ip is active, the ip address is resolved before being looked up into this# file. That is, if you want to map the ip address, be sure to set resolv_ip to no or# the resolved name will be looked into the file instead of the ip address. Note that# it can be used to resolve any ip address known to the dns and then map the unresolved# ip addresses to a name found in the usertab file.

17/07/2012 Página 8Por: Tiago Rocha – [email protected]

Page 9: Instalação e Configuração de Sistemas Linux

# Table syntax:# userid name or ip address name# Eg:# SirIsaac Isaac Newton# vinci Leonardo da Vinci# 192.168.10.1 Karol Wojtyla## Each line must be terminated with '\n'# If usertab have value "ldap" (case ignoring), user names# will be taken from LDAP server. This method as approaches for reception# of usernames from Active Didectory##usertab /etc/sarg/usertab

# TAG: LDAPHost hostname# FQDN or IP address of host with LDAP service or AD DC# default is '127.0.0.1'#LDAPHost 127.0.0.1

# TAG: LDAPPort port# LDAP service port number# default is '389'#LDAPPort 389

# TAG: LDAPBindDN CN=username,OU=group,DC=mydomain,DC=com# DN of LDAP user, who is authorized to read user's names from LDAP base# default is empty line#LDAPBindDN cn=proxy,dc=mydomain,dc=local

# TAG: LDAPBindPW secret# Password of DN, who is authorized to read user's names from LDAP base# default is empty line#LDAPBindPW secret

# TAG: LDAPBaseSearch OU=users,DC=mydomain,DC=com# LDAP search base# default is empty line#LDAPBaseSearch ou=users,dc=mydomain,dc=local

# TAG: LDAPFilterSearch uid=%s# User search filter by user's logins in LDAP# First founded record will be used# %s - will be changed to userlogins from access.log file# filter string can have some tags '%s'# default value is 'uid=%s'#LDAPFilterSearch uid=%s

# TAG: LDAPTargetAttr attributename# Name of the attribute containing a name of the user# default value is 'cn'#LDAPTargetAttr cn

# TAG: long_url yes|no# If yes, the full url is showed in report.# If no, only the site will be showed## YES option generate very big sort files and reports.#long_url no

# TAG: date_time_by bytes|elap# Date/Time reports show the downloaded volume or the elapsed time or both.#date_time_by bytes

# TAG: charset name# ISO 8859 is a full series of 10 standardized multilingual single-byte coded (8bit)# graphic character sets for writing in alphabetic languages# You can use the following charsets:# Latin1 - West European# Latin2 - East European # Latin3 - South European # Latin4 - North European

17/07/2012 Página 9Por: Tiago Rocha – [email protected]

Page 10: Instalação e Configuração de Sistemas Linux

# Cyrillic # Arabic # Greek # Hebrew # Latin5 - Turkish # Latin6# Windows-1251# Japan# Koi8-r# UTF-8#charset Latin1

# TAG: user_invalid_char "&/"# Records that contain invalid characters in userid will be ignored by Sarg.##user_invalid_char "&/"

# TAG: privacy yes|no# privacy_string "***.***.***.***"# privacy_string_color blue# In some countries the sysadm cannot see the visited sites by a restrictive law.# Using privacy yes the visited url will be changes by privacy_string and the link# will be removed from reports.##privacy no#privacy_string "***.***.***.***"#privacy_string_color blue

# TAG: include_users "user1:user2:...:usern"# Reports will be generated only for listed users.##include_users none

# TAG: exclude_string "string1:string2:...:stringn"# Records from access.log file that contain one of listed strings will be ignored.##exclude_string none

# TAG: show_successful_message yes|no# Shows "Successful report generated on dir" at end of process.#show_successful_message yes

# TAG: show_read_statistics yes|no# Shows some reading statistics.#show_read_statistics yes

# TAG: topuser_fields# Which fields must be in Topuser report.#topuser_fields NUM DATE_TIME USERID CONNECT BYTES %BYTES IN-CACHE-OUT USED_TIME MILISEC %TIME TOTAL AVERAGE

# TAG: user_report_fields# Which fields must be in User report.#user_report_fields CONNECT BYTES %BYTES IN-CACHE-OUT USED_TIME MILISEC %TIME TOTAL AVERAGE

# TAG: bytes_in_sites_users_report yes|no# Bytes field must be in Site & Users Report ?##bytes_in_sites_users_report no

# TAG: topuser_num n# How many users in topsites report. 0 = no limit#topuser_num 0

# TAG: datafile file# Save the report results in a file to populate some database#

17/07/2012 Página 10Por: Tiago Rocha – [email protected]

Page 11: Instalação e Configuração de Sistemas Linux

#datafile none

# TAG: datafile_delimiter ";"# ascii character to use as a field separator in datafile##datafile_delimiter ";"

# TAG: datafile_fields all# Which data fields must be in datafile# user;date;time;url;connect;bytes;in_cache;out_cache;elapsed##datafile_fields user;date;time;url;connect;bytes;in_cache;out_cache;elapsed

# TAG: datafile_url ip|name# Saves the URL as ip or name in datafile##datafile ip

# TAG: weekdays# The weekdays to take account ( Sunday->0, Saturday->6 )# Example:#weekdays 1-3,5# Default:#weekdays 0-6

# TAG: hours# The hours to take account# Example:#hours 7-12,14,16,18-20# Default:#hours 0-23

# TAG: dansguardian_conf file# DansGuardian.conf file path# Generate reports from DansGuardian logs.# Use 'none' to disable it.# dansguardian_conf /usr/dansguardian/dansguardian.conf##dansguardian_conf none

# TAG: dansguardian_filter_out_date on|off# This option replaces dansguardian_ignore_date whose name was not appropriate with respect to its action.# Note the change of parameter value compared with the old option.# 'off' use the record even if its date is outside of the range found in the input log file.# 'on' use the record only if its date is in the range found in the input log file.##dansguardian_filter_out_date on

# TAG: squidguard_conf file# path to squidGuard.conf file# Generate reports from SquidGuard logs.# Use 'none' to disable.# You can use sarg -L filename to use an alternate squidGuard log.# squidguard_conf /usr/local/squidGuard/squidGuard.conf##squidguard_conf none

# TAG: redirector_log file# the location of the web proxy redirector log such as one created by squidGuard or Rejik. The option# may be repeated up to 64 times to read multiple files.# If this option is specified, it takes precedence over squidguard_conf.# The command line option -L override this option.##redirector_log /usr/local/squidGuard/var/logs/urls.log

# TAG: redirector_filter_out_date on|off# This option replaces squidguard_ignore_date and redirector_ignore_date whose names were not# appropriate with respect to their action.# Note the change of parameter value compared with the old options.# 'off' use the record even if its date is outside of the range found in the input log file.# 'on' use the record only if its date is in the range found in the input log file.

17/07/2012 Página 11Por: Tiago Rocha – [email protected]

Page 12: Instalação e Configuração de Sistemas Linux

##redirector_filter_out_date on

# TAG: redirector_log_format# Format string for web proxy redirector logs.# This option was named squidguard_log_format before sarg 2.3.# REJIK #year#-#mon#-#day# #hour# #list#:#tmp# #ip# #user# #tmp#/#tmp#/#url#/#end## SQUIDGUARD #year#-#mon#-#day# #hour# #tmp#/#list#/#tmp#/#tmp#/#url#/#tmp# #ip#/#tmp# #user# #end##redirector_log_format #year#-#mon#-#day# #hour# #tmp#/#list#/#tmp#/#tmp#/#url#/#tmp# #ip#/#tmp# #user# #end#

# TAG: show_sarg_info yes|no# shows sarg information and site path on each report bottom##show_sarg_info yes

# TAG: show_sarg_logo yes|no# shows sarg logo##show_sarg_logo yes

# TAG: parsed_output_log directory# Saves the processed log in a sarg format after parsing the squid log file.# This is a way to dump all of the data structures out, after parsing from # the logs (presumably this data will be much smaller than the log files themselves),# and pull them back in for later processing and merging with data from previous logs.##parsed_output_log none

# TAG: parsed_output_log_compress /bin/gzip|/usr/bin/bzip2|nocompress# Command to run to compress sarg parsed output log. It may contain# options (such as -f to overwrite existing target file). The name of# the file to compresse is provided at the end of this# command line. Don't forget to quote things appropriately.##parsed_output_log_compress /bin/gzip

# TAG: displayed_values bytes|abbreviation# how the values will be displayed in reports.# eg. bytes - 209.526# abbreviation - 210K##displayed_values bytes

# Report limits# TAG: authfail_report_limit n# TAG: denied_report_limit n# TAG: siteusers_report_limit n# TAG: squidguard_report_limit n# TAG: user_report_limit n# TAG: dansguardian_report_limit n# TAG: download_report_limit n# report limits (lines).# '0' no limit##authfail_report_limit 10#denied_report_limit 10#siteusers_report_limit 0#squidguard_report_limit 10#dansguardian_report_limit 10#user_report_limit 10#user_report_limit 50

# TAG: www_document_root dir# Where is your Web DocumentRoot# Sarg will create sarg-php directory with some PHP modules:# - sarg-squidguard-block.php - add urls from user reports to squidGuard DB##www_document_root /var/www/html

# TAG: block_it module_url# This tag allow you to pass urls from user reports to a cgi or php module,# to be blocked by some Squid acl

17/07/2012 Página 12Por: Tiago Rocha – [email protected]

Page 13: Instalação e Configuração de Sistemas Linux

## Eg.: block_it /sarg-php/sarg-block-it.php# sarg-block-it is a php that will append a url to a flat file.# You must change /var/www/html/sarg-php/sarg-block-it to point to your file# in $filename variable, and chown to a httpd owner.## sarg will pass http://module_url?url=url##block_it none

# TAG: external_css_file path# Provide the path to an external css file to link into the HTML reports instead of# the inline css written by sarg when this option is not set.## In versions prior to 2.3, this used to be an absolute file name to# a file to include verbatim in each HTML page but, as it takes a lot of# space, version 2.3 switched to a link to an external css file.# Therefore, this option must contain the HTTP server path on which a client# browser may find the css file.## Sarg use theses style classes:# .logo logo class# .info sarg information class, align=center# .title_c title class, align=center# .header_c header class, align:center# .header_l header class, align:left# .header_r header class, align:right# .text text class, align:right# .data table text class, align:right# .data2 table text class, align:left# .data3 table text class, align:center# .link link class## Sarg can be instructed to output the internal css it inline# into the reports with this command:## sarg --css## You can redirect the output to a file of your choice and edit# it to your liking.##external_css_file none

# TAG: user_authentication yes|no# Allow user authentication in User Reports using .htaccess# Parameters: # AuthUserTemplateFile - The template to use to create the# .htaccess file. In the template, %u is replaced by the# user's ID for which the report is generated. The path of the# template is relative to the directory containing sarg# configuration file.## user_authentication no# AuthUserTemplateFile sarg_htaccess

# TAG: download_suffix "suffix,suffix,...,suffix"# file suffix to be considered as "download" in Download report.# Use 'none' to disable. #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"

# TAG: ulimit n# The maximum number of open file descriptors to avoid "Too many open files" error message.# You need to run sarg as root to use ulimit tag.# If you run sarg with a low privilege user, set to 'none' to disable ulimit##ulimit 20000

# TAG: ntlm_user_format username|domainname+username# NTLM users format.#

17/07/2012 Página 13Por: Tiago Rocha – [email protected]

Page 14: Instalação e Configuração de Sistemas Linux

#ntlm_user_format domainname+username

# TAG: realtime_refresh_time num sec# How many time to auto refresh the realtime report# 0 = disable## realtime_refresh_time 3

# TAG: realtime_access_log_lines num# How many last lines to get from access.log file ## realtime_access_log_lines 1000

# TAG: realtime_types: GET,PUT,CONNECT,ICP_QUERY,POST# Which records must be in realtime report.## realtime_types GET,PUT,CONNECT

# TAG: realtime_unauthenticated_records: ignore|show# What to do with unauthenticated records in realtime report.## realtime_unauthenticated_records: show

# TAG: byte_cost value no_cost_limit# Cost per byte.# Eg. byte_cost 0.01 100000000# per byte cost = 0.01# bytes with no cost = 100 Mb# 0 = disable## byte_cost 0.01 50000000

# TAG: squid24 on|off# Compatilibity with squid version <= 2.4 when using emulate_http_log on## squid24 off

Depois de editado reiniciaremos o nosso Squid com o seguinte comando:# /etc/init.d/squid stop# /etc/init.d/squid start

Para gerar o relatório de log de acesso e só dar o seguinte comando:# sarg

Ele mostrará a seguinte mensagem:

SARG: Gerou o relatório com sucesso em: /var/www/sarg/

De qualquer máquina na mesma rede você conseguirá visualizar os relatórios. É só chamar o IP da máquina que está rodando o Sarg e Squid “http://192.168.0.10/sarg“ é o caminho onde foi criado o relatório.

Instalando e configurando o Mrtg:

Para iniciarmos a instalação execute o seguinte comando:# apt-get install mrtg

Bem simples, o MRTG já está instalando e pronto para ser usado, mas precisamos definir algumas configurações nele, então vamos lá. Abaixo temos uma configuração que defini e que funciona perfeitamente, mas será preciso limpar seu arquivo de configuração atual, então vamos lá:

# echo > /etc/mrtg.cfg

Pronto, o arquivo foi limpo, agora vamos usar nosso editor para acrescentar as configurações nele.

17/07/2012 Página 14Por: Tiago Rocha – [email protected]

Page 15: Instalação e Configuração de Sistemas Linux

# pico /etc/mrtg.cfg

Copie e colo o script para dentro do arquivo#Configurando MRTGWorkDir: /var/www/mrtg/Htmldir: /var/www/mrtg/icondir: images/Refresh: 300Interval: 5Language: portugueseRunAsDaemon:Yes#---------------------# Monitorar eth1# REDE LOCAL#---------------------Target[eth1]: `cat /proc/net/dev |grep eth1 |awk -F':' '{print $2}' |awk '{print $1}'; cat /proc/net/dev |grep eth1 | awk -F':' '{print $2}' |awk '{print $9}'; echo -e; echo -e`MaxBytes[eth1]: 1250000Title[eth1]: eth1 - Utilização eth1PageTop[eth1]: <H1>Estatísticas das interfaces<BR>Utilização interface interna (eth1)</H1>Options[eth1]: growright

Crie o diretório de saída e dê as permissões necessárias:# mkdir /var/www/mrtg# chown proxy.proxy /var/www/mrtg

Feito isso, salve o arquivo e inicie o mrtg pela primeira vez:

# mrtgEle vai criar os logs pela primeira vez na pasta /var/www/mrtg/.Visto que estou contanto que todos já estejam com Apache instalado apontando para a referida pasta.

Agora chegou a hora mais esperada, vamos testá-lo. Para isso devemos digitar no browser:

http://ip_do_server/mrtg/

Agora que vem um pulinho do gato, se você prestar atenção, quando acessar a pasta pela primeira vez, ele vai listar os arquivos gerados, para que isso não aconteça, execute o comando:

# ln -s /var/www/mrtg/eth1.html /var/www/mrtg/index.html

OBS: Se eth0 for sua rede local substitua eth1 pela equivalente.

Podemos colocar ele para iniciar juntamente com o sistema, eu particularmente prefiro o rcconf, que é simples e eficiente. Então vamos lá:

# apt-get install rcconf

Feito isso teremos que criar um link para o mrtg na pasta /etc/init.d/ para que o rcconf posso identificá-lo, façamos:

# ln -sf /usr/bin/mrtg /etc/init.d/mrtg

Feito isso acessaremos o rcconf e marcaremos no menu a opção a qual o mrtg está, para que o mesmo inicie com o sistema.

Agradecimentos / Material de apoio: Agradeço a comunidade Linux que ajudou nas configurações e a mim mesmo pela iniciativa de criar um padrão de configuração e seus procedimentos com arquivos válidos para configuração. Material de apoio e dúvidas podem ser conseguidas no site: www.vivaolinux.com.br

17/07/2012 Página 15Por: Tiago Rocha – [email protected]