02 - Baixando a VirtualBox 
https://www.virtualbox.org/

Clique acima no botâo "Download 5.0 Virtualbox"

Clique no link acima em
VirtualBox 5.0.20 for Windows hosts "x86/amd64"
Observe na imagem abaixo no canto inferior esquerdo o download concluído da
VirtualBox, clique duplo nele para iniciar a instalação da VirtualBox.

Clique em
Next

Clique em
Next

Clique em
Next

Clique em
Next

Clique em
Install

Clique em
Instalar

Clique em
Instalar

Clique em
Instalar

Clique em
Finish
03 - Configuração do Debian na VirtualBox 
Clique em
Novo, no campo
Nome: digite
Debian 8.4 - aula - clique em
Próximo

Clique em
Próximo e defina 1024 de memória ram

Clique em
Criar

Clique em
Próximo

Clique em
Próximo

Clique em
Criar

Notem que já tenho outros sistemas operacionais instalados na virtualbox,
a nossa instalação é a última...

Clique em
Configurações, clique em
Rede e selecione o Adaptador 1 conectado a:
Placa em modo Bridge porque durante a instalação serão baixados arquivos das fontes
do Debian e precisaremos de acesso a internet.

Clique duplo em
Debian 8.4 - aula

Clique em
Drive do hospedeiro 'D:' e será aberta uma atela para apontar para o arquivo iso.

Selecione o arquivo .iso e clique em
iniciar
04 - Iniciando instalação do Debian 
Quando instalamos no servidor a forma texto teremos o controle de tudo, pois saberemos
o que foi instalado ao passo que na forma gráfica muitas outras coisas serão instaladas
e precisamos manter o controle de tudo o que for instalado afim de deixarmos o servidor
o mais seguro possivel.
Clique em
Install para iniciarmos a instalação. Instalaremos a versão "texto" do
Debian e não a gráfica.

Vou manter o padrão inglês visto que sou fluente no idioma e muito acostumado mas se
você quiser poderá escolher o idioma português.
Language:
English

Country, territory or area:
United States

Keymap to use:
American English

Hostname:
Debian e pressione enter

Domain:
Pressione enter

Root password:
123 enter ( agora, mais tarde mudaremos... )

Será solicitado a confirmação da senha:
123

Vamos criar um usuário de nome
jura e senha
123 e pressione enter

Easterm:
Pressione enter

Partitioning method:
Pressione enter

Select disk to partition:
Pressione enter

Vamos deixar o Linux particionar o disco. Para iniciantes é a opção mais fácil, no
meu tutorial atualizado mostro como particionar manualmente o disco assim poderemos
definir o tamanho das partições.
Partitioning scheme:
All files in one partition ( recommended for new users )- enter

Pressione "enter"

Selecione
Yes e Pressione "enter" para criar as partições.

Debian archive mirror country:
Brasil - enter

Como estou em Santa Catarina selecionarei este repositório.
Debian archive mirror:
debian.pop-sc.rnp.br

HTTP proxy information:
Pressione enter

Participate in the package usage survey?
No

Vamos instalar somente as duas últimas opções:
SSH server
e
Standard system utilities
após selecionado as duas última opções abaixo pressione em
Continue

Install the GRUB boot loader to the master boot recard:
yes

Device for boot loader installation:
/dev/sda (ata-VBOX_HARDDISK_VB80a3767c-ea193ef3)
Selecione a segunda opção e pressione enter

Installation complete: Pressione enter em
Continue

Instalação concluída do linux debian na virtualbox.... estamos no terminal...

Digite...: root
Password.: 123 ( enter )

Use o comando "ifconfig" para visualizar o ip do nosso servidor instalado na VirtualBox.
*** Todos os camandos em Linux devem ser digitados em letras minúsculas ***
O servidor recebeu o ip
192.168.1.101 visto que na configuração na Virtual Box
definimos o "modo bridge", ou seja os ips são gerenciados pelo servidor de dhcp do
modem, ou seja, atribuição automática de ip do modem.
Este ip pode ser fixo e adiante veremos isto.
Digite:
ifconfig e pressione enter
05 - Putty - Windows ---> Linux 
Para facilitar copiar e colar comandos, códigos etc tentaremos acessar do Windows o
nosso servidor usando o programa chamado
putty.exe
Baixe-o neste link.:
http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html
Digite o ip........:
192.168.1.101
Nome para salvar...:
101-Servidor Aula
( caso futuramente usemos este ip nao precisaremos digitar tudo novamente )
Clique no botão....:
Save

Na primeira conexão do Putty será mostrada a tela abaixo:

Tentei acessar como
root e senha
123 e mostrou a mensagem
Access denied
( acesso negado )... feche a tela do putty e abra novamente mas agora usaremos o
usuário comum.

Através do Putty usaremos o usuário "jura" e senha "123" que definimos durante a
instalação do Debian.
Login as..:
jura
Password..:
123
Após logado com sucesso use o comando "su" para virar super usuário ou root e digite
a senha do root que é 123
Para sair do diretório "/home/jura", digite "cd" e pressione "enter"
Caso queira mudar a senha do root digite
password pressione enter e digite a
senha
senha_nova

Vamos executar os dois comandos abaixo para atualizar os sistema:
apt-get update ( enter )
apt-get upgrade ( enter )
ou
apt-get update -y && apt-get upgrade -y ( enter )

Verificando se estamos com acesso externo / internet ... ( ip dns do google )
ping 8.8.8.8

Verificando, monitorando se há algum erro no sistema ( arquivo log ).
tail -f /var/log/syslog

Verificando nossa rota.
route -n

Edite o arquivo abaixo e remova as primeiras 3 linhas ( “#” e “deb cdrom” )
Usaremos o editor de texto padrão do Debian chamado de “nano”.
Para remover estas linhas, posicione o cursor no início do arquivo com a setinha para
cima e pressione “ctrl k” para apagar as 3 linhas iniciais do arquivo.
nano /etc/apt/sources.list ( enter )
#
# deb cdrom:[Debian GNU/Linux 8.4.0 _Jessie_ - Official amd64 NETINST Binary-1 20160402-14:42]/ jessie main
# deb cdrom:[Debian GNU/Linux 8.4.0 _Jessie_ - Official amd64 NETINST Binary-1 20160402-14:42]/ jessie main
deb http://debian.pop-sc.rnp.br/debian/ jessie main
deb-src http://debian.pop-sc.rnp.br/debian/ jessie main
deb http://security.debian.org/ jessie/updates main
deb-src http://security.debian.org/ jessie/updates main
# jessie-updates, previously known as 'volatile'
deb http://debian.pop-sc.rnp.br/debian/ jessie-updates main
deb-src http://debian.pop-sc.rnp.br/debian/ jessie-updates main
ctrl + x + y + enter ( salvar e sair do arquivo )
Abaixo apenas mostrando as 3 linhas no inicio do arquivo...

As 3 linhas do inicio do arquivo foram removidas...
apt-get update -y && apt-get upgrade -y
cat /etc/network/interfaces ( enter )

Vamos definir um ip fixo ( 192.168.1.13 ) para nosso servidor na rede interno.
nano /etc/network/interfaces
auto lo
iface lo inet loopback
source /etc/network/interfaces.d/*
allow-hotplug eth0
iface eth0 inet static
address
192.168.1.13
netmask 255.255.255.0
network 192.168.1.0
broadcast 192.168.1.255
gateway
192.168.1.1
# 192.168.1.1 eh o ip do modem Dlink
dns-nameservers 8.8.8.8
# Acima ip dns do google
ctrl + x + y + enter ( salvar e sair do arquivo )

Reinicie o servidor para atualizar a mudança dos ips. Tem um linha que "deveria"
fazer esta atualização mas por incrivel que pareça trava e não vai, então vamos
reiniciar.
shutdown –r now
Agora vamos cadastrar o ip 192.168.1.13 no Putty para acessarmos o terminal.
06 - Ajustando a hora 
Vamos atualizar a hora do sistema.
dpkg-reconfigure tzdata
Geographic area:
America e pressione enter

Para chegar rapidamente na cidade
São Paulo pressione
S S S S S e enter em
São Paulo

Note no primeiro comando na imagem abaixo que apenas a hora não estava correta mas ok.
07 - Criando arquivo de boot 
Vamos criar o arquivo de boot para executar certas linhas de configuração essenciais
na inicialização do nosso servidor, assim se o servidor for reiniciado estas linhas
serão carregadas automaticamente.
nano /etc/init.d/rc.begin ( enter )
#!/bin/bash
clear
echo ''
echo ''
echo '===================================='
echo ''
echo ''
# ip forward = faz o bypass de compartilhamento e ativa o roteamento no kernel
modprobe iptable_nat
echo 1 >/proc/sys/net/ipv4/ip_forward
echo 'IP forward ................. [ ok ] '
echo ''
echo ''
echo '===================================='
echo ''
ctrl + x + y + enter ( salvar e sair do arquivo )
Tornando arquivo executável.
chmod +x /etc/init.d/rc.begin ( enter )
Aplicar o update-rc.d , retornará alguns warnings ( messagens )...
update-rc.d rc.begin defaults ( enter )
insserv: warning: script 'rc.begin' missing LSB tags and overrides
Precisaremos criar um link simbólico para que o RunLevel consiga subir o script.
ln -s /etc/init.d/rc.begin /etc/rc2.d/ ( enter )
Listando o link simbólico acima.
ls -la /etc/rc2.d/ | grep rc.begin ( enter )
lrwxrwxrwx 1 root root 20 May 20 10:39 rc.begin -> /etc/init.d/rc.begin
lrwxrwxrwx 1 root root 18 May 20 10:39 S02rc.begin -> ../init.d/rc.begin
08 - Alguns comandos iniciais 
Listando todos os serviços que estão rodando após conclusão da instalação.
ps aux ( enter )
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.4 28296 4452 ? Ss 09:50 0:00 /sbin/init
root 2 0.0 0.0 0 0 ? S 09:50 0:00 [kthreadd]
root 3 0.0 0.0 0 0 ? S 09:50 0:00 [ksoftirqd/0]
root 5 0.0 0.0 0 0 ? S< 09:50 0:00 [kworker/0:0H]
root 6 0.0 0.0 0 0 ? S 09:50 0:00 [kworker/u2:0]
root 7 0.0 0.0 0 0 ? S 09:50 0:01 [rcu_sched]
root 8 0.0 0.0 0 0 ? S 09:50 0:00 [rcu_bh]
root 9 0.0 0.0 0 0 ? S 09:50 0:00 [migration/0]
root 10 0.0 0.0 0 0 ? S 09:50 0:00 [watchdog/0]
root 11 0.0 0.0 0 0 ? S< 09:50 0:00 [khelper]
root 12 0.0 0.0 0 0 ? S 09:50 0:00 [kdevtmpfs]
root 13 0.0 0.0 0 0 ? S< 09:50 0:00 [netns]
root 14 0.0 0.0 0 0 ? S 09:50 0:00 [khungtaskd]
root 15 0.0 0.0 0 0 ? S< 09:50 0:00 [writeback]
root 16 0.0 0.0 0 0 ? SN 09:50 0:00 [ksmd]
root 17 0.0 0.0 0 0 ? SN 09:50 0:00 [khugepaged]
root 18 0.0 0.0 0 0 ? S< 09:50 0:00 [crypto]
root 19 0.0 0.0 0 0 ? S< 09:50 0:00 [kintegrityd]
root 20 0.0 0.0 0 0 ? S< 09:50 0:00 [bioset]
root 21 0.0 0.0 0 0 ? S< 09:50 0:00 [kblockd]
root 23 0.0 0.0 0 0 ? S 09:50 0:00 [kswapd0]
root 24 0.0 0.0 0 0 ? S< 09:50 0:00 [vmstat]
root 25 0.0 0.0 0 0 ? S 09:50 0:00 [fsnotify_mark]
root 31 0.0 0.0 0 0 ? S< 09:50 0:00 [kthrotld]
root 32 0.0 0.0 0 0 ? S< 09:50 0:00 [ipv6_addrconf]
root 33 0.0 0.0 0 0 ? S< 09:50 0:00 [deferwq]
root 67 0.0 0.0 0 0 ? S 09:50 0:00 [khubd]
root 68 0.0 0.0 0 0 ? S< 09:50 0:00 [ata_sff]
root 69 0.0 0.0 0 0 ? S< 09:50 0:00 [kpsmoused]
root 70 0.0 0.0 0 0 ? S 09:50 0:00 [scsi_eh_0]
root 71 0.0 0.0 0 0 ? S< 09:50 0:00 [scsi_tmf_0]
root 72 0.0 0.0 0 0 ? S 09:50 0:00 [scsi_eh_1]
root 73 0.0 0.0 0 0 ? S 09:50 0:00 [kworker/u2:2]
root 74 0.0 0.0 0 0 ? S< 09:50 0:00 [scsi_tmf_1]
root 75 0.0 0.0 0 0 ? S 09:50 0:00 [scsi_eh_2]
root 76 0.0 0.0 0 0 ? S< 09:50 0:00 [scsi_tmf_2]
root 82 0.0 0.0 0 0 ? S< 09:50 0:00 [kworker/0:1H]
root 104 0.0 0.0 0 0 ? S 09:50 0:00 [jbd2/sda1-8]
root 105 0.0 0.0 0 0 ? S< 09:50 0:00 [ext4-rsv-conver]
root 135 0.0 0.0 0 0 ? S 09:50 0:00 [kauditd]
root 137 0.0 0.3 40920 3348 ? Ss 09:50 0:00 /lib/systemd/systemd-udevd
root 140 0.0 0.2 28872 2552 ? Ss 09:50 0:01 /lib/systemd/systemd-journald
root 360 0.0 0.2 37080 2728 ? Ss 09:50 0:00 /sbin/rpcbind -w
statd 369 0.0 0.2 37280 2852 ? Ss 09:50 0:00 /sbin/rpc.statd
root 374 0.0 0.0 0 0 ? S< 09:50 0:00 [rpciod]
root 376 0.0 0.0 0 0 ? S< 09:50 0:00 [nfsiod]
root 383 0.0 0.0 23356 204 ? Ss 09:50 0:00 /usr/sbin/rpc.idmapd
daemon 384 0.0 0.1 19024 1776 ? Ss 09:50 0:00 /usr/sbin/atd -f
root 385 0.0 0.5 55184 5344 ? Ss 09:50 0:00 /usr/sbin/sshd -D
root 386 0.0 0.2 27476 2688 ? Ss 09:50 0:00 /usr/sbin/cron -f
root 388 0.0 0.2 19856 2604 ? Ss 09:50 0:00 /lib/systemd/systemd-logind
message+ 390 0.0 0.3 42124 3292 ? Ss 09:50 0:00 /usr/bin/dbus-daemon --system --address=systemd: --
root 429 0.0 0.3 258672 3312 ? Ssl 09:50 0:00 /usr/sbin/rsyslogd -n
root 430 0.0 0.1 4256 1724 ? Ss 09:50 0:00 /usr/sbin/acpid
root 433 0.0 0.2 14416 2108 tty1 Ss+ 09:50 0:00 /sbin/agetty --noclear tty1 linux
Debian-+ 650 0.0 0.3 53248 3348 ? Ss 09:50 0:00 /usr/sbin/exim4 -bd -q30m
root 656 0.0 0.5 82728 5776 ? Ss 09:51 0:00 sshd: jura [priv]
jura 658 0.0 0.4 82728 4672 ? R 09:51 0:00 sshd: jura@pts/0
jura 659 0.0 0.4 22948 4720 pts/0 Ss 09:51 0:00 -bash
root 668 0.0 0.3 46360 3160 pts/0 S 09:51 0:00 su
root 669 0.0 0.3 21860 3748 pts/0 S 09:51 0:00 bash
root 1767 0.0 0.0 0 0 ? S 15:16 0:00 [kworker/0:0]
root 1776 0.0 0.0 0 0 ? S 15:26 0:00 [kworker/0:1]
root 1777 0.0 0.0 0 0 ? S 15:31 0:00 [kworker/0:2]
root 1778 0.0 0.2 19100 2500 pts/0 R+ 15:36 0:00 ps aux
Contando quantos serviços estão ativos.
ps aux | wc -l
67
Lista de serviços rodando.
service --status-all ( enter )
[ + ] acpid
[ + ] atd
[ - ] bootlogs
[ - ] bootmisc.sh
[ - ] checkfs.sh
[ - ] checkroot-bootclean.sh
[ - ] checkroot.sh
[ + ] console-setup
[ + ] cron
[ + ] dbus
[ + ] exim4
[ - ] hostname.sh
[ - ] hwclock.sh
[ + ] kbd
[ + ] keyboard-setup
[ - ] killprocs
[ + ] kmod
[ - ] motd
[ - ] mountall-bootclean.sh
[ - ] mountall.sh
[ - ] mountdevsubfs.sh
[ - ] mountkernfs.sh
[ - ] mountnfs-bootclean.sh
[ - ] mountnfs.sh
[ + ] networking
[ + ] nfs-common
[ + ] procps
[ + ] rc.begin
[ + ] rc.local
[ - ] rmnologin
[ + ] rpcbind
[ + ] rsyslog
[ - ] sendsigs
[ + ] ssh
[ + ] udev
[ + ] udev-finish
[ - ] umountfs
[ - ] umountnfs.sh
[ - ] umountroot
[ + ] urandom
Listando espaço ocupado pelos diretórios “var” e “etc”
du -sch /var ( enter )
134M /var
179M total
du -sch /etc ( enter )
179M /etc
179M total
O arquivo /etc/passwd contém informações sobre todos os usuários, inclusive as
suas senhas criptografadas.
cat /etc/passwd ( enter )
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
systemd-timesync:x:100:103:systemd Time Synchronization,,,:/run/systemd:/bin/false
systemd-network:x:101:104:systemd Network Management,,,:/run/systemd/netif:/bin/false
systemd-resolve:x:102:105:systemd Resolver,,,:/run/systemd/resolve:/bin/false
systemd-bus-proxy:x:103:106:systemd Bus Proxy,,,:/run/systemd:/bin/false
Debian-exim:x:104:109::/var/spool/exim4:/bin/false
messagebus:x:105:110::/var/run/dbus:/bin/false
statd:x:106:65534::/var/lib/nfs:/bin/false
sshd:x:107:65534::/var/run/sshd:/usr/sbin/nologin
jura:x:1000:1000:jura,,,:/home/jura:/bin/bash
Filtro “mais limpo”
cat /etc/passwd | cut -d":" -f1 ( enter )
root
daemon
bin
sys
sync
games
man
lp
mail
news
uucp
proxy
www-data
backup
list
irc
gnats
nobody
systemd-timesync
systemd-network
systemd-resolve
systemd-bus-proxy
Debian-exim
messagebus
statd
sshd
jura
Contando usuários da lista acima.
cat /etc/passwd | cut -d":" -f1 | wc –l ( enter )
27
O Syslog é o sistema de registro de eventos, seu objetivo é armazenar mensagens de
eventos ocorridos no sistema, permitindo ao administrador, localizar possíveis falhas
ou tentativas de invasão no sistema.
Um dos motivos pelo qual, geralmente, se coloca o /var em uma partição separada, é que
se evitar que os logs cresçam tanto ao ponto de estourarem a partição, e sendo em uma
partição separada o impacto seria menor do que se fosse na raiz.
tail -f /var/log/syslog ( enter )
May 19 01:12:44 debian sm-notify[374]: Version 1.2.8 starting
May 19 01:12:44 debian nfs-common[368]: Starting NFS common utilities: statd idmapd.
May 19 01:12:44 debian cron[389]: (CRON) INFO (pidfile fd = 3)
May 19 01:12:44 debian cron[389]: (CRON) INFO (Running @reboot jobs)
May 19 01:12:44 debian acpid: starting up with netlink and the input layer
May 19 01:12:44 debian acpid: 1 rule loaded
May 19 01:12:44 debian acpid: waiting for events: event logging is off
May 19 01:12:44 debian kernel: [ 7.208209] random: nonblocking pool is initialized
May 19 01:12:44 debian exim4[393]: Starting MTA: exim4.
May 19 01:17:01 debian CRON[676]: (root) CMD ( cd / && run-parts --report /etc/cron.hourly)
Registro do uso de autorizações do sistema, como mecanismos que exigem senhas.
Exemplo: o comando sudo ou logins SSH remotos.
tail -f /var/log/auth.log ( enter )
May 19 01:12:44 debian systemd-logind[392]: Watching system buttons on /dev/input/event3 (Power Button)
May 19 01:12:44 debian systemd-logind[392]: Watching system buttons on /dev/input/event4 (Sleep Button)
May 19 01:12:44 debian systemd-logind[392]: New seat seat0.
May 19 01:13:08 debian sshd[660]: Accepted password for jura from 192.168.1.100 port 53078 ssh2
May 19 01:13:08 debian sshd[660]: pam_unix(sshd:session): session opened for user jura by (uid=0)
May 19 01:13:11 debian su[672]: Successful su for root by jura
May 19 01:13:11 debian su[672]: + /dev/pts/0 jura:root
May 19 01:13:11 debian su[672]: pam_unix(su:session): session opened for user root by jura(uid=1000)
May 19 01:17:01 debian CRON[675]: pam_unix(cron:session): session opened for user root by (uid=0)
May 19 01:17:01 debian CRON[675]: pam_unix(cron:session): session closed for user root
Então atenção com a senha do Root !
Mudando a senha do root, já vimos anteriormente.
passwd ( enter )
Enter new UNIX password: senha_nova ( enter )
Retype new UNIX password: senha_nova ( enter )
passwd: password updated successfully
netstat -tap | grep LISTEN
tcp 0 0 localhost:smtp *:* LISTEN 654/exim4
tcp 0 0 *:40868 *:* LISTEN 373/rpc.statd
tcp 0 0 *:sunrpc *:* LISTEN 364/rpcbind
tcp 0 0 *:ssh *:* LISTEN 390/sshd
tcp6 0 0 localhost:smtp [::]:* LISTEN 654/exim4
tcp6 0 0 [::]:46566 [::]:* LISTEN 373/rpc.statd
tcp6 0 0 [::]:sunrpc [::]:* LISTEN 364/rpcbind
tcp6 0 0 [::]:ssh [::]:* LISTEN 390/sshd
netstat -planta | grep LISTEN ( enter )
tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 654/exim4
tcp 0 0 0.0.0.0:40868 0.0.0.0:* LISTEN 373/rpc.statd
tcp 0 0 0.0.0.0:111 0.0.0.0:* LISTEN 364/rpcbind
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 390/sshd
tcp6 0 0 ::1:25 :::* LISTEN 654/exim4
tcp6 0 0 :::46566 :::* LISTEN 373/rpc.statd
tcp6 0 0 :::111 :::* LISTEN 364/rpcbind
tcp6 0 0 :::22 :::* LISTEN 390/sshd
netstat –lntpe
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State User Inode PID/Program
tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 0 11071 654/exim4
tcp 0 0 0.0.0.0:40868 0.0.0.0:* LISTEN 106 9889 373/rpc.statd
tcp 0 0 0.0.0.0:111 0.0.0.0:* LISTEN 0 9779 364/rpcbind
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 0 10632 390/sshd
tcp6 0 0 ::1:25 :::* LISTEN 0 11072 654/exim4
tcp6 0 0 :::46566 :::* LISTEN 106 9895 373/rpc.statd
tcp6 0 0 :::111 :::* LISTEN 0 9782 364/rpcbind
tcp6 0 0 :::22 :::* LISTEN 0 10641 390/sshd
netstat –ltun
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:40868 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:111 0.0.0.0:* LISTEN
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN
tcp6 0 0 ::1:25 :::* LISTEN
tcp6 0 0 :::46566 :::* LISTEN
tcp6 0 0 :::111 :::* LISTEN
tcp6 0 0 :::22 :::* LISTEN
udp 0 0 0.0.0.0:963 0.0.0.0:*
udp 0 0 127.0.0.1:973 0.0.0.0:*
udp 0 0 0.0.0.0:35292 0.0.0.0:*
udp 0 0 0.0.0.0:111 0.0.0.0:*
udp6 0 0 :::963 :::*
udp6 0 0 :::58473 :::*
udp6 0 0 :::111 :::*
Estou conectado usando ssh na porta 22.
netstat -n -A inet
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 52 192.168.1.13:22 192.168.1.100:53078 ESTABLISHED
netstat -tulpn | grep :22
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 390/sshd
tcp6 0 0 :::22 :::* LISTEN 390/sshd
tail -f /var/log/syslog
May 20 08:50:50 Debian exim4[389]: Starting MTA: exim4.
May 20 09:17:01 Debian CRON[680]: (root) CMD ( cd / && run-parts --report /etc/cron.hourly)
May 20 10:17:01 Debian CRON[699]: (root) CMD ( cd / && run-parts --report /etc/cron.hourly)
May 20 11:17:01 Debian CRON[763]: (root) CMD ( cd / && run-parts --report /etc/cron.hourly)
May 20 12:17:01 Debian CRON[792]: (root) CMD ( cd / && run-parts --report /etc/cron.hourly)
May 20 13:17:01 Debian CRON[843]: (root) CMD ( cd / && run-parts --report /etc/cron.hourly)
May 20 13:24:49 Debian rsyslogd-2007: action 'action 17' suspended, next retry is Fri May 20 13:25:19 2016
[try http://www.rsyslog.com/e/2007 ]
May 20 14:17:01 Debian CRON[1769]: (root) CMD ( cd / && run-parts --report /etc/cron.hourly)
May 20 14:37:15 Debian kernel: [20792.530035] nf_conntrack version 0.5.0 (8003 buckets, 32012 max)
May 20 14:37:15 Debian kernel: [20792.534626] ip_tables: (C) 2000-2006 Netfilter Core Team
cat /var/log/auth.log | grep -i jura | grep Successful
May 19 20:27:56 Debian su[715]: Successful su for root by jura
May 19 20:37:18 Debian su[682]: Successful su for root by jura
May 19 20:39:00 Debian su[697]: Successful su for root by jura
May 19 20:44:33 Debian su[720]: Successful su for root by jura
May 19 20:48:20 Debian su[672]: Successful su for root by jura
May 20 08:51:40 Debian su[668]: Successful su for root by jura
lsof -P -i -n | grep TC
rpcbind 360 root 8u IPv4 9757 0t0 TCP *:111 (LISTEN)
rpcbind 360 root 11u IPv6 9760 0t0 TCP *:111 (LISTEN)
rpc.statd 369 statd 9u IPv4 9867 0t0 TCP *:60782 (LISTEN)
rpc.statd 369 statd 11u IPv6 9873 0t0 TCP *:38834 (LISTEN)
sshd 385 root 3u IPv4 10789 0t0 TCP *:22 (LISTEN)
sshd 385 root 4u IPv6 10798 0t0 TCP *:22 (LISTEN)
exim4 650 Debian-exim 4u IPv4 11001 0t0 TCP 127.0.0.1:25 (LISTEN)
exim4 650 Debian-exim 5u IPv6 11002 0t0 TCP [::1]:25 (LISTEN)
sshd 656 root 3u IPv4 11106 0t0 TCP 192.168.1.13:22->192.168.1.100:49259 (ESTABLISHED)
sshd 658 jura 3u IPv4 11106 0t0 TCP 192.168.1.13:22->192.168.1.100:49259 (ESTABLISHED)
netstat -an | awk '/tcp/ {print $6}' | sort | uniq –c
1 ESTABLISHED
8 LISTEN
lsof -P -i -n | cut -f 1 -d " " | uniq | tail -n +2
rpcbind
rpc.statd
sshd
exim4
sshd
09 - No-ip - "ip fixo para acesso remoto" 
O no-ip.org permite ter um ip gratuito porém teremos que criar uma conta. Abaixo
veremos passo a passo como fazer isto. Para configurar um servidor de emails o
no-ip.org não serve! Se você tiver um ip fixo oficial ( válido ), ignore este
exemplo pois não será necessário.
O no-ip trata-se de uma "mascara" de ip. Muitas vezes para você criar um server você
precisa ter um IP fixo. O grande problema é que na maioria dos casos os nossos IPs são
constantemente alterados, chama-se de IPs dinâmicos.
O No-ip faz uma conexão direta com o seu computador e lhe fornece um ip fixo ligado ao
seu computador, ou seja, sempre que você precisar uma conexão com o computador, não
precisa necessariamente saber o IP atual dele, usa o NO-ip e pronto.
Devemos de ser gratos ao serviço “no-ip” por nos proporcionar este serviço gratuito e
com isto podermos iniciar nosso aprendizado. Muito obrigado “no-ip.org”. Precisaremos
de um ip fixo para acessarmos o nosso servidor remotamente via ssh.
Vamos criar uma conta no
https://www.noip.com/
ATENÇÃO
O no-ip.com não é uma solução para servidor de emails. Para tal teremos que ter um ip
fixo oficial. Vamos contratar um ip fixo passo a passo. Servidor de email é algo bem
rigoroso, com muitos controles, restrições etc, e para não termos problemas com
blacklists precisaremos ter um ip fixo.
Clique em
Sign up para criar um conta ou
Sign in para acessar sua conta.

Nosso id no no-ip.com e veja ao lado o nosso ip.

Usaremos o no.ip.com, crie a sua conta neste site gratuitamente ou em outro da sua
escolha. Vamos criar um diretório para armazenar os nosso downloads.
mkdir downloads ( enter )
cd downloads/ ( enter )
Se ainda não foi instlaado, instale os progromas make e g++
apt-get install g++ ( enter )
apt-get install make ( enter )
Baixar o arquivo cliente do no.ip.
wget -c http://www.no-ip.com/client/linux/noip-duc-linux.tar.gz ( enter )
Descompatar o arquivo.
tar xvf noip-duc-linux.tar.gz ( enter )
cd noip-2.1.9-1/ ( enter )
Instalando e configurando No-Ip:
root@debian:~/downloads/noip-2.1.9-1#
make && make install ( enter )
make: `noip2' is up to date.
if [ ! -d /usr/local/bin ]; then mkdir -p /usr/local/bin;fi
if [ ! -d /usr/local/etc ]; then mkdir -p /usr/local/etc;fi
cp noip2 /usr/local/bin/noip2
/usr/local/bin/noip2 -C -c /tmp/no-ip2.conf
Auto configuration for Linux client of no-ip.com.
Please enter the login/email string for no-ip.com
linux1.noip@gmail.com
Please enter the password for user 'way@tpa.com.br'
********
Only one host [debian70.no-ip.org] is registered to this account.
It will be used.
Please enter an update interval:[30]
1
Do you wish to run something at successful update?[N] (y/N)
n
New configuration file '/tmp/no-ip2.conf' created.
mv /tmp/no-ip2.conf /usr/local/etc/no-ip2.conf
root@debian:~/instalacoes/noip-2.1.9-1#
Como saber onde está o no-ip?
whereis noip2 ( enter )
noip2: /usr/local/bin/noip2
Para executar o cliente do noip2.
/usr/local/bin/noip2& ( enter )
[1] 5098
Vamos verificar se o processo do no-ip esta rodando.
ps aux | grep noip2 ( enter )
nobody 2202 0.0 0.1 18592 908 ? Ss 00:39 0:00 /usr/local/bin/noip2
root 2537 0.0 0.1 7608 960 pts/0 S+ 00:45 0:00 grep --color noip2
Vamos nos conectar no servidor local com o usuário
jura para testarmos o ssh.
ssh –l jura localhost ( enter )
jura@localhost's password:
123
The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.
Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
You have mail.
Last login: Fri May 20 09:51:37 2016 from 192.168.1.100
jura@Debian:~$
jura@Debian:~$
su ( mudando para root )
Password:
123
root@Debian:/home/jura#
root@Debian:/home/jura#
cd
root@Debian:~#
root@Debian:~#
Agora vamos adicionar a linha que carrega o no.ip no arquivo boot
rc.begin , pois se o
servidor cair ou for reiniciado carregue sempre o no.ip pois com ele poderemos
acessar nosso servidor remotamente.
nano /etc/init.d/rc.begin ( enter )
#!/bin/bash
clear
echo ''
echo '============================================='
echo ''
# ip forward = faz o bypass do compartilhamento e ativa o roteamento no kernel
modprobe iptable_nat
echo 1 >/proc/sys/net/ipv4/ip_forward
echo 'IP forward .......................... [ ok ] '
echo ''
/usr/local/bin/noip2&
echo 'Inicializando o servico ( noip2 ).... [ ok ] '
echo ''
echo '============================================='
echo ''
ctrl + x + y + enter ( salvar e sair do arquivo )
Vamos reiniciar o servidor para testarmos se o no.ip foi carregado
shutdown –r now ( enter )
Vamos verificar se o processo do no-ip foi carregado com sucesso.
ps aux | grep noip2 ( enter )
nobody 2202 0.0 0.1 18592 908 ? Ss 00:39 0:00 /usr/local/bin/noip2
root 2537 0.0 0.1 7608 960 pts/0 S+ 00:45 0:00 grep --color noip2
Testando no-ip.
ping debian70.no-ip.org ( enter )
PING debian70.no-ip.org (201.3.233.130) 56(84) bytes of data.
64 bytes from 201-3-233-130.bnut3702.dsl.brasiltelecom.net.br (201.3.233.130): icmp_req=1 ttl=64 time=1.08 ms
64 bytes from 201-3-233-130.bnut3702.dsl.brasiltelecom.net.br (201.3.233.130): icmp_req=2 ttl=64 time=0.547 ms
No-ip - reconfiguando
Se precisarmos reconfigurar o no.ip use a linha abaixo.
./downloads/noip-2.1.9-1/noip2 -c CONFIG –C ( enter )
10 - Modem - liberando portas 
Para acessar o servidor da rede externa teremos que liberar a porta 22 no arquivo de
de configuração do ssh no modem. Como usaremos outras portas em breve vamos liberar as
portas:
Servidor..:
192.168.1.13
Ssh.......:
22
Apache....:
8080
FTP.......:
50000 ( não usaremos a porta 21 padrão )
Webmin....:
10000
Modem no modo router
Precisaremos liberar no modem algumas portas para acessarmos da rede externa o nosso
servidor na VirtualBox com o ssh, apache, FTP e webmin etc...

Acessando da rede externa com o usuário jura e após mudando para super usuário.
ssh –l jura debian70.no-ip.org -p22 ( enter )
Acessando da rede externa com o usuário
jura e após mudando para super usuário.

Acessando da rede externa com o usuário
jura e após mudando para super usuário.
11 - O que é "apt-get"? 
"Apt-get" vem da palavra "APplicaTion-GETting"
O apt-get “automatiza” o processo de instalação de um pacote.
Utilizado em distribuições Debian, Ubuntu e seus derivados para instalar e remover
programas.
Atualiza a lista de pacotes dos repositórios.
apt-get update
Hit http://security.debian.org jessie/updates InRelease
Ign http://debian.pop-sc.rnp.br jessie InRelease
Hit http://debian.pop-sc.rnp.br jessie-updates InRelease
Hit http://security.debian.org jessie/updates/main Sources
Hit http://debian.pop-sc.rnp.br jessie Release.gpg
Hit http://security.debian.org jessie/updates/main amd64 Packages
Hit http://debian.pop-sc.rnp.br jessie-updates/main Sources
Hit http://security.debian.org jessie/updates/main Translation-en
Get:1 http://debian.pop-sc.rnp.br jessie-updates/main amd64 Packages/DiffIndex [3,472 B]
Get:2 http://debian.pop-sc.rnp.br jessie-updates/main Translation-en/DiffIndex [1,720 B]
Hit http://debian.pop-sc.rnp.br jessie Release
Hit http://debian.pop-sc.rnp.br jessie/main Sources
Hit http://debian.pop-sc.rnp.br jessie/main amd64 Packages
Hit http://debian.pop-sc.rnp.br jessie/main Translation-en
Fetched 5,192 B in 2s (2,406 B/s)
Reading package lists... Done
Atualiza todos os programas do Sistema.
apt-get upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Ou
apt-get update && apt-get upgrade
Instalar pacotes de programas.
apt-get install htop
Reading package lists... Done
Building dependency tree
Reading state information... Done
Suggested packages:
strace ltrace
The following NEW packages will be installed:
htop
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 0 B/75.3 kB of archives.
After this operation, 209 kB of additional disk space will be used.
Selecting previously unselected package htop.
(Reading database ... 34839 files and directories currently installed.)
Preparing to unpack .../htop_1.0.3-1_amd64.deb ...
Unpacking htop (1.0.3-1) ...
Processing triggers for mime-support (3.58) ...
Processing triggers for man-db (2.7.0.2-5) ...
Setting up htop (1.0.3-1) ...
root ~ #
Desinstalando o programa.
apt-get remove htop
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages will be REMOVED:
htop
0 upgraded, 0 newly installed, 1 to remove and 0 not upgraded.
After this operation, 209 kB disk space will be freed.
Do you want to continue? [Y/n] y
(Reading database ... 34850 files and directories currently installed.)
Removing htop (1.0.3-1) ...
Processing triggers for man-db (2.7.0.2-5) ...
Processing triggers for mime-support (3.58) ...
apt-get ( enter )
apt 1.0.9.8.3 for amd64 compiled on Mar 12 2016 13:31:17
Usage: apt-get [options] command
apt-get [options] install|remove pkg1 [pkg2 ...]
apt-get [options] source pkg1 [pkg2 ...]
apt-get is a simple command line interface for downloading and
installing packages. The most frequently used commands are update
and install.
Commands:
update - Retrieve new lists of packages
upgrade - Perform an upgrade
install - Install new packages (pkg is libc6 not libc6.deb)
remove - Remove packages
autoremove - Remove automatically all unused packages
Procurar pacotes apenas pelo nome.
apt-cache search --names-only ssh ( enter )
aolserver4-nssha1 - AOLserver4 module: performs SHA1 hashes Provides a Tcl
autossh - Automatically restart SSH sessions and tunnels
clusterssh - administer multiple ssh or rsh shells simultaneously
crosshurd - Install a Debian system
dropbear - lightweight SSH2 server and client
erlang-ssh - Erlang/OTP implementation of SSH protocol
fusiondirectory-plugin-ssh - ssh plugin for FusionDirectory
fusiondirectory-plugin-ssh-schema - LDAP schema for FusionDirectory ssh plugin
libganymed-ssh2-java - pure Java implementation of the SSH-2 protocol
gosa-plugin-ssh - ssh plugin for GOsa²
gosa-plugin-ssh-schema - LDAP schema for GOsa² ssh plugin
gpsshogi - Shogi playing program based on OpenShogiLib
Saber status do cache, como versões distintas, dependências. Comando rodado logo após
a instalação do Debian.
apt-cache stats ( enter )
Total package names: 54137 (1,083 k)
Total package structures: 54140 (3,032 k)
Normal packages: 41892
Pure virtual packages: 419
Single virtual packages: 4691
Mixed virtual packages: 357
Missing: 6781
Total distinct versions: 43149 (3,107 k)
Total distinct descriptions: 84507 (2,028 k)
Total dependencies: 268307 (7,513 k)
Total ver/file relations: 44347 (1,064 k)
Total Desc/File relations: 84507 (2,028 k)
Total Provides mappings: 7397 (148 k)
Total globbed strings: 75 (589 )
Total dependency version space: 1,088 k
Total slack space: 69.8 k
Total space accounted for: 14.9 M
Desinstalando ssh.
apt-get remove --purge ssh ( enter )
12 - O que é um pacote ".deb"? 
Para entender isso você terá que conhecer uma das mais antigas e estáveis distribuições
Linux chamada Debian ( Por isso do DEB), o debian desenvolveu um sistema de
empacotamento de software para facilitar a instalação de programas no Linux, esse
empacotamento ganho o nome de DEB, assim o arquivo neste formato tem o nome
"programa.deb".
Para instalar um pacote com o dpkg, precisamos ter o pacote.deb salvo em algum lugar
da máquina. O parâmetro para instalar é simples, porém o dpkg NÃO resolve dependências,
ou seja, caso o pacote que você está instalando dependa de outros, eu aconselho
profundamente a usar o apt-get para resolver tais dependências.
Para remover um pacote no formato 'deb' removendo também todos os arquivos de
configuração relacionados ao pacote.
dpkg -p nome_do_pacote
dpkg --purge nome_do_pacote
dpkg -i Instala pacotes
dpkg -r Desinstala pacotes
dpkg -l Lista pacotes instalados
dpkg -p Mostra informações sobre um pacote
dpkg -p postfixadmin ( enter ) ( se estiver instalado )
dpkg --list | grep postfixadmin ( enter ) ( se estiver instalado )
Lista pacotes instalados.
dpkg –l ( enter )
Para exibir todos os pacotes instalados que contenham em seu nome a palavra postfix
dpkg -l | grep postfix ( enter )
Para obter uma lista de pacotes instalados no sistema:
dpkg --get-selections ( enter )
initscripts install
insserv install
install-info install
installation-report install
iproute install
iptables install
iputils-ping install
isc-dhcp-client install
isc-dhcp-common install
isc-dhcp-server install
kbd install
keyboard-configuration install
klibc-utils install
laptop-detect install
libacl1 install
.deb - reconfigurando
Se precisar reconfigurar algum aplicativo já instalado / configurado.
dpkg-reconfigure phpmyadmin ( enter )
dpkg-reconfigure postfix ( enter )
13 - Programas essências no servidor 
Alguns programas essênciais que precisaremos instalar no servidor, porém logo após o
uso e se não precisar mais destes, remova-os por segurança !
Para compactar e descompactar arquivos .tar.bz2 , precisaremos do bzip2 .
apt-get install bzip2 ( enter )
Vamos verificar onde esta o programa instalado.
whereis bzip2 ( enter )bzip2: /bin/bzip2 /usr/share/man/man1/bzip2.1.gz
Editores de texto mais amigáveis.
apt-get install mc vim ( enter )
Compilador ( já instalamos estes quando configuramos o no-ip )
apt-get install gcc make g++ ( enter )
Por razoes de segurança sempre remova os programas que não utilizar mais.
apt-get remove make ( enter )
apt-get remove g++ ( enter )
O comando ps trabalha como se tirasse uma fotografia da situação dos processos naquele
momento. O comando top, por sua vez, coleta as informações, mas as atualiza
regularmente. Geralmente essa atualização ocorre a cada 10 segundos.
shift + u
Selecione usuario ( www-data , proxy, named, mail, postfix )
shift + m
Ordenar processos que mais usa memória ao menor.
shift + p
Lista processos que mais consomem processamento.
shift + z
Será mostrada a tela abaixo, podemos ajustar a configuração do top facilmente, definir
cor etc...
Com o iftop teremos um panorama geral de todas as conexões ativas, de todas as
interfaces de rede que estejam trafegando dados e todos os protocolos utilizados neste
exato momento. Além dos dados quantitativos o programa gera gráficos em barra e os
atualiza automaticamente a cada 10 segundos ou por um período que você pode determinar.
iftop
Programa mais amigável de verificação de "consumo de memória, cpu , swap e processo do
sistema".
apt-get install htop ( enter )
htop ( enter )
Monitorando a banda.
apt-get install bwm-ng ( enter )
bwm-ng ( enter )
apt-get install glances ( enter )
glances ( enter )
14 - Terminal - configurando cores 
Se preferir, este arquivo permite definir cores no Shell. A parte trabalhosa é digitar
o código abaixo.
nano ~/.bashrc ( enter )
PS1='\[\e[1;32m\]\u \[\e[1;34m\]\w \[\e[1;32m\]\$ \[\e[0;37m\] '
alias ls="ls --color=auto --time-style=long-iso"
alias grep='grep --color'
alias c=clear
alias x=startx
alias m=mutt
alias svi='sudo vim'
alias ci='vim'
alias reboot='sudo /sbin/reboot'
alias halt='sudo /sbin/halt'
alias lock="clear && vlock -c"
alias rd='cd "`pwd -P`"'
alias tp='trash-put'
alias root='sudo bash -l'
alias kernbuild='make -j3 && make modules_install && ls -ld ../linux && date'
alias bt='aria2c --max-upload-limit=10K --seed-time=60 --listen-port=8900-8909'
alias xevs="xev | grep 'keycode\|button'"
alias daggerfall='dosbox -conf ~/.dosbox.conf.daggerfall'
function s() { eix -Fc "$1"; }
function sd() { eix -FsSc "$1"; }
function se() { eix -F "^$1\$"; }
function si() { eix -FIc "$1"; }
function cifsmount() { sudo mount -t cifs -o username=${USER},uid=${UID},gid=${GROUPS} $1 $2; }
function cifsumount() { sudo umount $1; }
function randpass() {
if [ "$2" == "0" ]; then
cat /dev/urandom | tr -cd '[:alnum:]' | head -c ${1:-32}
else
cat /dev/urandom | tr -cd '[:graph:]' | head -c ${1:-32}
fi
echo
}
function o3() { unzip -p "$1" content.xml | o3totxt | utf8tolatin1; }
function li() { locate -i "$1" | grep -i --color "$1"; }
function l() { locate "$1" | grep --color "$1"; }
function eview() {
FILE=$(equery which $1)
if [ -f "$FILE" ]; then
view $FILE
fi
}
function echange() {
PACKAGE="$(eix -e --only-names $1)"
if [ "$PACKAGE" != "" ]; then
view /usr/portage/$PACKAGE/ChangeLog
fi
}
function i() {
EXT=`echo "${1##*.}" | sed 's/\(.*\)/\L\1/'`
if [ "$EXT" == "mp3" ]; then
id3v2 -l "$1"
echo
mp3gain -s c "$1"
elif [ "$EXT" == "flac" ]; then
metaflac --list --block-type=STREAMINFO,VORBIS_COMMENT "$1"
else
echo "ERRO: Tipo de arquivo não suportado..."
fi
}
function cn() { for i in *.mp3; do id3v2 --TXXX "Catalog Number":"$1" "$i"; done; }
ctrl x + y + enter ( salvar e sair do arquivo )
15 - Comandos comumente utilizados 
Afim de mantermos organizado nossos downloads sugiro criarmos um diretório chamado de
downloads e mantermos estes arquivos neste diretório. Se a organização for feita desde
o início tornará nosso trabalho prático
Cria diretório.
mkdir downloads ( enter )
Entra no diretório.
cd downloads ( enter )
Sai do diretório.
cd ( enter )
Listar arquivos.
ls
Cria um diretório.
mkdir
Cria o diretório casa.
mkdir casa
Remove um diretório vazio.
rmdir
Remove o diretório casa.
rmdir casa
Apaga todos os arquivos e sub-diretórios.
rm -r casa/
Apaga todos os arquivos de um diretório.
rm *
Apaga o arquivos arq.txt.
rm arq.txt
Exibe o diretório atual.
pwd
Sai do diretório casa.
cd casa/
Mostra qual diretório se encontra.
pwd
/root/casa
Entra no diretório casa.
cd casa
Sai de um diretório.
cd
Filtra processo do ssh ( pid )
ps ax | grep nmbd
1117 ? Ss 0:01 /usr/sbin/nmbd -D
1118 ? S 0:00 /usr/sbin/nmbd -D
10007 pts/0 S+ 0:00 grep nmbd
Mata processo.
kill -9 nmbd
ps ax | grep nmbd
Lista os diretórios, arquivos oculto e executáveis.
ls -a
Mostra o diretório corrente
pwd
Volta para o diretório anterior
cd -
Volta um diretório acima
cd ..
Volta para seu diretório /home
cd ~
Renomeia arquivo e pasta.
mv [arquivo1] [arquivo2]
Move o arquivo para um determinado caminho.
mv [arquivo] [caminho]
Cria um link
ln -s [caminho] [link]
ln -s /usr/bin/limewire limewire
Cria novo arquivo
cat > [arquivo]
touch [arquivo]
Acrescenta arq.2 em arq.1
cat [arquivo1] >> [arquivo2]
cat teste1 >> teste2
Mostra as primeiras linhas de um arquivo.
head [-linhas] [arquivo]
head -10 texto.txt
Faz o contrário do comando anterior.
tail [-linhas] [arquivo]
tail -20 texto.txt
Muda o nome de um comando.
alias [comando/atual] [comando_novo]
alias dir=ls -l
Lista os últimos 500 comandos que você digitou.
history
history | grep ssh
Limpa todo o histórico
history –C
Muda para o super usuário root, precisa da senha.
su
Muda para outro usuário, também necessita da senha.
su [usuário]
Troca senha.
passwd
Adiciona um usuário no sistema, requer root.
adduser
Deleta um usuário, requer root.
userdel [usuário]
Deleta o usuário e sua pasta que se encontra no diretório /home, requer root.
userdel -r [usuário]
Descompacta um arquivo em formato .tar.gz
tar -zxvf jurandir.tar.gz
Descompacta um arquivo no formato .tar.bz2
tar -jxvf jurandir.tar.bz2
Mostra o tempo desde do último boot.
uptime
Localiza o caminho de um executável/comando.
whereis ssh
ssh: /usr/bin/ssh /etc/ssh /usr/share/ssh /usr/share/man/man1/ssh.1.gz
Mostra quem está conectado ao sistema nesse momento.
who
Faz download de arquivo na internet)
wget -c [URL]
wget -c http://www.link.do.download
Mostra quem se logou primeiro no sistema.
whoami
Lista grupos
cat /etc/group
Mostra capacidade do disco rígido ( hd )
fdisk -l | grep -iE 'mb|gb|tb'
Listando arquivo sshd_config sem as linhas comentadas "#"
grep -v ^# /etc/ssh/sshd_config
Lista arquivos na ordem inversa, do “maior” para “menor”
find . -type f -print0 | xargs -0 du -h | sort -hr | head -20
find -type f -exec du -sh {} + | sort -rh | head
Lista somente diretórios.
ls -F $1 | grep \/ | sed -e 's/\/$/4/g'
Retorna tamanho do diretório.
du -sch /var
Achar e derrubar outro user root : )
who -uH
ps aux | grep pts/1
kill -9 2104
Procura no disco rígido inteiro a string “noip2”
find / -type f -print0 | xargs -0 grep -Hn -C2 "noip2"
Verificar no log do sistema se há algum problema no servidor.
tail -f /var/log/syslog
tail -f /var/log/messages
Adicionar usuário.
adduser eric
Apagar apenas o usuário.
deluser eric
Apagar o usuário e o diretorio no home.
userdel -r eric
Instalando proftpd.
apt-get install proftpd
Desistalando + depedencias do proftpd.
apt-get remove --purge proftpd
apt-get clean
df -h | grep '^/dev/'
/dev/sda1 7.4G 1.2G 5.9G 16% /
df -Ph | grep '^/dev/' | sed 's/ */\t/' | expand -t32
/dev/sda1 7.4G 1.2G 5.9G 16% /
df -hT /home
Filesystem Type Size Used Avail Use% Mounted on
/dev/sda1 ext4 7.4G 1.2G 5.9G 16% /
Criando diretório aluno.
mkdir /home/aluno
Vamos criar o arquivo linux.class.txt dentro do diretório aluno.
nano /home/jura/linux_class.txt
Hello
Linux class.
by Jurandir
ctrl + x + y + enter ( salvar e sair do arquivo )
Listando arquivo criado.
ls /home/aluno/ -l
total 8
drwxr-xr-x 6 jura jura 4096 2016-05-24 10:37 demoCA
-rw-r--r-- 1 root root 34 2016-05-24 11:34 linux_class.txt
Visualizando conteúdo do arquivo texto com o comando “cat”
cat /home/aluno/linux_class.txt
Hello
Linux class
by Jurandir
Mudar de “root” para o usuário “aluno” – tem restrição para executar comandos.
root@debian:~#
root@debian:~#
su - jura
jura@debian:~$
jura@debian:~$
Mudar de “usuário aluno” para “root” – este é super usuário e pode executar todos
os camandos.
jura@debian:~$
jura@debian:~$
su
Password:
senha
root@debian:/home/aluno#
root@debian:/home/aluno#
Retorna ip externo.
dig o-o.myaddr.l.google.com @ns1.google.com txt +short
"187.5.183.149"
hostname -I
192.168.1.13
Informação do HD.
ls -l /dev/disk/by-id/ | grep '/sda$' | grep -o 'ata[^ ]*'
ata-ST3500418AS_5VMFV6PB
Informações do processador.
grep 'model\|MHz' /proc/cpuinfo | tail -n 2
model name : Intel(R) Core(TM) i5-4440 CPU @ 3.10GHz
cpu MHz : 2966.985
Lista ip interno e externo.
ifconfig | sed -n 's/.*inet addr:\([0-9.]\+\)\s.*/\1/p'
192.168.1.13
127.0.0.1
apt-get install awk
Listando serviços que estão rodando.
ps aux |awk '{$1} {++P[$1]} END {for(a in P) if (a !="USER") print a,P[a]}'
Debian-+ 1
statd 1
jura 12
nobody 1
root 80
daemon 1
message+ 1
du -h --time --max-depth=1 | sort -hr
792K 2016-05-24 11:13 .
728K 2016-05-23 18:15 ./downloads
24K 2016-05-24 10:38 ./demoCA
8.0K 2016-05-23 21:31 ./.mutt
4.0K 2016-05-23 18:16 ./.ssh
du --max-depth=1 -h * | sort -h -k 1 | egrep '(M|G)\s'
17M instalacoes/webmail
74M instalacoes/webmin-1.630
116M instalacoes
Lista arquivos dos maiores para menores.
du -sh /home/* | sort –rh | head -n 10
55M /home/lixeira_smb
52M /home/computing_smb
7.6M /home/aluno1_smb
3.8M /home/mail
20K /home/ewb
alias du1="du -xsm * | sort -n | awk '{ printf(\"%4s MB ./\",\$1) ;
for (i=1;i<=NF;i++) { if (i>1) printf(\"%s \",\$i) } ; printf(\"\n\") }' | tail"
du1
1 MB ./instalacoes
Mostra todas informações referente as entradas (login) e saídas (logout) de usuários
do sistema.
last -a
jura pts/1 Tue May 24 11:14 still logged in 192.168.1.100
jura pts/2 Tue May 24 09:53 still logged in 191.52.240.89
jura pts/1 Tue May 24 09:49 - 11:13 (01:24) 192.168.1.100
jura pts/0 Tue May 24 09:48 still logged in 192.168.1.100
reboot system boot Tue May 24 09:42 - 11:38 (01:56) 3.16.0-4-amd64
jura pts/1 Mon May 23 18:49 - down (02:52) 192.168.1.100
jura pts/0 Mon May 23 18:20 - down (03:21) 192.168.1.100
reboot system boot Mon May 23 18:18 - 21:41 (03:23) 3.16.0-4-amd64
jura pts/0 Mon May 23 18:01 - down (00:16) 192.168.1.100
Exibe informações mostrando o endereço IP da maquina de onde foi efetuado os logins.
last -d
jura pts/1 192.168.1.100 Tue May 24 11:14 still logged in
jura pts/2 191.52.240.89 Tue May 24 09:53 still logged in
jura pts/1 192.168.1.100 Tue May 24 09:49 - 11:13 (01:24)
jura pts/0 192.168.1.100 Tue May 24 09:48 still logged in
root tty1 0.0.0.0 Tue May 24 09:48 still logged in
reboot system boot 0.0.0.0 Tue May 24 09:42 - 11:39 (01:56)
jura pts/1 192.168.1.100 Mon May 23 18:49 - down (02:52)
jura pts/0 192.168.1.100 Mon May 23 18:20 - down (03:21)
lastlog
Username Port From Latest
root tty1 Tue May 24 09:48:22 -0300 2016
daemon **Never logged in**
bin **Never logged in**
sys **Never logged in**
sync **Never logged in**
games **Never logged in**
man **Never logged in**
lp **Never logged in**
mail **Never logged in**
news **Never logged in**
uucp **Never logged in**
proxy **Never logged in**
www-data **Never logged in**
backup **Never logged in**
list **Never logged in**
irc **Never logged in**
gnats **Never logged in**
dmesg | grep -i cpu
[ 0.000000] Initializing cgroup subsys cpuset
[ 0.000000] Initializing cgroup subsys cpu
[ 0.000000] Initializing cgroup subsys cpuacct
[ 0.000000] x86 PAT enabled: cpu 0, old 0x7040600070406, new 0x7010600070106
[ 0.000000] CPU MTRRs all blank - virtualized system.
[ 0.000000] ACPI: SSDT 0x000000003FFF02A0 0001CC (v01 VBOX VBOXCPUT 00000002 INTL 20100528)
[ 0.000000] smpboot: Allowing 1 CPUs, 0 hotplug CPUs
[ 0.000000] setup_percpu: NR_CPUS:512 nr_cpumask_bits:512 nr_cpu_ids:1 nr_node_ids:1
[ 0.000000] PERCPU: Embedded 27 pages/cpu @ffff88003fc00000 s80896 r8192 d21504 u2097152
[ 0.000000] pcpu-alloc: s80896 r8192 d21504 u2097152 alloc=1*2097152
[ 0.000000] pcpu-alloc: [0] 0
[ 0.000000] RCU restricting CPUs from NR_CPUS=512 to nr_cpu_ids=1.
[ 0.000000] RCU: Adjusting geometry for rcu_fanout_leaf=16, nr_cpu_ids=1
[ 0.009099] mce: CPU supports 0 MCE banks
[ 0.077631] smpboot: CPU0: Intel(R) Core(TM) i5-4440 CPU @ 3.10GHz (fam: 06, model: 3c, stepping: 03)
[ 0.080000] Performance Events: unsupported p6 CPU model 60 no PMU driver, software events only.
[ 0.080000] x86: Booted up 1 node, 1 CPUs
[ 0.080000] NMI watchdog: disabled (cpu0): hardware events not enabled
[ 0.080000] cpuidle: using governor ladder
[ 0.080000] cpuidle: using governor menu
[ 0.310263] microcode: CPU0 sig=0x306c3, pf=0x2, revision=0x19
[ 0.313491] ledtrig-cpu: registered to indicate activity on CPUs
tail /var/log/syslog
May 24 09:47:56 debian rsyslogd: [origin software="rsyslogd" swVersion="8.4.2" x-pid="426" x-info="http://www.rsyslog.com"] rsyslogd was HUPed
May 24 09:47:57 debian anacron[413]: Job `cron.daily' terminated
May 24 09:47:57 debian anacron[413]: Normal exit (1 job run)
May 24 10:01:04 debian exim4[2179]: Stopping MTA:.
May 24 10:01:05 debian exim4[2182]: Starting MTA: exim4.
May 24 10:04:12 debian fetchmail[2782]: Not starting fetchmail daemon, disabled via /etc/default/fetchmail.
May 24 10:17:02 debian CRON[2832]: (root) CMD ( cd / && run-parts --report /etc/cron.hourly)
May 24 11:17:01 debian CRON[2997]: (root) CMD ( cd / && run-parts --report /etc/cron.hourly)
Cor no terminal do Debian digite comando abaixo:
echo -e "\e[1;34;47;01m DEBIAN \e[1;33;40;02m Linux Class - by Jurandir \e[0m"
Color: Foreground: Background:
black 30 40
red 31 41
green 32 42
yellow 33 43
blue 34 44
magenta 35 45
cyan 36 46
white 37 47
Procurando arquivos com as terminações entre aspas duplas na linha abaixo.
find . \( -name "*.c" -o -name "*.h" -o -name "*.sc" -o -name "*.ini" \) –print
./instalacoes/noip-2.1.9-1/noip2.c
./instalacoes/noip-2.1.9-1/._noip2.c
Lista os 10 maiores arquivos no servidor.
find / -type f 2>/dev/null | xargs du 2>/dev/null | sort -n | tail -n 10 | cut -f 2
| xargs -n 1 du -h
./downloads/noip-2.1.9-1/._noip2.c
./downloads/noip-2.1.9-1/noip2.c
Verificando espaço usado no disco pelos arquivos e diretórios.
du -h /var/cache/apt/
4.0K /var/cache/apt/archives/partial
49M /var/cache/apt/archives
95M /var/cache/apt/
du -h /var/log
14M /var/log/installer/cdebconf
14M /var/log/installer
8.0K /var/log/exim4
12K /var/log/fsck
144K /var/log/apt
16M /var/log
Listando os camandos mais usados.
du -sh .[!.]* * | sort -hr | grep -v '^0'
728K downloads
24K demoCA
8.0K .mutt
4.0K .ssh
4.0K sent
4.0K .profile
4.0K .muttrc
4.0K dead.letter
4.0K .bashrc
4.0K .bash_history
du -h /var/* | sort -nr | head
756K /var/lib/mlocate
716K /var/backups
496K /var/lib/usbutils
228K /var/mail
208K /var/lib/dpkg/alternatives
148K /var/log/apt
132K /var/lib/systemd
113M /var/lib
103M /var/cache
95M /var/cache/apt
du -h /home/
4.0K /home/jura/demoCA/crl
4.0K /home/jura/demoCA/private
4.0K /home/jura/demoCA/newcerts
4.0K /home/jura/demoCA/certs
8.0K /home/jura/demoCA
32K /home/jura
4.0K /home/
Lista todos arquivos, exceto arquivos terminados com ".txt"
du -ah --exclude="*.txt" /home/
Lista data e hora.
du -ha --time /home/
4.0K 2016-05-22 16:00 /home/jura/.profile
4.0K 2016-05-24 10:37 /home/jura/demoCA/crl
4.0K 2016-05-24 10:37 /home/jura/demoCA/private
4.0K 2016-05-24 10:37 /home/jura/demoCA/newcerts
4.0K 2016-05-24 10:37 /home/jura/demoCA/crlnumber
4.0K 2016-05-24 10:37 /home/jura/demoCA/certs
24K 2016-05-24 10:37 /home/jura/demoCA
4.0K 2016-05-24 11:34 /home/jura/linux_class.txt
4.0K 2016-05-24 10:45 /home/jura/.fetchmail.pid
4.0K 2016-05-24 10:45 /home/jura/.fetchmailrc
4.0K 2016-05-22 16:00 /home/jura/.bashrc
4.0K 2016-05-24 11:13 /home/jura/.bash_history
4.0K 2016-05-22 16:00 /home/jura/.bash_logout
56K 2016-05-24 11:34 /home/jura
60K 2016-05-24 11:34 /home/
find / -name "lost+found" | xargs du -h
16K /lost+found
Procura palavras com o termo "Hello" no diretorio home.
grep -r -H "Hello" /home
/home/jura/linux_class.txt:Hello
egrep -w -R 'Hello|bie' /home
/home/jura/linux_class.txt:Hello
Localizando a string "amigos" em "/var/www/"
grep -ri "amigos" /var/www/
/var/www/amigos.php:$query = "SELECT * FROM amigos ORDER BY nome";
Lista os maiores arquivos em Mb dos maiores para os menores.
find /var -type f | xargs ls -s | sort -rn | awk '{size=$1/1024;
printf("%dMb %s\n", size,$2);}' | head
32Mb /var/lib/apt/lists/debian.pop-sc.rnp.br_debian_dists_jessie_main_binary-amd64_Packages
31Mb /var/lib/apt/lists/debian.pop-sc.rnp.br_debian_dists_jessie_main_source_Sources
22Mb /var/cache/apt/srcpkgcache.bin
22Mb /var/cache/apt/pkgcache.bin
21Mb /var/lib/apt/lists/debian.pop-sc.rnp.br_debian_dists_jessie_main_i18n_Translation-en
20Mb /var/cache/apt/archives/g++-4.9_4.9.2-10_amd64.deb
13Mb /var/log/installer/cdebconf/templates.dat
5Mb /var/cache/apt/archives/gcc-4.9_4.9.2-10_amd64.deb
4Mb /var/cache/apt/archives/cpp-4.9_4.9.2-10_amd64.deb
3Mb /var/cache/apt/archives/binutils_2.25-5_amd64.deb
Lista arquivos editados nos ultimos 15 dias com tamanho ate 15 mb no diretorio home.
find /home/ -name '*.docx' -a -size +15M -mtime -15
/home/computing_smb/Linux/Linux - new2.docx
/home/lixeira_smb/ewb1/Linux - new.docx
/home/lixeira_smb/ewb1/_Linux - d 7 - 1 - 000 - 489.docx
/home/lixeira_smb/ewb1/Linux - new2.docx
find /var/www -type f | grep -i "\.gif$"
/var/www/dir1/dlf/fh10.gif
/var/www/dir1/dlf/real.gif
/var/www/dir1/dlf/fla.gif
/var/www/dir1/dlf/gif.gif
/var/www/dir1/dlf/xls.gif
find / -name '*.doc' -o -name '*.conf' -print
/etc/proftpd/ldap.conf
/etc/proftpd/virtuals.conf
/etc/proftpd/modules.conf
/etc/proftpd/tls.conf
/etc/proftpd/sql.conf
/etc/gtk-2.0/im-multipress.conf
/etc/ucf.conf
/etc/selinux/semanage.conf
/etc/ldap/ldap.conf
find . -size +3M -print
./instalacoes/webmin-1.720.tar.gz
./instalacoes/squid-3.4.10.tar.gz
grep '^jura' /etc/passwd
jura:x:1000:1000:jura,,,:/home/jura:/bin/bash
grep '^ftp1' /etc/passwd
ftp1:x:1001:1001:,,,:/home/ftp1:/bin/bash
16 - Postfix + Squirrelmail + Roundcube + SASL + Amavis + ClamV 
O Postfix é um MTA (Mail Transfer Agent) responsável pelo envio e recebimento das
mensagens entre servidores, quando de cara para internet e configurado para resonder
por um domínio, não entrega as mensagens aos clientes de e-mail (POP3), não baixa as
mensagens de outros servidores, recebe quando enviadas diretamente a ele mas não vai
buscar em outros servidores, não tem anti-viruse outros filtros utilizados em
servidores de e-mail, precisa de outros pacotes que se integram ao Postfix para
configurar o que chamamos de servidor de e-mail.
O Squirrelmail é um script de webmail escrito em php, que permite acessar as mensagens
de um servidor imap via web. Ele é bem leve, tanto do ponto de vista dos recursos
utilizados no servidor, quanto do ponto de vista dos clientes. As páginas geradas pelo
webmail são simples páginas html, sem javascript nem nenhum outro recurso especial.
Isso o torna um campeão de compatibilidade, principalmente com os navegadores usados
em PDAs e browsers antigos.
O RoundCube é um potente webmail client escrito em php, com suporte aos banco de dados
MySQL, PostGreSQL e SQLite. Ele faz uso em diversas funcionalidades de AJAX, o que o
deixa bem dinâmico.
----------------------------------------------------------------
ifconfig
eth0 Link encap:Ethernet HWaddr 08:00:27:66:03:43
inet addr:192.168.2.186 Bcast:192.168.2.255 Mask:255.255.255.0
inet6 addr: fe80::a00:27ff:fe66:343/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:48205 errors:0 dropped:0 overruns:0 frame:0
TX packets:12986 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:35130781 (33.5 MiB) TX bytes:1649285 (1.5 MiB)
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:7412 errors:0 dropped:0 overruns:0 frame:0
TX packets:7412 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:648035 (632.8 KiB) TX bytes:648035 (632.8 KiB)
Se houver 3 linhas comentadas com o character #.
nano /etc/apt/sources.list
deb http://debian.pop-sc.rnp.br/debian/ jessie main
deb-src http://debian.pop-sc.rnp.br/debian/ jessie main
deb http://security.debian.org/ jessie/updates main
deb-src http://security.debian.org/ jessie/updates main
# jessie-updates, previously known as 'volatile'
deb http://debian.pop-sc.rnp.br/debian/ jessie-updates main
deb-src http://debian.pop-sc.rnp.br/debian/ jessie-updates main
ctrl + x + y + enter ( salvar e sair do arquivo )
Atualize o sistema.
apt-get update && apt-get upgrade
Instalando…
apt-get install postfix bind9 apache2
Internet Site ( enter ) - System mail name: juralinux.com.br ( enter )
Ajuste as 3 linhas primeiras linhas.
nano /etc/hosts
127.0.0.1 localhost
127.0.1.1 mail.juralinux.com.br juralinux
192.168.2.172 mail.juralinux.com.br juralinux
ctrl + x + y + enter ( salvar e sair do arquivo )
Descomentar e adicionar dns do google.
nano /etc/bind/named.conf.options
forwarders {
8.8.8.8;
8.8.4.4;
};
ctrl + x + y + enter ( salvar e sair do arquivo )
service bind9 restart && service bind9 status
apt-get install courier-imap courier-imap-ssl courier-pop courier-pop-ssl
yes - ok – enter
ls -l /etc/courier
total 80
-rw-rw---- 1 daemon daemon 3667 Nov 8 2014 authdaemonrc
-rw------- 1 daemon root 201 Mar 24 17:48 dhparams.pem
-rw-r--r-- 1 root root 15320 Jan 25 2015 imapd
-rw------- 1 daemon daemon 350 Jan 25 2015 imapd.cnf
-rw------- 1 daemon root 5419 Mar 24 17:48 imapd.pem ***
-rw-r--r-- 1 root root 9369 Jan 25 2015 imapd-ssl
-rw-r--r-- 1 root root 3760 Jan 25 2015 pop3d
-rw------- 1 daemon daemon 350 Jan 25 2015 pop3d.cnf
-rw------- 1 daemon root 5419 Mar 24 17:48 pop3d.pem ***
-rw-r--r-- 1 root root 8373 Jan 25 2015 pop3d-ssl
drwxr-xr-x 2 daemon daemon 4096 Mar 24 17:48 shared
cd /etc/courier
mv imapd.pem imapd.pem.old
Ajuste o arquivo como no exemplo abaixo.
nano imapd.cnf
RANDFILE = /etc/courier/imapd.rand
[ req ]
default_bits = 4096
encrypt_key = yes
distinguished_name = req_dn
x509_extensions = cert_type
prompt = no
default_md = sha1
[ req_dn ]
C=BR
ST=SC
L=Santa Catarina
O=Courier Mail Server
OU=Automatically-generated IMAP SSL key
CN=localhost
emailAddress=postmaster@juralinix.com.br
[ cert_type ]
nsCertType = server
ctrl + x + y + enter ( salvar e sair do arquivo )
mv pop3d.pem pop3d.pem.old
nano pop3d.cnf
RANDFILE = /etc/courier/pop3d.rand
[ req ]
default_bits = 4096
encrypt_key = yes
distinguished_name = req_dn
x509_extensions = cert_type
prompt = no
default_md = sha1
[ req_dn ]
C=BR
ST=SC
L=Santa Catarina
O=Courier Mail Server
OU=Automatically-generated IMAP SSL key
CN=localhost
emailAddress=postmaster@juralinix.com.br
[ cert_type ]
nsCertType = server
ctrl + x + y + enter ( salvar e sair do arquivo )
nano /etc/postfix/main.cf
myhostname = juralinux.com.br
mydomain = juralinux.com.br
mydestination = juralinux.com.br, mail.juralinux.com.br, localhost
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
home_mailbox = Maildir/
mailbox_command =
smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)
biff = no
append_dot_mydomain = no
readme_directory = no
# TLS parameters
smtpd_use_tls = yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtpd_relay_restrictions = permit_mynetworks,permit_sasl_authenticated,
defer_unauth_destination
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
relayhost =
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
ctrl + x + y + enter ( salvar e sair do arquivo )
service postfix restart && service postfix status
netstat -tap | grep imap
tcp6 0 0 [::]:imaps [::]:* LISTEN 6240/couriertcpd
tcp6 0 0 [::]:imap2 [::]:* LISTEN 6166/couriertcpd
netstat -tan | egrep -w "(25|143|110)"
tcp 0 0 0.0.0.0:25 0.0.0.0:* LISTEN
tcp6 0 0 :::25 :::* LISTEN
tcp6 0 0 :::110 :::* LISTEN
tcp6 0 0 :::143 :::* LISTEN
tcp6 0 0 192.168.2.122:143 192.168.2.136:49527 ESTABLISHED
netstat -plant
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 192.168.2.122:53 0.0.0.0:* LISTEN 8599/named
tcp 0 0 127.0.0.1:53 0.0.0.0:* LISTEN 8599/named
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 453/sshd
tcp 0 0 0.0.0.0:25 0.0.0.0:* LISTEN 8759/master
tcp 0 0 127.0.0.1:953 0.0.0.0:* LISTEN 8599/named
tcp 0 0 0.0.0.0:39004 0.0.0.0:* LISTEN 436/rpc.statd
tcp 0 0 0.0.0.0:111 0.0.0.0:* LISTEN 427/rpcbind
tcp 0 0 127.0.0.1:59227 127.0.0.1:111 TIME_WAIT -
tcp 0 52 192.168.2.122:22 192.168.2.136:49401 ESTABLISHED 732/sshd: jura [pri
tcp6 0 0 :::53 :::* LISTEN 8599/named
tcp6 0 0 :::22 :::* LISTEN 453/sshd
tcp6 0 0 :::25 :::* LISTEN 8759/master
tcp6 0 0 ::1:953 :::* LISTEN 8599/named
tcp6 0 0 :::993 :::* LISTEN 6240/couriertcpd
tcp6 0 0 :::995 :::* LISTEN 6087/couriertcpd
tcp6 0 0 :::60075 :::* LISTEN 436/rpc.statd
tcp6 0 0 :::110 :::* LISTEN 5998/couriertcpd
tcp6 0 0 :::143 :::* LISTEN 6166/couriertcpd
tcp6 0 0 :::111 :::* LISTEN 427/rpcbind
tcp6 0 0 :::80 :::* LISTEN 8826/apache2
tcp6 0 0 192.168.2.122:143 192.168.2.136:49527 ESTABLISHED 8971/imapd
Adicionando usuários.
adduser mike
adduser eric
adduser isa
ls -l /home
drwxr-xr-x 2 eric eric 4096 Mar 27 15:13 eric
drwxr-xr-x 2 isa isa 4096 Mar 27 15:13 isa
drwxr-xr-x 2 jura jura 4096 May 22 2016 jura
drwxr-xr-x 2 mike mike 4096 Mar 27 15:13 mike
Listando usuários.
cut -d: -f1 /etc/passwd
:
:
jura
postfix
bind
eric
isa
mike
Instalando squirrelmail.
apt-get install squirrelmail
Inisira as 2 linhas no final do arquivo.
nano /etc/apache2/apache2.conf
Alias /webmail "/usr/share/squirrelmail/"
DirectoryIndex index.php
ctrl + x + y + enter ( salvar e sair do arquivo )
service postfix restart && service postfix status
service apache2 restart && service apache2 status
Enviando emails teste.
echo "Testing email, by Jura" | mail -s "Test 123" eric@juralinux.com.br
echo "Testing email, by Jura" | mail -s "Test 123" eric@juralinux.com.br
echo "Testing email, by Jura" | mail -s "Test 123" eric@juralinux.com.br
Abrindo browser
http://192.168.2.189/webmail/src/login.php
eric - 123
cat /var/log/mail.log | grep -e "from" | grep -e "@*.br" | awk '{print $7}' | sort | uniq -c | sort -r | head -20
cat /var/log/mail.log | grep -e "status=sent" | grep -e "@*.br" | awk '{print $7}' | sort | uniq -c | sort -r | head -20
cat /var/log/mail.log | grep -e "from" | grep -e "@*.br" | awk '{print $7}' | sort | uniq -c | sort -r | head -20
cat /var/log/mail.log | grep "status=sent" | wc -l
3
cat /var/log/mail.log | grep "status=sent"
cat /var/log/mail.log | grep "status=sent" | grep "Apr 6" | wc –l
20
----------------------------------------------------------------
cat /var/log/mail.log | grep "1[3-3]:52"
Apr 6 13:52:23 mail postfix/master[2079]: terminating on signal 15
Apr 6 13:52:23 mail postfix/master[2391]: daemon started -- version 2.11.3, configuration /etc/postfix
Apr 6 13:52:31 mail dovecot: master: Warning: Killed with signal 15 (by pid=1 uid=0 code=kill)
Apr 6 13:52:31 mail dovecot: anvil: Warning: Killed with signal 15 (by pid=1 uid=0 code=kill)
Apr 6 13:52:31 mail dovecot: log: Warning: Killed with signal 15 (by pid=1 uid=0 code=kill)
----------------------------------------------------------------
telnet localhost 25
Trying ::1...
Connected to localhost.
Escape character is '^]'.
220 juralinux.com.br ESMTP Postfix (Debian/GNU)
ehlo juralinux
250-juralinux.com.br
250-PIPELINING
250-SIZE 10240000
250-VRFY
250-ETRN
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN
quit
221 2.0.0 Bye
Connection closed by foreign host.
----------------------------------------------------------------
telnet localhost 25
Trying ::1...
Connected to localhost.
Escape character is '^]'.
220 juralinux.com.br ESMTP Postfix (Debian/GNU)
helo juralinux.com.br
250 juralinux.com.br
mail from: eric@juralinux.com.br
250 2.1.0 Ok
rcpt to: isa@juralinux.com.br
250 2.1.5 Ok
data
354 End data with
.
Hello
Test 1 2 3
.
250 2.0.0 Ok: queued as BA08120717
quit
221 2.0.0 Bye
Connection closed by foreign host.
----------------------------------------------------------------
telnet localhost 143
Trying ::1...
Connected to localhost.
Escape character is '^]'.
* OK [CAPABILITY IMAP4rev1 UIDPLUS CHILDREN NAMESPACE THREAD=ORDEREDSUBJECT
THREAD=REFERENCES SORT QUOTA IDLE ACL ACL2=UNION STARTTLS] Courier-IMAP ready.
Copyright 1998-2011 Double Precision, Inc. See COPYING for distribution information.
----------------------------------------------------------------
Verificando arquivos de log.
tail /var/log/mail.log
tail -f /var/log/mail.err
tail -f /var/log/mail.info
tail -f /var/log/mail.warn
tail -f /var/log/syslog
----------------------------------------------------------------
Espaço de disco usado pelo usuário eric.
du -ch /home/eric/
4.0K /home/eric/Maildir/tmp
4.0K /home/eric/Maildir/cur
100K /home/eric/Maildir/new
112K /home/eric/Maildir
4.0K /home/eric/mail
132K /home/eric/
132K total
----------------------------------------------------------------
Configurando o idioma para Português.
squirrelmail-configure
SquirrelMail Configuration : Read: config.php (1.4.0)
---------------------------------------------------------
Main Menu --
1. Organization Preferences
2. Server Settings
3. Folder Defaults
4. General Options
5. Themes
6. Address Books
7. Message of the Day (MOTD)
8. Plugins
9. Database
10. Languages ***
D. Set pre-defined settings for specific IMAP servers
C Turn color on
S Save data
Q Quit
SquirrelMail Configuration : Read: config.php (1.4.0)
---------------------------------------------------------
Language preferences
1. Default Language : pt_BR
2. Default Charset : pt_BR ISO-8859-1
3. Enable lossy encoding : false
R Return to Main Menu
C Turn color on
S Save data
Q Quit
Command >>
----------------------------------------------------------------
Apos alterar pressione a letra "s" de salvar e "q" para sair.
----------------------------------------------------------------
Obs: Se com os comandos acima ano der certo, tente opções abaixo...
dpkg-reconfigure locales
Desativar ( pressionando na barra espaçadora )
[*] en_US.UTF-8 UTF-8
Ative as 2 opções abaixo ( pressionando na barra espaçadora )
[*] pt_BR ISO-8859-1
[*] pt_BR.UTF-8 UTF-8
Pressione TAB e OK e enter
Na próxima tela selecione...
pt_BR
Pressione TAB e OK e enter
service apache2 restart
Configurando o cliente no Outlook.
ip local ( 192.168.2.177 )
===[ SASL ]===
Autenticação SASL no servidor SMTP para que seja enviado mensagens de e-mail somente
com a autenticação.
apt-get install sasl2-bin
Ajuste as 2 linhas no arquivo abaixo:
nano /etc/default/saslauthd
#--- inicio do arquivo
START=yes
#--- ajuste a última linha como está abaixo.
OPTIONS="-c -m /var/spool/postfix/var/run/saslauthd -r"
ctrl + x + y + enter ( salvar e sair do arquivo )
groups postfix && usermod -G sasl postfix
Crie o arquivo.
nano /etc/postfix/sasl/smtpd.conf
pwcheck_method: saslauthd
mech_list: plain login
ctrl + x + y + enter ( salvar e sair do arquivo )
service saslauthd restart && service saslauthd status
ps -ef | grep saslauthd
mkdir /etc/postfix/ssl
cd /etc/postfix/ssl/
openssl genrsa -des3 -rand /etc/hosts -out smtpd.key 1024
Verificando a chave criada acima.
openssl rsa -in /etc/postfix/ssl/smtpd.key -text
Permissão de leitura e escrita ( 0600 )
chmod 0600 smtpd.key
Criando chave.
openssl req -new -key smtpd.key -out smtpd.csr
openssl x509 -req -days 3650 -in smtpd.csr -signkey smtpd.key -out smtpd.crt
openssl rsa -in smtpd.key -out smtpd.key.unencrypted
Renomeando.
mv -f smtpd.key.unencrypted smtpd.key
openssl req -new -x509 -extensions v3_ca -keyout cakey.pem -out cacert.pem -days 3650
Apenas verificando conteúdo ...
openssl x509 -noout -hash -in /etc/postfix/ssl/smtpd.crt
openssl x509 -noout -subject -in /etc/postfix/ssl/smtpd.crt
openssl x509 -noout -text -in /etc/postfix/ssl/smtpd.crt
openssl rsa -in smtpd.key -out smtpd.key.unencrypted
chown -R root:postfix /etc/postfix/ssl/
chmod -R 640 /etc/postfix/ssl/
Adicionar as linhas abaixo:
nano /etc/postfix/main.cf
# Adicionar os dois blocos abaixo.
#---[ Atenticacao SASL ]---------------------
smtpd_sasl_auth_enable = yes
smtpd_sasl_security_options = noanonymous
broken_sasl_auth_clients = yes
smtpd_sasl_authenticated_header = yes
smtpd_sasl_local_domain =
smtpd_sasl_auth_enable = yes
#---[ criptografia ]-------------------------
smtpd_tls_auth_only = yes
smtp_use_tls = yes
smtpd_use_tls = yes
smtpd_tls_key_file = /etc/postfix/ssl/smtpd.key
smtpd_tls_cert_file = /etc/postfix/ssl/smtpd.crt
smtpd_tls_CAfile = /etc/postfix/ssl/cacert.pem
smtpd_tls_loglevel = 1
smtpd_tls_received_header = yes
smtpd_tls_session_cache_timeout = 3600s
smtp_tls_note_starttls_offer = yes
tls_random_source = dev:/dev/urandom
ctrl + x + y + enter ( salvar e sair do arquivo )
service postfix restart && service postfix status
telnet localhost 25
Trying ::1...
Connected to localhost.
Escape character is '^]'.
220 juralinux.com.br ESMTP Postfix (Debian/GNU)
ehlo juralinux.com.br
250-juralinux.com.br
250-PIPELINING
250-SIZE 10240000
250-VRFY
250-ETRN
250-STARTTLS
250-AUTH DIGEST-MD5 NTLM CRAM-MD5 PLAIN LOGIN
250-AUTH=DIGEST-MD5 NTLM CRAM-MD5 PLAIN LOGIN
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN
quit
221 2.0.0 Bye
Connection closed by foreign host.
ls /etc/postfix/ssl -l
total 20
-rw-r----- 1 root postfix 1464 Mar 21 11:01 cacert.pem
-rw-r----- 1 root postfix 1834 Mar 21 11:01 cakey.pem
-rw-r----- 1 root postfix 928 Mar 21 10:58 smtpd.crt
-rw-r----- 1 root postfix 757 Mar 21 10:58 smtpd.csr
-rw-r----- 1 root postfix 887 Mar 21 11:00 smtpd.key
telnet localhost 143
Trying ::1...
Connected to localhost.
Escape character is '^]'.
* OK [CAPABILITY IMAP4rev1 UIDPLUS CHILDREN NAMESPACE THREAD=ORDEREDSUBJECT
THREAD=REFERENCES SORT QUOTA IDLE ACL ACL2=UNION STARTTLS] Courier-IMAP ready.
Copyright 1998-2011 Double Precision, Inc. See COPYING for distribution informat
telnet localhost 110
Trying ::1...
Connected to localhost.
Escape character is '^]'.
+OK Hello there.
quit
+OK Better luck next time.
Connection closed by foreign host.
telnet localhost pop3
Trying ::1...
Connected to localhost.
Escape character is '^]'.
+OK Hello there.
quit
+OK Better luck next time.
Connection closed by foreign host.
netstat -tan | egrep -w "(25|143|110)"
tcp 0 0 0.0.0.0:25 0.0.0.0:* LISTEN
tcp6 0 0 :::25 :::* LISTEN
tcp6 0 0 :::110 :::* LISTEN
tcp6 0 0 :::143 :::* LISTEN
tcp6 0 0 ::1:110 ::1:36921 TIME_WAIT
tcp6 0 0 ::1:143 ::1:57954 TIME_WAIT
tail /var/log/mail.log
tail /var/log/mail.err
Vamos enviar alguns emails via terminal para testar...
echo "Testing email, by Jura" | mail -s "Test 123" eric@juralinux.com.br
echo "Testing email, by Jura" | mail -s "Test 123" eric@juralinux.com.br
echo "Testing email, by Jura" | mail -s "Test 123" eric@juralinux.com.br
ls /home/eric/Maildir/ -l
total 28
drwx------ 2 eric eric 4096 Mar 27 15:56 courierimapkeywords
-rw-r--r-- 1 eric eric 36 Mar 27 15:56 courierimapsubscribed
-rw-r--r-- 1 eric eric 203 Mar 27 16:12 courierimapuiddb
-rw-r--r-- 1 eric eric 359 Mar 27 16:13 courierpop3dsizelist
drwx------ 2 eric eric 4096 Mar 27 16:13 cur
drwx------ 2 eric eric 4096 Mar 27 18:30 new
drwx------ 2 eric eric 4096 Mar 27 18:30 tmp
ls /home/eric/Maildir/cur/ -l
total 24
-rw------- 1 eric eric 423 Mar 27 15:56 1490644566.V801I206faM954656.debian:2,S
-rw------- 1 eric eric 423 Mar 27 15:56 1490644567.V801I206f7M590525.debian:2,S
-rw------- 1 eric eric 664 Mar 27 16:03 1490645019.V801I20213M662705.debian:2,S
-rw------- 1 eric eric 664 Mar 27 16:03 1490645031.V801I20215M35042.debian:2,RS
-rw------- 1 eric eric 994 Mar 27 16:12 1490645573.V801I20721M411702.debian:2,S
-rw------- 1 eric eric 1266 Mar 27 16:13 1490645598.V801I20720M832424.debian:2,S
Os 3 últimos emails enviados.
tail -f /var/log/mail.err /var/log/mail.info /var/log/mail.log
apt-get install nmap
nmap -Pn -p T:25,143 localhost | grep open
25/tcp open smtp
143/tcp open imap
Visualizando apelas linhas de código ( não as linhas comentadas )
grep -ve "^#" -ve "^$" /etc/default/saslauthd
grep -ve "^#" -ve "^$" /etc/postfix/main.cf
Cuidando dos Spams.... Vamos validar termos usados no corpo do email e configurar uma
blacklist de malware.
wget -O - 'https://lists.malwarepatrol.net/cgi/getfile?receipt=f1391767429&product=8&
list=postfix' > /etc/postfix/mbl-body-deny
Vamos visualizar apenas a parte inicial deste arquivo visto que este é muito longo.
cat mbl-body-deny | more
#
# Malware Patrol - Block List - https://www.malwarepatrol.net
# List for Postfix MTA
# Generated at: 20170405130008 UTC
#
# Please do not update this list more often than every hour.
#
# Copyright (c) 2017 - Andre Correa - Malware Patrol - Malware Block List
# This information is provided as-is and under the Terms and Conditions
# available in the following address:
#
# https://www.malwarepatrol.net/terms.shtml
#
# Using this information indicates your agreement to be bound by these
# terms. If you do not accept them, please delete this file immediately.
#
# You can report false positives or broken rules/signatures to:
# fp (a t) malwarepatrol.net
#
# Kn2su6fOsZ5fnhesG2hPPMDDDX3LYM3y
#
/http:\/\/(.+@)?perso\.wanadoo\.es\/download789.*/ DISCARD MBL-834
/http:\/\/(.+@)?www\.noadware\.net.*/ DISCARD MBL-2205
/http:\/\/(.+@)?download\.bearshare\.com.*/ DISCARD MBL-3473
/http:\/\/(.+@)?perso\.wanadoo\.es\/voxcard_01.*/ DISCARD MBL-6139
/http:\/\/(.+@)?ghusthir\.no\.sapo\.pt.*/ DISCARD MBL-7865
/http:\/\/(.+@)?perso\.wanadoo\.es\/selviba101.*/ DISCARD MBL-14021
/http:\/\/(.+@)?perso\.wanadoo\.es\/orcamento05.*/ DISCARD MBL-14614
/http:\/\/(.+@)?perso\.wanadoo\.es\/post_cards2006.*/ DISCARD MBL-14793
/http:\/\/(.+@)?ak\.imgfarm\.com\/images\/nocache\/funwebproducts\/ei-2.*/ DISCARD MBL-16526
/http:\/\/(.+@)?www2\.verizon\.net\/micro\/vol_toolbar.*/ DISCARD MBL-16610
/http:\/\/(.+@)?perso\.wanadoo\.es\/software002.*/ DISCARD MBL-17138
/http:\/\/(.+@)?perso\.wanadoo\.es\/para_voce.*/ DISCARD MBL-17206
/http:\/\/(.+@)?perso\.wanadoo\.es\/downloadscard.*/ DISCARD MBL-17681
/http:\/\/(.+@)?perso\.wanadoo\.es\/tdfgr.*/ DISCARD MBL-18165
/http:\/\/(.+@)?perso\.wanadoo\.es\/terrafotos2006.*/ DISCARD MBL-18277
/http:\/\/(.+@)?perso\.wanadoo\.es\/cartoes2006.*/ DISCARD MBL-18461
/http:\/\/(.+@)?perso\.wanadoo\.es\/zbsb2006.*/ DISCARD MBL-18611
/http:\/\/(.+@)?66\.39\.4\.207\/graph.*/ DISCARD MBL-22137
/http:\/\/(.+@)?www\.elettraautomazioni\.it\/public\/nuke\/images.*/ DISCARD MBL-22154
/http:\/\/(.+@)?perso\.wanadoo\.es\/payboy0006.*/ DISCARD MBL-22299
/http:\/\/(.+@)?69\.5\.5\.56.*/ DISCARD MBL-23282
/http:\/\/(.+@)?perso\.wanadoo\.es\/filesxfer.*/ DISCARD MBL-23369
/http:\/\/(.+@)?perso\.wanadoo\.es\/bookswf\/MinhasFotos.*/ DISCARD MBL-23962
/http:\/\/(.+@)?cardsvirtual\.no\.sapo\.pt.*/ DISCARD MBL-24020
/http:\/\/(.+@)?perso\.wanadoo\.es\/filesxfer.*/ DISCARD MBL-24049
/http:\/\/(.+@)?perso\.wanadoo\.es\/coracao_links_ks.*/ DISCARD MBL-24170
/http:\/\/(.+@)?perso\.wanadoo\.es\/verificcc.*/ DISCARD MBL-24342
/http:\/\/(.+@)?www\.trm\.cn\/ggt.*/ DISCARD MBL-24347
O aquivo possui 17 mb.
ls /etc/postfix/ -lh
total 17M
-rw-r--r-- 1 root root 329 Apr 3 10:11 dynamicmaps.cf
-rw-r--r-- 1 root root 1.9K Apr 5 16:24 main.cf
-rw-r--r-- 1 root root 1.5K Apr 3 10:12 main.cf--bk
-rw-r--r-- 1 root root 7.8K Apr 5 16:25 master.cf
-rw-r--r-- 1 root root 17M Apr 5 20:23 mbl-body-deny ***
-rw-r--r-- 1 root root 161 Apr 4 19:53 mysql-virtual_domains_maps.cf
-rw-r--r-- 1 root root 186 Apr 4 19:53 mysql-virtual_mailbox_maps.cf
-rw-r--r-- 1 root root 20K Nov 4 2014 postfix-files
-rwxr-xr-x 1 root root 8.7K Nov 4 2014 postfix-script
-rwxr-xr-x 1 root root 28K Nov 4 2014 post-install
drwxr-xr-x 2 root root 4.0K Apr 3 10:15 sasl
drw-r----- 2 root postfix 4.0K Apr 3 10:19 ssl
Agora vamos adicionar a linha abaixo no arquivo /etc/postfix/main.cf para abrir o
arquivo acima.
No final do arquivo digite a linha abaixo:
nano /etc/postfix/main.cf
body_checks = regexp:/etc/postfix/mbl-body-deny
ctrl + x + y + enter ( salvar e sair do arquivo )
postmap /etc/postfix/mbl-body-deny
service postfix restart && service postfix status
nano /etc/postfix/helo_access
### helo access
localhost REJECT 554 BadSender1
127.0.0.1 REJECT 554 BadSender2
juralinux.com.br REJECT 554 BadSender3
ctrl + x + y + enter ( salvar e sair do arquivo )
Adicione a linha abaixo no arquivo /etc/postfix/main.cf
nano /etc/postfix/main.cf
check_helo_access hash:/etc/postfix/helo_access
ctrl + x + y + enter ( salvar e sair do arquivo )
postmap helo_access
ls -l helo_access*
-rw-r--r-- 1 root root 341 Apr 5 20:38 helo_access
-rw-r--r-- 1 root root 12288 Apr 5 20:52 helo_access.db
service postfix restart && service postfix status
Crie o arquivo abaixo.
nano /etc/postfix/header_checks
#Bloqueio de mensagens falsas de virus
/([Vv].rus(es)?|V.RUS).*(ALERT|alert|S(EU|UA)|YOUR|en(viado|contrado)|found|detect(ado|ed)|blo(cked|queado)|[Rr]emetente|sent)/ REJECT Bogus anti-virus alert - please config your mail server properly
/[Rr]eturn(ado|ed) d(evido|ue) (a|to) [Vv].rus/ REJECT Bogus anti-virus alert - please config your mail server properly
/[dD]etect[ea]do? [Vv].rus(es)?/ REJECT Bogus anti-virus alert - please config your mail server properly
# Bloqueio de assuntos já manjados
/VIAGRA*|Viagra*|viagra*/ REJECT Mensagem recusada - Spams nao sao permitidos aqui
*/you?*|You?*|YOU?*/ REJECT Mensagem recusada - Spams nao sao permitidos aqui
/name=[^>]*\.(bat|com|exe|dll)/ REJECT
ctrl + x + y + enter ( salvar e sair do arquivo )
Adicione a linha abaixo no arquivo /etc/postfix/main.cf
nano /etc/postfix/main.cf
header_checks = regexp:/etc/postfix/header_checks
ctrl + x + y + enter ( salvar e sair do arquivo )
postmap header_checks
ls -l header_checks*
-rw-r--r-- 1 root root 664 Apr 5 21:09 header_checks
-rw-r--r-- 1 root root 12288 Apr 5 21:09 header_checks.db
service postfix restart && service postfix status
Crie o arquivo abaixo.
nano /etc/postfix/ip-access
# Bloqueando as redes de acordo com a RFC 198
10 REJECT RFC 1918 Esta rede nao é permitida
192.168 REJECT RFC 1918 Esta rede nao é permitida
127 REJECT - Voce nao eh localhost
# Spammers Conhecidos
rede124.centrodainternet.com REJECT Voce é um Spammer Conhecido, sai fora!
*.maquina01.com REJECT Voce é um Spammer Conhecido, sai fora!
casacampolu.com.br REJECT Voce é um Spammer Conhecido, sai fora!
royaume.com REJECT Voce é um Spammer Conhecido, sai fora!
*.hospedagemdesites.ws REJECT Voce é um Spammer Conhecido, sai fora!
webcasaaftb.com REJECT Voce é um Spammer Conhecido, sai fora!
microstrategy.com REJECT Voce é um Spammer Conhecido, sai fora!
fastprinter.com.br REJECT Voce é um Spammer Conhecido, sai fora!
recriandoonline.com.br REJECT Voce é um Spammer Conhecido, sai fora!
ctrl + x + y + enter ( salvar e sair do arquivo )
Adicione a linha abaixo no arquivo /etc/postfix/main.cf
nano /etc/postfix/main.cf
ip-access = regexp:/etc/postfix/ip-access
ctrl + x + y + enter ( salvar e sair do arquivo )
postmap ip-access
ls -l ip-access*
-rw-r--r-- 1 root root 664 Apr 5 21:09 header_checks
-rw-r--r-- 1 root root 12288 Apr 5 21:09 header_checks.db
service postfix restart && service postfix status
Crie o arquivo abaixo.
nano /etc/postfix/mime_checks
# Bloquear e-mail com anexos: lnk, asd, hlp, ocx, reg, bat, cpl, chm, com, cmd, exe, dll, vxd, pir, scr, hta, jse, shm, shb, shs, vbe, vbs, vbx, wsf, wsh e xl
/^\s*Content-(Disposition|Type).*name\s*=\s*"?(.+\.(lnk|asd|hlp|ocx|reg|bat|c(pl|hm|om|md)|exe|dll|vxd|pif|scr|hta|jse?|sh[mbs]|vb[esx]|ws[fh]|xl))"?\s*$/ DISCARD Attachment não permitido de acordo com regras locais - Possivel Virus. File "$2" has the unacceped extension "$3"
/^\s*Content-(Disposition|Type).*name\s*=\s*"?(.+\.(com))"?\s*$/ REJECT Attachment não permitido de acordo com regras locais - Possível Vírus. File "
ctrl + x + y + enter ( salvar e sair do arquivo )
Adicione a linha abaixo no arquivo /etc/postfix/main.cf
nano /etc/postfix/main.cf
mime_header_checks = regexp:/etc/postfix/mime_checks
ctrl + x + y + enter ( salvar e sair do arquivo )
postmap mime_checks
ls -l mime_checks*
-rw-r--r-- 1 root root 587 Apr 5 21:20 mime_checks
-rw-r--r-- 1 root root 12288 Apr 5 21:20 mime_checks.db
service postfix restart && service postfix status
===[ Roundcube ]===
O RoundCube lê as mensagens diretamente do mailbox, e utiliza um sistema de cache para
torná-lo mais rápido. As mensagens enviadas são salvas no banco de dados.
apt-get install mysql-server mysql-client postgresql mcrypt libdbd-sqlite3-perl sqlite3
apt-get install libapache2-mod-php5 php5-pgsql php5-mysql php5-mcrypt php5-sqlite
apt-get update && apt-get upgrade
cd /var/www/html
wget https://downloads.sourceforge.net/project/roundcubemail/roundcubemail/1.1.3/
roundcubemail-1.1.3-complete.tar.gz
tar xfz roundcubemail-1.1.3-complete.tar.gz
mv roundcubemail-1.1.3 roundcubemail
Instalando dependências.
apt-get install php5-mcrypt php5-intl
nano /etc/php5/apache2/php.ini /
[intl]
intl.default_locale = en_US.UTF-8
ctrl + x + y + enter ( para salvar e sair do arquivo )
rgrep date.timezone /etc/php5/apache2/
/etc/php5/apache2/php.ini:; http://php.net/date.timezone
/etc/php5/apache2/php.ini:;date.timezone =
dpkg-reconfigure tzdata – America ( enter )
Pressione 8 vezes a letra “S” para pular para “São Paulo” ( enter )
Procure no arquivo date.timezone e adicione America/São_Paulo
nano /etc/php5/apache2/php.ini
date.timezone = America/Sao_Paulo
ctrl + x + y + enter ( para salvar e sair do arquivo )
service apache2 restart && service apache2 status
Abrir interface do Roundcube para iniciar instalacao:
http://192.168.2.172/roundcubemail/installer/
No final da tela clique no botão “CREATE CONFIG”
Copie e cole o código gerado acima para dentro do arquivo config.inc.php
cat > /var/www/html/roundcubemail/config/config.inc.php
cole arqui o código gerado ...
ctrl + d ( salvar e sair )
cd /var/www/html/roundcubemail/config/
ls -l
total 56
-rw-r--r-- 1 501 80 3908 Sep 13 2015 config.inc.php.sample
-rw-r--r-- 1 501 80 48834 Sep 13 2015 defaults.inc.php
-rw-r--r-- 1 501 80 2815 Sep 13 2015 mimetypes.php
Vamos renomear o original.
chown www-data:www-data /var/www/html/roundcubemail/temp/ /var/www/html/roundcubemail/logs/
chmod g+w /var/www/html/roundcubemail/logs/
chmod g+w /var/www/html/roundcubemail/temp/
service apache2 restart && service apache2 status
mysql --defaults-file=/etc/mysql/debian.cnf
CREATE DATABASE roundcubemail;
GRANT ALL PRIVILEGES ON roundcubemail.* TO roundcube@localhost IDENTIFIED BY 'secret123';
flush privileges;
quit
mysql --defaults-file=/etc/mysql/debian.cnf roundcubemail < /var/www/html/roundcubemail/SQL/mysql.initial.sql
service apache2 restart && service postfix restart
service postfix status && service apache2 status
Por segurança vamos remover o diretório installer como esta orientado na tela de insta-
lação do Roundcube acima.
rm -rf installer
Obs:
Se tentar logar no Roundcube com o usuário Eric e se ainda não foi enviado um emaila
via terminal então não será possivel logar com o usuário Eric.
Não sei porque isto acontece ( sorry ).
Envie um email via terminal ( abaixo ) após faça o login com Eric.
echo "Testing email, by Jura" | mail -s "Test 123" eric@juralinux.com.br
http://192.168.2.172/roundcubemail/
User: eric
Pass: 123
===[ Postfix Mail Log Analyzer ]===
Analiza quantos emails estão em fila, quantos e-mails não foram entregues e porque
e-mails não são entregues.
aptitude -y install pflogsumm
perl /usr/sbin/pflogsumm -d yesterday /var/log/mail.log
Postfix log summaries for Apr 4
Grand Totals
------------
messages
5 received
5 delivered
0 forwarded
0 deferred
0 bounced
0 rejected (0%)
0 reject warnings
0 held
0 discarded (0%)
2067 bytes received
2067 bytes delivered
2 senders
2 sending hosts/domains
2 recipients
1 recipient hosts/domains
Per-Hour Traffic Summary
------------------------
time received delivered deferred bounced rejected
--------------------------------------------------------------------
0000-0100 0 0 0 0 0
0100-0200 0 0 0 0 0
0200-0300 0 0 0 0 0
0300-0400 0 0 0 0 0
0400-0500 0 0 0 0 0
0500-0600 0 0 0 0 0
0600-0700 0 0 0 0 0
0700-0800 0 0 0 0 0
0800-0900 0 0 0 0 0
0900-1000 0 0 0 0 0
:
:
:
Host/Domain Summary: Message Delivery
--------------------------------------
sent cnt bytes defers avg dly max dly host/domain
-------- ------- ------- ------- ------- -----------
5 2067 0 0.1 s 0.1 s juralinux.com.br
Host/Domain Summary: Messages Received
---------------------------------------
msg cnt bytes host/domain
-------- ------- -----------
3 966 juralinux.com.br
2 1101 localhost
Senders by message count
------------------------
3 root@juralinux.com.br
2 eric@localhost
Recipients by message count
---------------------------
4 eric@juralinux.com.br
1 isa@juralinux.com.br
Senders by message size
-----------------------
1101 eric@localhost
966 root@juralinux.com.br
Recipients by message size
--------------------------
1512 eric@juralinux.com.br
555 isa@juralinux.com.br
message deferral detail: none
message bounce detail (by relay): none
message reject detail: none
message reject warning detail: none
message hold detail: none
message discard detail: none
smtp delivery failures: none
Warnings: none
Fatal Errors: none
Panics: none
Master daemon messages
----------------------
6 daemon started -- version 2.11.3, configuration /etc/postfix
5 terminating on signal 15
crontab -e
# send mail log summary at AM 1:00 everyday to root
00 01 * * * perl /usr/sbin/pflogsumm -e -d yesterday /var/log/mail.log |
mail -s 'Logwatch for Postfix' root
===[ Fail2ban ]===
O Fail2Ban é extremamente eficaz na prevenção de ataques de força bruta e de negação
de serviço (DoS).
aptitude install fail2ban
fail2ban-client status ssh
Status for the jail: ssh
|- filter
| |- File list: /var/log/auth.log
| |- Currently failed: 0
| `- Total failed: 0
`- action
|- Currently banned: 0
| `- IP list:
`- Total banned: 0
iptables --list | grep fail2ban
fail2ban-ssh tcp -- anywhere anywhere multiport dports ssh
Chain fail2ban-ssh (1 references)
tail /var/log/fail2ban.log
2017-04-06 18:45:34,767 fail2ban.server [3704]: INFO Changed logging target to /var/log/fail2ban.log for Fail2ban v0.8.13
2017-04-06 18:45:34,768 fail2ban.jail [3704]: INFO Creating new jail 'ssh'
2017-04-06 18:45:34,848 fail2ban.jail [3704]: INFO Jail 'ssh' uses pyinotify
2017-04-06 18:45:34,869 fail2ban.jail [3704]: INFO Initiated 'pyinotify' backend
2017-04-06 18:45:34,875 fail2ban.filter [3704]: INFO Added logfile = /var/log/auth.log
2017-04-06 18:45:34,876 fail2ban.filter [3704]: INFO Set maxRetry = 6
2017-04-06 18:45:34,877 fail2ban.filter [3704]: INFO Set findtime = 600
2017-04-06 18:45:34,877 fail2ban.actions[3704]: INFO Set banTime = 600
2017-04-06 18:45:34,899 fail2ban.jail [3704]: INFO Jail 'ssh' started
fail2ban-regex /var/log/maillog /etc/fail2ban/filter.d/roundcube-auth.conf
Running tests
=============
Use failregex file : /etc/fail2ban/filter.d/roundcube-auth.conf
Use single line : /var/log/maillog
Results
=======
Failregex: 0 total
Ignoreregex: 0 total
Date template hits:
Lines: 1 lines, 0 ignored, 0 matched, 1 missed
|- Missed line(s):
| /var/log/maillog
`-
fail2ban-regex /var/log/dovecot.log /etc/fail2ban/filter.d/postfix.conf
Running tests
=============
Use failregex file : /etc/fail2ban/filter.d/postfix.conf
Use single line : /var/log/dovecot.log
Results
=======
Failregex: 0 total
Ignoreregex: 0 total
Date template hits:
Lines: 1 lines, 0 ignored, 0 matched, 1 missed
|- Missed line(s):
| /var/log/dovecot.log
`-
fail2ban-regex /var/log/mail.log "\[\], reject.*\.\.\. Relaying denied"
Running tests
=============
Use failregex line : \[\], reject.*\.\.\. Relaying denied
Use log file : /var/log/mail.log
Results
=======
Failregex: 0 total
Ignoreregex: 0 total
Date template hits:
|- [# of hits] date format
| [862] MONTH Day Hour:Minute:Second
`-
Lines: 862 lines, 0 ignored, 0 matched, 862 missed
Missed line(s): too many to print. Use --print-all-missed to print all 862 lines
grep "Ban " /var/log/fail2ban.log | awk -F[\ \:] '{print $10,$8}' | sort | uniq -c | sort –n
awk '($(NF-1) = /Ban/){print $NF}' /var/log/fail2ban.log | sort | uniq -c | sort -n
===[ logwatch ]===
O Logwatch é uma ferramenta para monitorar os arquivos de log do seu sistema. Este
programa requer um servidor de e-mail em funcionamento em sua rede para enviar os logs
por e-mail para você.
apt-get install logwatch
logwatch --mailto jura@juralinux.com.br
logwatch --service sshd --range=Today
################### Logwatch 7.4.0 (03/01/11) ################
Processing Initiated: Thu Apr 6 20:11:37 2017
Date Range Processed: today
( 2017-Apr-06 )
Period is day.
Detail Level of Output: 0
Type of Output/Format: stdout / text
Logfiles for Host: mail
#####################################################
--------------------- SSHD Begin ------------------------
SSHD Started: 4 Time(s)
Users logging in through sshd:
jura:
192.168.2.136: 2 times
---------------------- SSHD End -------------------------
################## Logwatch End #########################
logwatch --service sshd --range=Today --detail=Medium
logwatch --service sshd --range=Today --detail=High
===[ Postfix.Admin ]===
Gerenciador gráfico criado para o Postfix em PHP e serve para gerenciar as caixas
postais, domínios etc...
Vamos baixar opacote ( http://postfixadmin.sourceforge.net/ ) para o formato do debian.
Nele já está tudo pronto para o programa ser instalado, todos os caminhos definidos,
etc…, por isto o arquivo tem a terminação .deb
wget https://downloads.sourceforge.net/project/postfixadmin/postfixadmin/postfixadmin-3.0.2/postfixadmin_3.0.2-1_all.deb
dpkg -i postfixadmin_3.0.2-1_all.deb
Instalando dependências ( forçando ).
apt-get install -f
Yes – enter – mysql – enter – digitar senha do mysql
Criando login e senha do administrador do postfix.admin
http://192.168.2.155/postfixadmin/setup.php
mkdir -p /usr/share/postfixadmin/templates_c
chmod -R 777 /usr/share/postfixadmin/templates_c
Precisamos reiniciar o apache2.
service apache2 restart && service apache2 status
Procure no arquivo abaixo por:
$CONF['setup_password'] = 'changeme';
E mude pelo hash gerado, linha em vermelho.
nano /etc/postfixadmin/config.inc.php
// $CONF['setup_password'] = 'changeme';
// http://www.juralinux.com.br/postfixadmin/setup.php
// Copiar linha do has gerada na pagina
$CONF['setup_password'] = '3c75e2b27cc44fc8c25c6adddaa73216:db0aa49a75e44a91161702b382cfb43c89f13d30';
ctrl + x + y + enter ( para salvar e sair do arquivo )
Foi gerado o hash que será configurado no arquivo config.php
O email de super usuário eric@juralinux.com.br não foi aceito, então usei
jonas.ben@hotmail.com
Vamos configurar um administrador e senha.
Setup password : 123Abc ( senha criada no hash – página anterior )
Adminsitrador : jonas.ben@hotmail.com
Senha : 123456Abc
Senha : 123456Abc
http://192.168.2.155/postfixadmin/login.php
Precisaremos criar dois arquivos abaixo:
cd /etc/postfix/
Crie o arquivo abaixo.
cat > /etc/postfix/mysql-virtual_domains_maps.cf
# mapear dominios cadastrados ( locais )
user = root
password = 123=
hosts = 127.0.0.1
dbname = postfixadmin
query = SELECT domain FROM domain WHERE domain='%s'
ctrl + d ( salvar e sair do arquivo )
Crie o arquivo abaixo.
cat > /etc/postfix/mysql-virtual_mailbox_maps.cf
# procurar os usuarios - 1 se conta esta ativa
user = root
password = 123=
hosts = 127.0.0.1
dbname = postfixadmin
query = SELECT maildir FROM mailbox WHERE username='%s' AND active = 1
ctrl + d ( salvar e sair do arquivo )
service postfix restart && service postfix status
Missing printshots here... feeling lazy...
===[ Amavis ]===
Adicionando um antivírus
Para utilizar o Amavis em conjunto com o Postfix, de forma que todos os e-mails passem
primeiro pelo antivírus, e só depois sejam encaminhados para as caixas postais dos
usuários. O Amavisd "intercepta" as novas mensagens, entregando-as ao executável do
Clamav. De acordo com a configuração, as mensagens com arquivos infectados podem ser
simplesmente deletadas, ou colocadas em uma pasta de quarentena.
Lembrando que já foram incluídas as linhas de configuração do antivírus ( Amavis ) no
arquivo de configuração /etc/postfix/main.cf e no arquivo /etc/postfix/master.cf
Vamos instalar o antivirus Amavis.
apt-get update
apt-get autoclean
apt-get autoremove
apt-get install amavis
Adicione a linha abaixo no arquivo /etc/postfix/main.cf
nano /etc/postfix/main.cf
content_filter = smtp-amavis:[127.0.0.1]:10024
ctrl + x + y + enter ( para salvar e sair do arquivo )
Agora vamos adicionar as linhas abaixo do Amavis no final do arquivo.
nano /etc/postfix/master.cf
smtp-amavis unix - - - - 10 smtp
-o smtp_data_done_timeout=1200
-o smtp_send_xforward_command=yes
-o disable_dns_lookups=yes
-o max_use=20
-o smtp_generic_maps=
127.0.0.1:10025 inet n - - - - smtpd
-o content_filter=
-o smtpd_delay_reject=no
-o smtpd_client_restrictions=permit_mynetworks,reject
-o smtpd_helo_restrictions=
-o smtpd_sender_restrictions=
-o smtpd_recipient_restrictions=permit_mynetworks,reject
-o smtpd_end_of_data_restrictions=
-o smtpd_restriction_classes=
-o mynetworks=127.0.0.0/8
-o smtpd_error_sleep_time=0
-o smtpd_soft_error_limit=1001
-o smtpd_hard_error_limit=1000
-o smtpd_client_connection_count_limit=0
-o smtpd_client_connection_rate_limit=0
-o receive_override_options=no_header_body_checks,no_unknown_recipient_checks
-o local_header_rewrite_clients=
-o local_recipient_maps=
-o relay_recipient_maps=
-o strict_rfc821_envelopes=yes
ctrl + x + y + enter ( para salvar e sair do arquivo )
Adicionar a linha abaixo.
nano /etc/amavis/conf.d/05-node_id
$myhostname = "ns1.juralinux.com.br";
ctrl + x + y + enter ( para salvar e sair do arquivo )
Após terminar a configuração, reinicie todos os serviços para atualizá-los:
Reiniciando serviços.
service amavis restart && service amavis status
service postfix restart && service postfix status
telnet localhost 10024
Trying ::1...
Connected to localhost.
Escape character is '^]'.
220 [::1] ESMTP amavisd-new service ready
quit
221 2.0.0 [::1] amavisd-new closing transmission channel
Connection closed by foreign host.
telnet localhost 10025
Trying ::1...
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
220 juralinux.com.br ESMTP Postfix (Debian/GNU)
quit
221 2.0.0 Bye
Connection closed by foreign host.
netstat -plan | grep ama
tcp 0 0 127.0.0.1:10024 0.0.0.0:* LISTEN 23803/amavisd-new (
tcp6 0 0 ::1:10024 :::* LISTEN 23803/amavisd-new (
unix 2 [ ACC ] STREAM LISTENING 103775 23803/amavisd-new ( /var/lib/amavis/amavisd.sock
unix 2 [ ACC ] STREAM LISTENING 104291 23942/master private/smtp-amavis
unix 2 [ ] DGRAM 103767 23803/amavisd-new (
unix 2 [ ] DGRAM 103859 23817/amavisd-new (
unix 2 [ ] DGRAM 103870 23816/amavisd-new (
netstat -ntl | grep ":10024"
tcp 0 0 127.0.0.1:10024 0.0.0.0:* LISTEN
tcp6 0 0 ::1:10024 :::* LISTEN
===[ clamv ]===
Instalando o antivirus.
aptitude install clamav clamav-freshclam clamav-daemon
Verificando se o service está ativo.
ps aux | grep clamav
clamav 24617 1.1 1.5 97604 15468 ? Ss 16:55 0:00 /usr/bin/freshclam -d --foreground=true
root 24670 0.0 0.2 12728 2112 pts/0 S+ 16:55 0:00 grep clamav
Atualizando.
freshclam
Verificando se há virus.
clamscan --infected --remove --recursive /home
----------- SCAN SUMMARY -----------
Known viruses : 6192436
Engine version: 0.99.2
Scanned directories: 35
Scanned files : 36
Infected files: 0
Data scanned : 0.00 MB
Data read : 0.00 MB (ratio 0.00:1)
Time : 11.163 sec (0 m 11 s)
Vamos baixar um simulador de vírus chamado “eicar”
cd /home/eric
wget http://www.eicar.org/download/eicar.com
Verificando se há virus e removendo se encontrar algum. Foi encontrado o virus que
baixamos de nome “eicar
clamscan --infected --remove --recursive /home
/home/eric/eicar.com: Eicar-Test-Signature FOUND
/home/eric/eicar.com: Removed.
----------- SCAN SUMMARY -----------
Known viruses: 6192436
Engine version: 0.99.2
Scanned directories: 35
Scanned files: 37
Infected files: 1
Data scanned: 0.00 MB
Data read: 0.00 MB (ratio 0.00:1)
Time: 11.527 sec (0 m 11 s)
Vamos escanear o usuário “eric”
clamscan -ir /home/eric -l clamscanreport
----------- SCAN SUMMARY -----------
Known viruses : 6192436
Engine version : 0.99.2
Scanned directories: 21
Scanned files : 18
Infected files : 0
Data scanned : 0.00 MB
Data read : 0.00 MB (ratio 0.00:1)
Time : 10.567 sec (0 m 10 s)
Vamos escanear o servidor inteiro… processo demorado.
clamscan -ir / -l clamscanreport
Arquivo log do antivirus.
tail /var/log/clamav/freshclam.log
Wed Apr 5 16:58:37 2017 -> ClamAV update process started at Wed Apr 5 16:58:37 2017
Wed Apr 5 17:01:58 2017 -> Downloading main.cvd [100%]
Wed Apr 5 17:02:06 2017 -> main.cvd updated (version: 57, sigs: 4218790, f-level: 60, builder: amishhammer)
Wed Apr 5 17:03:59 2017 -> Downloading daily.cvd [100%]
Wed Apr 5 17:04:03 2017 -> daily.cvd updated (version: 23269, sigs: 1979305, f-level: 63, builder: neo)
Wed Apr 5 17:04:05 2017 -> Downloading bytecode.cvd [100%]
Wed Apr 5 17:04:05 2017 -> bytecode.cvd updated (version: 291, sigs: 55, f-level: 63, builder: neo)
Wed Apr 5 17:04:10 2017 -> Database updated (6198150 signatures) from db.local.clamav.net (IP: 64.22.33.90)
Se precisar reiniciar o service.
service clamav-freshclam restart && service clamav-freshclam status
Agendar o escaneamento do servidor à meia noite todos os dias.
crontab -e
# adicione a linha abaixo para agenda a tarefa.
00 00 * * * clamscan -r /home
ctrl + x + y + enter
"Wisdom is like a river, the deeper it is the less noise it makes"
Afim de aprender mais? Fale comigo: linux1.noip@gmail.com