quarta-feira, 10 de outubro de 2012

Compartilhamento de Internet 0001

Primeira dica:

Se o seu modem for roteado e já realiza a conexão com a internet sozinho, use esse código dentro do arquivo /etc/rc.local: /etc. 

# Compartilha a conexão

modprobe iptable_nat
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A POSTROUTING -eth1 -j MASQUERADE # note que eth1 é qual placa de rede está conectada diretamente ao modem, se for a eth0 troque por eth0, se for eth1 deixe eth1, lembrando que isso é para quando seu modem é roteado (conecta sozinho).

# Abre para a rede local:
iptables -A INPUT -p tcp --syn -s 192.168.10.0/255.255.255.0 -j ACCEPT

# Fecha o resto da rede:
iptables -A INPUT -p tcp --syn -j DROP

exit 0 

Feito isso basta salvar o arquivo. Então você terá sua placa eth1 recebendo a internet do modem e liberando para a rede através da eth0.


Segunda dica:

Caso seu modem não seja roteado, siga um artigo de minha autoria que explica como fazer a configuração de um discador PPPoE e compartilhar a internet passo a passo.

    Configurar servidor PPPoE (Ubuntu)

ATENÇÃO: Nesse artigo a única diferença é que eu não uso eth1 para receber a internet do modem e liberar por eth0, e sim o inverso, eth0 para eth1 e na hora de adicionar os comandos que fazem o compartilhamento eu não coloco nem eth0 nem eth1 e sim ppp0.

Arquivo /etc/rc.local:

# Compartilha a Conexão

modprobe iptable_nat
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A POSTROUTING -ppp0 -j MASQUERADE # note que agora eu coloquei ppp0, pois minha conexão é feita via ppp0.

# Abre para a rede local:
iptables -A INPUT -p tcp --syn -s 192.168.10.0/255.255.255.0 -j ACCEPT

# Fecha o resto da rede:
iptables -A INPUT -p tcp --syn -j DROP

exit 0

Compartilhando Internet



Compartilhando Internet

Apos a instalação do Ubuntu Server 12.04, vamos configurar para ser um Gateway e um Servidor DHCP em uma pequena rede, onde neste Servidor temos 2 placas de rede: eth0 e eth1 
  • eth0 liga o modem ADSL
  • eth1 a rede interna

Já feita a instalação do Ubuntu, vamos atualizar o mesmo: 

$ sudo apt-get update
$ sudo apt-get upgrade
 

E instale o "Sysv-rc-conf": 

$ sudo apt-get install sysv-rc-conf 

Após a atualização, vamos colocar a mão na massa, vamos editar as interfaces de redes: 

$ sudo vim /etc/network/interfaces 

E deixar assim:

E deixar assim: auto lo
iface lo inet loopback

auto eth0
iface eth0 inet dhcp

auto eth1
iface eth1 inet static

address 172.16.1.254
netmask 255.255.0.0
network 172.16.0.0
broatcast 172.16.255.255


Neste caso, deixei como DHCP a 'eth0', mas se quiser, podes deixar ele fixo também; e minha rede interna fica com a faixa de IP 172.16.1.0.0

E após isso, vamos reiniciar a rede:

$ sudo /etc/init.d/networking restart

Ou:

$ sudo invoke-rc.d networking restart

Com a rede já pronta, agora vamos efetuar o compartilhamento da Internet.

Agora vamos habilitar o encaminhamento de IPv4.

Edite o arquivo:

$ sudo vim /etc/sysctl.conf

Descomentar a linha:

# net.ipv4.ip_forward=1


Onde fica assim:

net.ipv4.ip_forward=1


Vamos agora salvar o arquivo e executar o seguinte comando, para tornar a mudança efetiva sem um Reboot:

$ sudo sysctl -w net.ipv4.ip_forward=1

Agora vamos criar um Script para o compartilhamento. Crie no "/etc/init.d":

$ sudo vim /etc/init.d/internet

E adicione:

#!/bin/bash
 
iniciar(){
modprobe iptable_nat
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

iptables -A INPUT -p tcp --syn -s 172.16.50.0/255.255.0.0 - j ACCEPT

iptables -A INPUT -p tcp --syn  -j DROP
}

parar(){
iptables -F -t nat
}
 
case "$1" in
"start") iniciar ;;
"stop") parar ;;
"restart") parar; iniciar ;;
*) echo "Use os parâmetros start ou stop"
esac


Salve e saia do arquivo. E dê permissão de execução:

$ sudo chmod 777 /etc/init.d/internet 

$ sudo chmod +x /etc/init.d/internet

* Lembrando que a linha com o 'eth0', é a placa onde está ligado na ADSL.
** Se estiver ligado na 'eth1', só alterar para: eth1

Pronto. Para iniciar e parar o serviço da Internet, use os comandos abaixo:

- Para iniciar:

$ sudo invoke-rc.d internet start

Ou:

$ sudo /etc/init.d/internet start

- Para parar:

$ sudo invoke-rc.d internet stop

Ou:

$ sudo /etc/init.d/internet stop

E pronto, seu Servidor Gateway já está funcionando.

Use o "Sysv-rc-conf" para adicionar na inicialização do Servidor:

$ sudo sysv-rc-conf 




terça-feira, 9 de outubro de 2012

INSTALACAO SQUID / DANSGURDIAN


#################################################
###### Arquivo de Configuracao Squid 3.1.14 #####
#################################################




###############################################################
################ Autenticação no Windows 2008 #################
###############################################################




auth_param ntlm children 20 startup=0 idle=1 concurrency=10
auth_param ntlm program /usr/bin/ntlm_auth FALCOMERLAN/VM-DC --helper-protocol=squid-2.5-ntlmssp
auth_param ntlm keep_alive on

auth_param basic program /usr/bin/ntlm_auth FALCOMERLAN/VM-DC --helper-protocol=squid-2.5-basic
auth_param basic children 20 startup=0 idle=1 concurrency=10
auth_param basic realm Proxy Squid - Digite suas credenciais
auth_param basic credentialsttl 5 hours

# acl para obter autenticação do AD


acl acesso proxy_auth REQUIRED
#http_access allow acesso


#external_acl_type grupo_AD ttl=360 %LOGIN /usr/lib/squid3/wbinfo_group.pl
#acl acesso_padrao external grupo_AD Domain Users
#acl acesso_bloqueado external grupo_AD Internet_Acesso_Bloqueado




# Configuracoes de debug NTLM (caso necessário, o debug vai para /var/log/squid3/cache.log)
#debug_options 29,9

Para testar se a configuração está funcionando corretamento:

squid –k check

Por fim, reiniciamos o squid 3:

/etc/init.d/squid3 restart

3.3 – Configurando o Dansguardian

Dansguardian é um software analisador de conteúdo de uma página web, também classifica e faz bloqueio da mesma. Ele trabalha em conjunto com o squid fazendo um bloqueio prévio de páginas. Vamos começar com a instalação e a configuração do serviço:

apt-get install dansguardian

Após fazer a instalação do dansguardian, vamos configurar o dansguardian para que receba conexões na porta 3128, e depois repasse a página para o squid na porta 8080. Configure o arquivo /etc/dansguardian/dansguardian.conf:



# DansGuardian config file for version 2.10.1.1


# **NOTE** as of version 2.7.5 most of the list files are now in dansguardianf1.conf


# Language dir where languages are stored for internationalisation.
# The HTML template within this dir is only used when reportinglevel
# is set to 3. When used, DansGuardian will display the HTML file instead of
# using the perl cgi script.  This option is faster, cleaner
# and easier to customise the access denied page.
# The language file is used no matter what setting however.
#
languagedir = '/etc/dansguardian/languages'


# language to use from languagedir.
language = 'portuguese'




# Network Settings

# the IP that DansGuardian listens on.  If left blank DansGuardian will
# listen on all IPs.  That would include all NICs, loopback, modem, etc.
# Normally you would have your firewall protecting this, but if you want
# you can limit it to a certain IP. To bind to multiple interfaces,
# specify each IP on an individual filterip line.
filterip =


# the port that DansGuardian listens to.
filterport = 3128


# the ip of the proxy (default is the loopback - i.e. this server)
proxyip = 127.0.0.1


# the port DansGuardian connects to proxy on
proxyport = 8080




# Auth plugins
# These replace the usernameidmethod* options in previous versions. They
# handle the extraction of client usernames from various sources, such as
# Proxy-Authorisation headers and ident servers, enabling requests to be
# handled according to the settings of the user's filter group.
# Multiple plugins can be specified, and will be queried in order until one
# of them either finds a username or throws an error. For example, if Squid
# is configured with both NTLM and Basic auth enabled, and both the 'proxy-basic'
# and 'proxy-ntlm' auth plugins are enabled here, then clients which do not support
# NTLM can fall back to Basic without sacrificing access rights.
#
# If you do not use multiple filter groups, you need not specify this option.
#
authplugin = '/etc/dansguardian/authplugins/proxy-basic.conf'
#authplugin = '/etc/dansguardian/authplugins/proxy-digest.conf'


#habilita autenticação NTLM


authplugin = '/etc/dansguardian/authplugins/proxy-ntlm.conf'




#authplugin = '/etc/dansguardian/authplugins/ident.conf'
#authplugin = '/etc/dansguardian/authplugins/ip.conf'


OBS: Não apagar o arquivo de configuração. Deixei apenas as configurações necessárias para habilitar o NTLM e trocar a porta do serviço do dansguardian. O dansguardian possui uma gama enorme de possibilidades de configuração, vale dá uma lida na documentação.


E em seguida configure os arquivos com os bloqueios e liberações do dansguardian. Depois reinicie o dansguardian:

/etc/init.d/dansguardian restart


3.4 – Instalando e Configurando o Sarg


       Sarg provê muitas informacoes sobre as atividades dos usuários Squid, tais como: tempos, bytes trafegados, sites acessados, etc... o que permite total e completa administração de seus recursos.
Baixe o pacote da última versão do Sarg e o descompacte na pasta /usr/local/src/ e execute os seguintes comandos:
Primeiro vamos instalar o apache:

apt-get install apache

Agora a pasta que vamos publicar os reports do sarg:

mkdir /var/www/squid-reports

Agora vamos ao Sarg:


cd /usr/local/src/


wget http://ufpr.dl.sourceforge.net/project/sarg/sarg/sarg-2.3.1/sarg-2.3.1.tar.gz


tar -xzvf sarg-2.3.1.tar.gz


cd sarg-2.3.1


./configure 


make


make install

Agora vamos editar o arquivo de configuração do sarg, para que ele gere relatórios diários, mensais e semanais.

vim /usr/local/etc/sarg.conf

Adicionando essa configuração no arquivo:

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

#############################################################
### Formato de log para NTLM ################################
#############################################################
ntlm_user_format domainname+username

OBS: Devido ao tamanho do arquivo, deixei apenas a parte da configuração para o formato de log utilizar dominio e usuário do NTLM.

Para finalizar, edite o arquivo /usr/local/Bin/sarg-reports e troque o script dentro do binario pelo script abaixo.:


#!/bin1/bash
# SARG - Daily/Weekly/Monthly Squid usage reports creation tool
# Written by Ugo Viti <ugo.viti@initzero.it>


# ----------------------------------------------------------------------------
#
# Copyright (C) 2005 Ugo Viti
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# ----------------------------------------------------------------------------




# Thanks for enanchements to:
# - martijn
# - Stas Degteff https://sourceforge.net/users/stas_degteff/


VER=20050202


## What is this?
# sarg-reports (this file) is a simple bash script written to automate
# the SARG (a powerful squid log analyzer) reports and log management.
# Sarg it self, provide to end user a generic interface to create
# reports based on squid access log (begin of log to current date).
# sarg-reports (this script) is useful because it allow you to easly
# create and manage Daily, Weekly and Monthly reports.
# Try it, within 5 minutes you will be ready to rule :-)
# using sarg-reports is very easy, read the following 3 steps to know how


## Requirements
# a) An unix system with bash shell (like GNU/Linux, FreeBSD, etc...)
# b) Squid - http://www.squid-cache.org
# c) Sarg - http://web.onda.com.br/orso/sarg.html




##
## Installation guide and configuration parameters
##


# 1) Download Squid and Sarg, Install, Configure and Tune
#    they before continue reading


# 2) In root crontab (crontab -e) insert the following lines:
#    (the today report creation time depend mostly of your squid server
#    load average, tune it):
#
#    --- BEGIN ROOT CRONTAB ---
#    PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
#    00 08-18/1 * * * sarg-reports today
#    00 00      * * * sarg-reports daily
#    00 01      * * 1 sarg-reports weekly 
#    30 02      1 * * sarg-reports monthly
#    --- END ROOT CRONTAB ---
#
#    REMEMBER: if you use logrotate, configure it to rotate the logs within MONTHLY basis,
#              AFTER sarg-reports created the monthly html report.


# 3) Customize the following variables:
#    (Please, configure accurately the sarg.conf file before)
#
#        (SARG) The sarg executable location
#      (CONFIG) The sarg main configuration file location
#     (HTMLOUT) Location where will be saved the reports
#   (PAGETITLE) The title of main index page
#     (LOGOIMG) Image logo to view in main index page
#    (LOGOLINK) HTTP web page link of logo
#       (DAILY) Word 'daily' translation, translate it to your language
#      (WEEKLY) Word 'weekly' translation, translate it to your language
#     (MONTHLY) Word 'monthly' translation, translate it to your language
# (EXCLUDELOG1) Exclude text from cron emails
#       +       (normally, sarg, during cron activity, if it don't find any valid records,
# (EXCLUDELOG2) it will output an error message (usually on 'today' reports).
#               I don't want to be warned by email about this, so, i wrote the 'text'
#               that will be never logged.
#               This is useful to receive email of real problems only (enjoy that)


#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
## Portuguese Language
       SARG=/usr/local/bin/sarg
     CONFIG=/usr/local/etc//sarg.conf
    HTMLOUT=/var/www/squid-reports
  PAGETITLE="Squid User Access Reports $(hostname)"
    LOGOIMG=http://www.initzero.it/images/initzero-logo.jpg
   LOGOLINK=http://www.initzero.it
      DAILY=Diario
     WEEKLY=Semanal
    MONTHLY=Mensal
EXCLUDELOG1="SARG:Nenhum log encontrado."
EXCLUDELOG2="SARG: Finalizado"
#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@




#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
## Russian Language
#       SARG="/usr/bin/sarg"
#     CONFIG=/etc/sarg/sarg.conf
#    HTMLOUT=/var/www/sarg-reports
#  PAGETITLE="óÔÁÔÉÓÔÉËÁ ÓÅÒ×ÅÒÁ ÐÒÏËÓÉ Squid"   # russian koi8-r
#    LOGOIMG=http://litek.ru/images/logotop.gif
#   LOGOLINK=http://litek.ru
#      DAILY="åÖÅÄÎÅ×ÎÁÑ"     # russian koi8-r
#     WEEKLY="åÖÅÎÅÄÅÌØÎÁÑ"   # russian koi8-r
#    MONTHLY="åÖÅÍÅÓÑÞÎÁÑ"    # russian koi8-r
#EXCLUDELOG1="SARG: Records in file:"
#EXCLUDELOG2="SARG: ïÔÞÅÔ ÕÓÐÅÛÎÏ ÓÇÅÎÅÒÉÒÏ×ÁÎ ×" # sarg.conf: language Russian_koi8
#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@




######################################################################
## The configuration is end, so don't touch anything bellow


# TEMP Files
TMPFILE=/tmp/sarg-reports.$RANDOM
 ERRORS="${TMPFILE}.errors"


# Date Calc
MANUALDATE=$2
case "$(uname)" in
"FreeBSD")
         TODAY=$(date +%d/%m/%Y)
     YESTERDAY=$(date -v-1d +%d/%m/%Y)
       WEEKAGO=$(date -v-1w +%d/%m/%Y)
      MONTHAGO=$(date -v-1m +01/%m/%Y)-$(date -v-1m +31/%m/%Y)
   ;;
"OpenBSD")
         TODAY=$(date +%d/%m/%Y)
     YESTERDAY=$(date -r $((`date +%s` - 86400 )) +%d/%m/%Y)
       WEEKAGO=$(date -r $((`date +%s` - 604800)) +%d/%m/%Y)
      MONTHAGO=$(perl -e '@t=localtime(time); $y=$t[4]==0?$t[5]+1899:$t[5]+1900; $m=$t[4]==0?12:$t[4]; print "1/$m/$y-",$m==2?$y%4>0?28:29:$m==4||$m==6||$m==9||$m==11?30:31 ,"/$m/$y\n";')
   ;;
*)
         TODAY=$(date --date "today" +%d/%m/%Y)
     YESTERDAY=$(date --date "1 day ago" +%d/%m/%Y)
       WEEKAGO=$(date --date "1 week ago" +%d/%m/%Y)
      MONTHAGO=$(date --date "1 month ago" +01/%m/%Y)-$(date --date "1 month ago" +31/%m/%Y)
   ;;
esac


# Fix for Red Hat 9 systems and coreutils prior to 5.0 version
export LC_ALL=C


# Main index.html creation
create_index_html ()
{
  echo -e "\
  <html>\n\
  <head>\n\
  <title>$PAGETITLE</title>\n\
  </head>\n\
  <body>\n\
  <div align=center>\n\
    <a href=$LOGOLINK><img border=0 src=$LOGOIMG></a>\n\
    <table border=0 cellspacing=6 cellpadding=7>\n\
      <tr>\n\
        <th align=center nowrap><b><font face=Arial size=4 color=green>$PAGETITLE</font></b></th>\n\
      </tr>\n\
      <tr>\n\
        <td align=center bgcolor=beige><font face=Arial size=3><a href=$DAILY>$DAILY</a></font></td>\n\
      </tr>\n\
      <tr>\n\
        <td align=center bgcolor=beige><font face=Arial size=3><a href=$WEEKLY>$WEEKLY</a></font></td>\n\
      </tr>\n\
      <tr>\n\
        <td align=center bgcolor=beige><font face=Arial size=3><a href=$MONTHLY>$MONTHLY</a></font></td>\n\
      </tr>\n\
    </table>\n\
  </div>\n\
  </body>\n\
  </html>" > $HTMLOUT/index.html
}




# Functions
exclude_from_log ()
{
  cat $ERRORS | grep -v "$EXCLUDELOG1" | grep -v "$EXCLUDELOG2"
  rm -f $TMPFILE*
}


manual ()
{
  DAILYOUT=$HTMLOUT/$DAILY
  mkdir -p $DAILYOUT
  create_index_html
  if [ -z "$MANUALDATE" ]
    then
      echo "No date given, please specify a valid date (DD/MM/YYYY)"
    else
      $SARG -f $CONFIG -d $MANUALDATE -o $DAILYOUT
  fi
}


today ()
{
  DAILYOUT=$HTMLOUT/$DAILY
  mkdir -p $DAILYOUT
  create_index_html
  $SARG -f $CONFIG -d $TODAY -o $DAILYOUT >$ERRORS 2>&1
  exclude_from_log
}


daily ()
{
  DAILYOUT=$HTMLOUT/$DAILY
  mkdir -p $DAILYOUT
  create_index_html
  $SARG -f $CONFIG -d $YESTERDAY -o $DAILYOUT >$ERRORS 2>&1
  exclude_from_log
}


weekly ()
{
  WEEKLYOUT=$HTMLOUT/$WEEKLY
  mkdir -p $WEEKLYOUT
  create_index_html
  $SARG -f $CONFIG -d $WEEKAGO-$YESTERDAY -o $WEEKLYOUT >$ERRORS 2>&1
  exclude_from_log
}


monthly ()
{
  MONTHLYOUT=$HTMLOUT/$MONTHLY
  mkdir -p $MONTHLYOUT
  create_index_html
  $SARG -f $CONFIG -d $MONTHAGO -o $MONTHLYOUT >$ERRORS 2>&1
  exclude_from_log
}


case $1 in
    manual)
        manual
        ;;
    today)
        today
        ;;
    daily)
        daily
        ;;
    weekly)
        weekly
        ;;
    monthly)
        monthly
        ;;
     *)
        echo "SARG - Daily / Weekly / Monthly - Squid proxy usage reports creation tool"
        echo "Written by Ugo Viti <ugo.viti@initzero.it>"
        echo "Version: $VER"
        echo
        echo "Usage: $0 [OPTIONS]"
        echo
        echo "Allowed options:"
        echo "    manual,  Create Manual report"
        echo "     today,  Create Today report"
        echo "     daily,  Create Daily report"
        echo "    weekly,  Create Weekly report"
        echo "    monthly,  Create Monthly report"
        exit 0
esac




## HISTORY:
# 20050502 - Stas Degteff added support for non latin Charset and added support for OpenBSD
# 20030826 - FreeBSD support (thanks to martijn to let me coding on your FreeBSD server :-))
# 20030715 - Some cleanups
# 20030623 - Manual report creation
# 20030620 - Main Index creation
# 20030619 - Solved 'sort' bug on Red Hat 9 systems
# 20030618 - First Version




## TODO:
# - Smarty weekly recognition...
#   Like "begin of last week to end of last week",
#   doesn't like this script do: "7 days ago to yesterday"
# - Monthly recognition isn't so elegant (is very ugly, i know)
# - Suggestions are welcome :-)
# - If you Rotate the squid logs before sarg-reports will run,
#   it will not create any html reports 
#   (TIPS: Rotate the logs after sarg-reports)



Vamos adicionar as linhas no arquivo /etc/crontab para que seja criado os reports automaticamente:


# SARG
00 20 * * * root /usr/local/bin/sarg-reports today
01 00    * * * root /usr/local/bin/sarg-reports daily
00 01    * * 1 root /usr/local/bin/sarg-reports weekly 
30 02    1 * * root /usr/local/bin/sarg-reports monthly

SQUID NO UBUNTU

 

Instalando e configurando o Squid 3

Bem, antes de tudo vamos fazer a instalação do Squid 3. Vamos atualizar nossa lista de pacotes, utilizando um terminal, logue como usuário "root" ou utilize "sudo" antes de cada comando, sendo que neste caso seu usuário precisa ter privilégio no sudoers.

# apt-get update

Após concluída a tarefa, vamos instalar o pacote Squid 3:

# apt-get install squid3

Concluída esta tarefa, vamos a configuração do Squid.

O coração 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 vim, portanto substitua pelo que preferir.

Backup do squid.conf original:

# cp -v /etc/squid3/squid.conf /etc/squid3/squid.conf.BACKUP

Apagando o original:

# rm -v /etc/squid3/squid.conf

Criando nossa configuração em um novo squid.conf (use seu editor preferido):

# vim /etc/squid3/squid.conf

Abrindo este novo arquivo, copie e cole este script e altere para suas características. Retire meus comentários se desejar:

##squid.conf
http_port 3128
cache_mem 1000 MB # Se seu servidor for dedicado, coloque neste valor a metade de sua memória RAM, do contrário use apenas 25%
cache_swap_low 90
cache_swap_high 95
cache_dir ufs /var/spool/squid3 45000 16 256 # Aqui é o tamanho máximo de sua cache, no meu caso é 45GB, estude sua necessidade e capacidade da partição /var

maximum_object_size 30000 KB
maximum_object_size_in_memory 40 KB

access_log /var/log/squid3/access.log squid
cache_log /var/log/squid3/cache.log
cache_store_log /var/log/squid3/store.log
pid_filename /var/log/squid3/squid3.pid # pid - mudamos para esta pasta para facilitar na identificação de problemas
mime_table /usr/share/squid3/mime.conf

cache_mgr sudporte@viacom.net.br
memory_pools off

diskd_program /usr/lib/squid3/diskd
unlinkd_program /usr/lib/squid3/unlinkd

refresh_pattern ^ftp:           1440    20%     10080
refresh_pattern ^gopher:        1440    0%      1440
refresh_pattern (cgi-bin|\?)    0       0%      0
refresh_pattern .               0       20%     4320
quick_abort_max 16 KB
quick_abort_pct 95
quick_abort_min 16 KB
request_header_max_size 20 KB
reply_header_max_size 20 KB
request_body_max_size 0 KB

acl manager proto cache_object
acl localhost src 127.0.0.1/32
acl to_localhost dst 127.0.0.0/8
acl vlan24 src 192.168.30.0/24 # Representa a sua rede e respectiva máscara de sub-rede
acl lan src 172.18.28.0/24 # Assim como neste exemplo, se você tiver mais de uma rede, deve ser expressada uma por uma

acl SSL_ports port 443 563
acl Safe_ports port 80 # http
acl Safe_ports port 21 # ftp
acl Safe_ports port 443 563 1863 # 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 allow vlan24
http_access allow vlan26
http_access allow vlan28

cache_mgr webmaster
mail_program mail
cache_effective_user proxy
cache_effective_group proxy
httpd_suppress_version_string off
visible_hostname zenhulk

error_directory /usr/share/squid3/errors/Portuguese/

Até aqui, se for utilizar proxy normal, esta é a base.

Se tiver usando Slackware Linux, modifique as seguintes linhas do squid.conf:

De:

access_log /var/squid/logs/access.log squid
cache_log /var/log/squid3/cache.log
cache_store_log /var/log/squid3/store.log
pid_filename /var/log/squid3/squid3.pid

Para:

access_log /var/squid3/log/access.log squid
cache_log /var/squid3/logs/cache.log
cache_store_log /var/squid3/logs/store.log
pid_filename /var/squid3/logs/squid3.pid

As linhas abaixo, já postadas no script, são responsáveis pelo nome do usuário que o Squid usa para manipular os arquivos, neste exemplo usuário "proxy":

cache_effective_user proxy
cache_effective_group proxy

Obs.: Se você usa Debian não se preocupe e desconsidere este item, pois o Debian cria o usuário "proxy" por padrão. Porém se você usa outras distros e fez a instalação do binário ou outra fonte, deve seguir os seguintes passos:

Criar um usuário "proxy" ou outro nome se preferir, 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/ e no Slackware /var/log/squid3/, daí você identifica onde fica em sua distro e:

# chown proxy.proxy /var/log/squid3/
ou
# chown proxy.proxy /var/squid3/log/ (Slackware)

Se você estiver com dificuldades para encontrar esta pasta, basta criá-la com estas características e dar as permissões ao usuário criado e mudar o padrão do script squid.conf aqui postado.

# mkdir -p /var/log/squid3

E não esqueça da permissão após criar a pasta:

# chown proxy.proxy /var/log/squid3/

Se você for implementar um proxy transparente, deverá aplicar algumas configurações em seu script de firewall, assunto abordado na página seguinte.

Proxy transparente e configuração do firewall Iptables

 
Como disse no tópico anterior, para seu proxy operar de forma transparente há algumas configurações a serem feitas.

No arquivo /etc/squid3/squid.conf, na primeira linha:

http_port 3128

Mudar para:

http_port 3128 transparent

Salve e execute o comando (este comando é muito útil para que você reconfigure o Squid sem parar o serviço):

# squid3 -k reconfigure

Agora vamos criar o arquivo /etc/init.d/firewall com seu editor de texto preferido (exceto no Slackware, que usa outro caminho para os scripts do init):

# vim /etc/init.d/firewall (Debian e outras distros)
ou
# vim /etc/rc.d/rc.firewall (Slackware)

#!bin/bash
echo 1 > /proc/sys/net/ipv4/ip_forward
#
iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT

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

# Liberando portas SSH a partir de qualquer interface
iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# Liberando portas squid, http e NTP. Estes serviços o firewall só irá
# responder se vierem da interface da rede interna. Daí você aplica de
# acordo com o cenário de sua máquina
iptables -A INPUT -p tcp --dport 3128 -i eth0 -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -i eth0 -j ACCEPT
iptables -A INPUT -p tcp --dport 21 -i eth0 -j ACCEPT
iptables -A INPUT -p tcp --dport 123 -i eth0 -j ACCEPT
iptables -A INPUT -p udp --dport 123 -i eth0 -j ACCEPT

# Nat Global (aqui você faz o mascaramento de forma geral para qualquer
# interface ou rede do servidor. Prefiro especificar a sub-rede, deixarei
# comentada a linha global
#iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE

# NAT Rede 1 e 2 (substitua as respectivas sub-redes pelas que você usa em
# sua rede e note que a "eth1" é minha interface diretamente conectada à internet,
# substitua-a pela sua interface adequada
iptables -t nat -A POSTROUTING -s 192.168.30.0/255.255.255.0 -o eth1 -j MASQUERADE
iptables -t nat -A POSTROUTING -s 172.18.28.0/255.255.255.0 -o eth1 -j MASQUERADE

# Jogando tráfego da porta 80 para o SQUID3 TRANSPARENT
iptables -t nat -A PREROUTING -s 192.168.30.0/255.255.255.0 -p tcp --dport 80 -j REDIRECT --to-port 3128
iptables -t nat -A PREROUTING -s 172.18.28.0/255.255.255.0 -p tcp --dport 80 -j REDIRECT --to-port 3128

# Exemplo de redirecionamento de porta, neste caso redirecionamento para
# Terminal Server e VNC (substitua as respectivas sub-redes pelas que você usa
# em sua rede e as portas respectivas do serviço que quer redirecionar.
# Note que a "eth1" é minha interface diretamente conectada à internet,
# substitua-a pela sua interface adequada
iptables -A FORWARD -p tcp --dport 3389 -d 182.164.2.1 -j ACCEPT
iptables -t nat -A PREROUTING -i eth1 -p tcp --dport 3389 -j DNAT --to 192.168.30.32
iptables -A FORWARD -p tcp --dport 3389 -d 182.164.2.1 -j ACCEPT
iptables -t nat -A PREROUTING -i eth1 -p tcp --dport 5900 -j DNAT --to 172.18.28.55

Você pode aproveitar estas dicas para deixar seu firewall um pouco mais robusto, porém se quiser apenas que resolva o proxy transparente, basta as linhas abaixo, salvo que somente elas, sem qualquer restrição, torna você vulnerável na rede mundial, daí você aplica suas regras da forma que lhe for conveniente, de acordo com sua responsabilidade.

Script de firewall que implementa somente o proxy transparente:

#!bin/bash
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE
iptables -t nat -A PREROUTING -s 192.168.30.0/255.255.255.0 -p tcp --dport 80 -j REDIRECT --to-port 3128

Devemos colocar as regras que criamos no script IPTABLES para ser executado sempre que o sistema inicializar, veja qual é a forma correta em sua respectiva distro.

No Debian, adicionar as seguintes linhas ao arquivo /etc/init.d/bootmisc.sh:

# vim /etc/init.d/bootmisc.sh

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

Então salvamos e damos permissão para que o script IPTABLES seja executado pelo sistema:

# chmod +x /etc/init.d/firewall

No Slackware, quando criamos o script do firewall IPTABLES, o salvamos no seguinte local: /etc/rc.d/rc.firewall

Então basta dar permissão de execução ao script:

# chmod +x /etc/rc.d/rc.firewall

Em outras distros e também Debian, se preferir use o arquivo /etc/rc.local, adicionando 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

Para limpar e desativar estas regras do IPTABLES basta:

# iptables -F
# iptables -X
# iptables -t nat -F
# iptables -t nat -X


Assim temos proxy transparente funcionando e regras de firewall Iptables.

quinta-feira, 4 de outubro de 2012

Compartilhamento de Internet com Ubuntu Server 12.04

Compartilhando Internet

Após a instalação do Ubuntu Server 12.04, vamos configurar para ser um Gateway e um Servidor DHCP em uma pequena rede, onde neste Servidor temos 2 placas de rede: eth0 e eth1
  • eth0 liga o modem ADSL
  • eth1 a rede interna

Já feita a instalação do Ubuntu, vamos atualizar o mesmo:

$ sudo apt-get update
$ sudo apt-get upgrade


E instale o "Sysv-rc-conf":

$ sudo apt-get install sysv-rc-conf

Após a atualização, vamos colocar a mão na massa, vamos editar as interfaces de redes:

$ sudo vim /etc/network/interfaces

E deixar assim:

auto lo
iface lo inet loopback

auto eth0
iface eth0 inet dhcp

auto eth1
iface eth1 inet static

address 172.16.1.254
netmask 255.255.0.0
network 172.16.0.0
broatcast 172.16.255.255


Neste caso, deixei como DHCP a 'eth0', mas se quiser, podes deixar ele fixo também; e minha rede interna fica com a faixa de IP 172.16.1.0.0

E após isso, vamos reiniciar a rede:

$ sudo /etc/init.d/networking restart

Ou:

$ sudo invoke-rc.d networking restart

Com a rede já pronta, agora vamos efetuar o compartilhamento da Internet.

Agora vamos habilitar o encaminhamento de IPv4.

Edite o arquivo:

$ sudo vim /etc/sysctl.conf

Descomentar a linha:

# net.ipv4.ip_forward=1


Onde fica assim:

net.ipv4.ip_forward=1


Vamos agora salvar o arquivo e executar o seguinte comando, para tornar a mudança efetiva sem um Reboot:

$ sudo sysctl -w net.ipv4.ip_forward=1

Agora vamos criar um Script para o compartilhamento. Crie no "/etc/init.d":

$ sudo vim /etc/init.d/internet

E adicione:

#!/bin/bash
 
iniciar(){
modprobe iptable_nat
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
}
 
parar(){
iptables -F -t nat
}
 
case "$1" in
"start") iniciar ;;
"stop") parar ;;
"restart") parar; iniciar ;;
*) echo "Use os parâmetros start ou stop"
esac


Salve e saia do arquivo. E dê permissão de execução:

$ sudo chmod 777 /etc/init.d/internet

* Lembrando que a linha com o 'eth0', é a placa onde está ligado na ADSL.
** Se estiver ligado na 'eth1', só alterar para: eth1

Pronto. Para iniciar e parar o serviço da Internet, use os comandos abaixo:

- Para iniciar:

$ sudo invoke-rc.d internet start

Ou:

$ sudo /etc/init.d/internet start

- Para parar:

$ sudo invoke-rc.d internet stop

Ou:

$ sudo /etc/init.d/internet stop

E pronto, seu Servidor Gateway já está funcionando.

Use o "Sysv-rc-conf" para adicionar na inicialização do Servidor:

$ sudo sysv-rc-conf