TUTORIAL DE COMO COMPARTILHAR INTERNET USANDO IPTABLES

INSTALAÇÃO UBUNTU SERVER PASSO À PASSO

DADOS DA MÁQUINA:
Login: menkosal101
Senha: astrafull
Nome da máquina: nsbrv1
Dominio: local.local

Particionamento:
/ (root) = 7 gib / (home) = 4 gib / (var) = 2 gib / (srv) = 6 gib
swap = 1 gib (restante dos 20 gib)

Após instalação completa do sistema:
uname -a (saber a versão atual do kernel);
sudo apt-get update - (atualização dos repositórios, sempre que precisar instalar algum pacote, executar este comando);
sudo apt-get dist-upgrade (atualização do kernel);
sudo apt-get ugrade (atualização dos pacotes);
ifconfig -a (visualizar todas as interfaces de rede inclusive as desativadas)
route -n (roteador em valores numericos)
iproute (ip do roteador)
ifconfig (visualizar as interfaces de rede ativas)
tail -20 /var/log/syslog (logs do sistema)
ps aux |grep dhcp (em particular o “grep” procura expressões)
sudo ifup “ethX” ativar a interface de rede “ethX”

Configurção das INTERFACES de rede:

##sudo cp -v /etc/hostname /etc/hostname.old
sudoedit /etc/hostname

COLOCA-SE O NOME DO SERVIDOR SEGUIDO DO SEU DOMÍNIO

nsbrv1.local.local

Configuração dos IP’s das placas de rede

Edição dos arquivos correspondente as placas de rede

##sudo cp -v /etc/network/interfaces /etc/network/interfaces.old

sudoedit /etc/network/interfaces

#CONFIGURAÇÃO DA PRIMEIRA PLACA DE REDE (eht0)
auto eth0
iface eth0 inet dhcp ### DEPENDE DA FORMA DE COMUNICACAO
#address
#netmask
#gateway
#network
#broadcast

#CONFIGURAÇÃO DA SEGUNDA PLACA DE REDE (eth1)
auto eth1
iface eth1 inet static
address 172.16.31.1
netmask 255.255.255.224
network 172.16.31.0
broadcast 172.16.31.31

Reiniciar as placas de rede

sudo /etc/init.d/networking restart

Instalação dos pacotes (dhcp3-server e bind9) para configuração dos serviços de rede.

sudo apt-get install dhcp3-server bind9

Localiza-se o arquivo de configuração dhcpd.conf e deve fazer uma cópia para um arquivo .old, daí se acontecer algum problema faz-se a restauração do arquivo

whereis dhcp3

##sudo mv -v /etc/dhcp3/dhcpd.conf /etc/dhcp3/dhcpd.conf.old

Ediçao do arquivo dhcpd.conf

sudoedit /etc/dhcp3/dhcpd.conf

# CONFIGURACAO DO dhcpd.conf (ADAPTADO)

authorative;
ddns-­update-­style none;
subnet 172.16.31.0 netmask 255.255.255.224 {
range 172.16.31.10 172.16.31.20;
default-­lease-­time 3600;
max­-lease­-time 7200;
option subnet-­mask 255.255.255.224;
option broadcast­-address 172.16.31.31;
option domain­-name­-servers 172.16.31.1;
option domain-­name “local.local”;
option routers 172.16.31.0;
log-facility local7;
};

host ClienteVM {
hardware ethernet 08:00:27:96:fc:f3;
fixed-­address 172.16.31.5;
};
######################################3
Após a configuração do dhcpd.conf

sudo /etc/init.d/dhcp3­-server start

Confirmando que o dhcp3-server está rodando, deve-se agora configurar o bind:

##sudo cp -v /etc/bind/named.conf.local /etc/bind/named.conf.local.old

sudoedit /etc/bind/named.conf.local

# Zona Inversa
zone "31.16.172.in­-addr.arpa" IN {
type master;
notify no;
file "/etc/bind/myzones/db.inversa”;
allow­-transfer { none; };
allow­-update { none; };
};
# Zona Direta
zone "local.local" IN {
type master;
file "/etc/bind/myzones/db.direta";
allow­-transfer { none; };
allow­-update { none; };
};

DICA: Caso o administrador da rede necessite de resoluções de Endereços públicos ou externos,ou seja, o servidor DNS para que o DNS local irá transmitir os pedidos que ele não pode processar. Esta configuração deverá ocorrer no arquivo /etc/bind/named.conf.options na diretriz abaixo:

sudoedit /etc/bind/named.conf.options

forwarders {
200.165.132.148;
200.255.255.66;
};

O administrador deverá configurar os endereços de seus respectivos servidores DNS externos.

Agora configura-se cada arquivo da Zona separadamente, primeiro criando o diretorio onde os arquivos ficarão armazendados.

sudo mkdir -v /etc/bind/myzones

sudoedit /etc/bind/myzones/db.inversa

# CONFIGURAÇÃO DA ZONA INVERSA
$TTL 86400

@ IN SOA nsbrv1.local.local. root.local.local. (
2010022501 ; SERIAL
3H ; REFRESH
15M ; RETRY
1W ; EXPIRE
1D ) ; NEGATIVE CACHE TTL

@ IN NS nsbrv1.

1 IN PTR nsbrv1.local.local.

sudoedit /etc/bind/myzones/db.direta

# CONFIGURAÇÃO DA ZONA DIRETA

$TTL 86400

@ IN SOA nsbrv1.local.local. root.local.local. (
2010052502 ; SERIAL
3H ; REFRESH
15M ; RETRY
1W ; EXPIRE
1D ) ; NEGATIVE CACHE TTL

@ IN NS nsbrv1.local.local.

@ IN A 127.0.0.1

@ IN AAAA : : 1 (IPv6)

nsbrv1 IN A 172.16.31.1

www IN A 172.16.31.1

ftp IN A 172.16.31.1

mail IN A 172.16.31.1

Após configuração dos arquivos individuais de cada Zona, edita-se o resolv.conf e reiniciar o serviço bind9.

sudo /etc/init.d/bind9 start

Agora verifica-se algumas informaçoes com os seguintes comandos:

nslookup www
dig local.local
host www

Estes comando procuram os serviços relacionados!
OBS.: NAO SEI O MOTIVO PELO QUAL NAO FUNCIONARAM COMIGO, DAI sudo apt-get install resolvconf e sudoedit /etc/resolv.conf e os servicos funcionaram, ainda sem entender! vou procurar saber o motivo!

Configuração do serviço OpenSSH

sudo apt-get install openssh-server openssh-client

whereis ssh

sudo cp -v /etc/ssh/sshd_config /etc/ssh/sshd_config.old

sudoedit /etc/ssh/sshd_config


compartilhamento com IPTABLES

# iptables -F
# iptables -F INPUT
# iptables -F OUTPUT
# iptables -F POSTROUTING -t nat
# iptables -F PREROUTING -t nat
# echo 1 > /proc/sys/net/ipv4/ip_forward
# iptables -P FORWARD ACCEPT
# iptables -A POSTROUTING -t nat -s 172.16.31.0/24 -o eth1  -j MASQUERADE


Daí tem-se o respectivo arquivo sshd_config

#
# Configuracao do servidor ssh # man ssh(8) para maiores detalhes
#
#  by SiLenT-MaN -
#

# Especifica a porta
Port               2961

# Especifica o IP da interface principal
ListenAddress            x.x.x.x

# Liberar apenas o grupo staff
AllowGroups            staff

# Liberar apenas os usuarios da Operacao
AllowUsers            silent joao maria


# O tempo em que o usuario tem para digitar sua senha
LoginGraceTime            30

# Maximo de tentativas
MaxStartups            2:50:10

# Autenticacao via senha
PasswordAuthentication         yes

# Protocolo SSH V2 (2048bits)
Protocol            2
PubkeyAuthentication         yes   

# Configuracao para o servidor sftp
Subsystem      sftp      /usr/lib/sftp-server

# Imprime a ultima vez que logou
PrintLastLog            yes

# Imprime mensagem ao logar
PrintMotd            no

# Desabilita o X11
X11Forwarding            no
X11DisplayOffset         10

# HostKeys for protocol version 2
HostKey               /etc/ssh/ssh_host_rsa_key
HostKey               /etc/ssh/ssh_host_dsa_key

# Separa os privilegios do SSH do usuario
UsePrivilegeSeparation         yes

# Desabilitado por causa do PrivSep
#PAMAuthenticationViaKbdInt      no

# Lifetime and size of ephemeral version 1 server key
KeyRegenerationInterval         3600
ServerKeyBits            768

# Logging
SyslogFacility            AUTH
LogLevel            INFO

# Checa as permissoes de diretorio do usuario
StrictModes            yes

# Autenticacao via RSA
RSAAuthentication         yes

# Autenticacao via rhost nao deve ser usada
#RhostsAuthentication         no

# Nao le os arquivos ~/.rhosts e ~/.shosts dos usuarios
IgnoreRhosts            yes

# For this to work you will also need host keys in /etc/ssh_known_hosts
RhostsRSAAuthentication         no

# similar for protocol version 2
HostbasedAuthentication         no

# Nao permite senhas em branco
PermitEmptyPasswords         no

# Autenticacao via ChallangeResponse
ChallengeResponseAuthentication      no

# Bloqueia o grupo root
DenyGroups            root

# Bloqueia o usuario root
DenyUsers            root
PermitRootLogin            no

# Verifica se o host continua conectado
KeepAlive            yes

# Resposta ao Telnet na Porta
#Banner = OI

####
Banner /etc/issue.net

UsePAM yes

Após edição do arquivo deve-se iniciar o servico openssh

sudo /etc/init.d/ssh restart

e verificar se o serviço está ativo

netstat -tanp |less

Não sei por que nao conectou ainda tenho que procurar a resposta!
TEM QUE ADICIONAR O USUARIO NO SSH, APENAS SE OS MESMOS SENDO IGUAIS NAO SERÁ PRECISO MUDAR!

ssh -p 13761 172.16.31.1 (ERRADO)

ssh -p 13761 menkosal101@172.16.31.1 (CORRETO)

Após configuração do openssh-server, vamos fazer o compartilhamento da Internet, editando sysctl, mas antes lembrar de fazer uma cópia.

sudo cp -v /etc/sysctl.conf /etc/sysctl.conf.old

sudoedit /etc/sysctl.conf

alteramos a parte que tem descomentar a linha

net.ipv4.ip-forward = 1 (desta forma é feito o compartilhamento da internet)

para saber se o serviço está ativo

sudo sysctl -p

sudo iptables -A POSTROUTING -t nat -j MASQUERADE

para confirmar que o ip vai ser compartilhado

sudo iptables -F

Agora vamos configurar o VSFTP e o Apache

sudo apt-get install vsftpd apache2

whereis vsftpd

sudo cp -v /etc/vsftpd.conf /etc/vsftpd.conf.old

# Example config file /etc/vsftpd.conf
#
# The default compiled in settings are fairly paranoid. This sample file
# loosens things up a bit, to make the ftp daemon more usable.
# Please see vsftpd.conf.5 for all compiled in defaults.
#
# READ THIS: This example file is NOT an exhaustive list of vsftpd options.
# Please read the vsftpd.conf.5 manual page to get a full idea of vsftpd's
# capabilities.
#
#
# Run standalone?  vsftpd can run either from an inetd or as a standalone
# daemon started from an initscript.
listen=YES
#
# Run standalone with IPv6?
# Like the listen parameter, except vsftpd will listen on an IPv6 socket
# instead of an IPv4 one. This parameter and the listen parameter are mutually
# exclusive.
#listen_ipv6=YES
#
# Allow anonymous FTP? (Beware - allowed by default if you comment this out).
anonymous_enable=YES
#
# Uncomment this to allow local users to log in.
local_enable=YES
#
# Uncomment this to enable any form of FTP write command.
write_enable=YES
#
# Default umask for local users is 077. You may wish to change this to 022,
# if your users expect that (022 is used by most other ftpd's)
#local_umask=022
#
# Uncomment this to allow the anonymous FTP user to upload files. This only
# has an effect if the above global write enable is activated. Also, you will
# obviously need to create a directory writable by the FTP user.
anon_upload_enable=YES
#
# Uncomment this if you want the anonymous FTP user to be able to create
# new directories.
#anon_mkdir_write_enable=YES
#
# Activate directory messages - messages given to remote users when they
# go into a certain directory.
dirmessage_enable=YES
#
# Activate logging of uploads/downloads.
xferlog_enable=YES
#
# Make sure PORT transfer connections originate from port 20 (ftp-data).
connect_from_port_20=YES
#
# If you want, you can arrange for uploaded anonymous files to be owned by
# a different user. Note! Using "root" for uploaded files is not
# recommended!
#chown_uploads=YES
#chown_username=whoever
#
# You may override where the log file goes if you like. The default is shown
# below.
#xferlog_file=/var/log/vsftpd.log
#
# If you want, you can have your log file in standard ftpd xferlog format
#xferlog_std_format=YES
#
# You may change the default value for timing out an idle session.
#idle_session_timeout=600
#
# You may change the default value for timing out a data connection.
#data_connection_timeout=120
#
# It is recommended that you define on your system a unique user which the
# ftp server can use as a totally isolated and unprivileged user.
#nopriv_user=ftpsecure
#
# Enable this and the server will recognise asynchronous ABOR requests. Not
# recommended for security (the code is non-trivial). Not enabling it,
# however, may confuse older FTP clients.
#async_abor_enable=YES
#
# By default the server will pretend to allow ASCII mode but in fact ignore
# the request. Turn on the below options to have the server actually do ASCII
# mangling on files when in ASCII mode.
# Beware that turning on ascii_download_enable enables malicious remote parties
# to consume your I/O resources, by issuing the command "SIZE /big/file" in
# ASCII mode.
# These ASCII options are split into upload and download because you may wish
# to enable ASCII uploads (to prevent uploaded scripts etc. from breaking),
# without the DoS risk of SIZE and ASCII downloads. ASCII mangling should be
# on the client anyway..
#ascii_upload_enable=YES
#ascii_download_enable=YES
#
# You may fully customise the login banner string:
ftpd_banner=Bem vindo Ao FTP do Murilo
#
# You may specify a file of disallowed anonymous e-mail addresses. Apparently
# useful for combatting certain DoS attacks.
#deny_email_enable=YES
# (default follows)
#banned_email_file=/etc/vsftpd.banned_emails
#
# You may restrict local users to their home directories.  See the FAQ for
# the possible risks in this before using chroot_local_user or
# chroot_list_enable below.
chroot_local_user=YES
#
# You may specify an explicit list of local users to chroot() to their home
# directory. If chroot_local_user is YES, then this list becomes a list of
# users to NOT chroot().
#chroot_list_enable=YES
# (default follows)
#chroot_list_file=/etc/vsftpd.chroot_list
#
# You may activate the "-R" option to the builtin ls. This is disabled by
# default to avoid remote users being able to cause excessive I/O on large
# sites. However, some broken FTP clients such as "ncftp" and "mirror" assume
# the presence of the "-R" option, so there is a strong case for enabling it.
#ls_recurse_enable=YES

#opção para ativar log em /var/log/messages
syslog_enable=YES

#Opção de qual porta o servidor ira ficar escutando
listen_port=100

#Pegar a data do sistema:
use_localtime=YES

#Limite Maximos de Users:
max_clients=10

#Limite maximo de users por ip:
max_per_ip=8

#Ativa log de down/uploads
xferlog_enable=YES
xferlog_file=/var/log/vsftpd.log

Instalacao do SAMBA (SMB)

whereis samba

less /etc/samba/smb.conf

CRIAR DIRETORIOS

sudo mkdir /srv/{AULA1,VIDEOS } criando dois diretorios dentro do srv

sudo chown menkosal101:menkosal101 /srv/{ , } NAO DEIXAR ESPAÇO ENTRE OS DIRETORIOS

ALTERAR ARQUIVO SMB.CONF

sudoedit /etc/samba/smb.conf

; /etc/smb.conf
;
; Esteja seguro de reinicializar o servidor após executar as mudanças no
: arquivo, exemplo:
; /etc/rc.d/init.d/smb stop
; /etc/rc.d/init.d/smb start

[global]
; Deve ser retirado o símbolo de comentário (;) caso se deseje ter um usuário
; convidado (guest)
; guest account = nobody
 log file = /var/log/samba-log.%m
 lock directory = /var/lock/samba
 share modes = yes

[homes]
 comment = Diretórios Pessoais
 browseable = no
 read only = no
 create mode = 0750

[tmp]
 comment = Localização de Arquivos Temporários  
 path = /tmp
 read only = no
 public = yes

Servidor proxy

SQUID PRONTO

visible_hostname nome_servidor
http_port 192.168.0.1:3128
cache_mgr admnet@empresa.com.br
cache_mem 64 MB
hierarchy_stoplist cgi-bin ?
acl QUERY urlpath_regex cgi-bin \?
no_cache deny QUERY
auth_param basic program /usr/lib/squid/ncsa_auth /etc/squid/passwd
auth_param basic children 250
auth_param basic realm Digite seu Login
auth_param basic credentialsttl 8 hours
auth_param basic casesensitive off
refresh_pattern ^ftp:      1440   20%   10080
refresh_pattern ^gopher:   1440   0%   1440
refresh_pattern .      0   20%   4320
acl rede_interna proxy_auth REQUIRED
acl all src 0.0.0.0/0.0.0.0
acl manager proto cache_object
acl localhost src 127.0.0.1/255.255.255.255
acl to_localhost dst 127.0.0.0/8
acl SSL_ports port 443 563
acl Safe_ports port 80      # http
acl Safe_ports port 21      # ftp
acl Safe_ports port 110      # pop
acl Safe_ports port 443 563   # https, snews
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 rede_interna
http_access allow manager localhost
http_access deny manager
http_access deny !Safe_ports
http_access deny CONNECT !SSL_ports
http_access allow localhost
http_access deny all
http_reply_access allow all
httpd_accel_host virtual
httpd_accel_port 80
httpd_accel_with_proxy on
httpd_accel_uses_host_header on
icp_access allow all
coredump_dir /var/spool/squid

Comentários

Postagens mais visitadas deste blog

MUDAR O NOME DE USUÁRIO NO UBUNTU

5 Distribuições Linux que você deve ter instalado em seu pendrive

99 coisas para fazer antes de morrer