segunda-feira, 15 de agosto de 2011

Spam na vida Real

Não tem nada mais chato que receber spam em papel. Seja no sinal ( semáfaro, farol, sinaleiro), seja em casa.

Este pequno truque visa pelo menos descobrir quem são os picaretas que divulgam seu endereço físico para terceiros.

A ideia é simples, e funciona melhor se você tiver acabado de se mudar. Para cada local que fornecer seu endereço, coloque no campo complemento um identificador (ID).

Depois, anote em uma planilha o ID e para quem você forneceu o endereço, além da data.

Exemplo:

Rua Dos Não sei das quanta, 1234 Apt 201 ID02 Cidade Tal, MG

Na sua planilha:

ID   Data      Nome
01    12/8/11 Banco Semvergonnha
02   15/8/11  Loja do João


Quando receber um spam, localize o ID na correspondência e verifique na tabela pra saber quem foi o safado...



Mudança de paradigma sobre Antivirus


Particularmente, não uso antivirus algum. Boas práticas são mais eficientes.

 http://g1.globo.com/tecnologia/noticia/2011/08/talvez-esteja-na-hora-de-desinstalar-o-antivirus-de-seu-computador.html

 



quinta-feira, 21 de julho de 2011

Novo desafio

Pessoal, parti para um novo desafio, me tornei CIO da mais nova empresa de TI e Cloud Computing de Belo Horizonte.

Conheçam a www.wh1.com.br a 1ª reseller Google de Minas Gerais.



segunda-feira, 18 de julho de 2011

Complicar pra que?

Recentemente estou numa fase de simplificação. Após oito anos trabalhando com Tecnologia da Informação, Administração de redes e Segurança, percebi que as coisas podem ser mais simples, e, consequentemente, mais baratas.

Uma das maneiras é utilizar ferramentas robustas, de empresas notavelmente sólidas, mas como serviço. Atualmente, a idéia de Cloud Computing está se encaixando como uma luva.

Uma das coisas aparentemente simples, mas que é de uma enorme complexidade é o email. No mundo corporativo, o email é uma forma oficial de comunicação, que serve hoje, como aceite de propostas, fechamento de negócios e até como prova jurídica.

Deve existir uma maneira mais simples de manter um email eficiente em uma empresa, sem ter que ficar monitorando logs de smtp, gerenciando quotas, e migrando arquivos pst de um lado para o outro.

A busca continua!

sábado, 23 de abril de 2011

DynDNS no OpenWrt

Olá pessoal,

Como todos já deve ter percebido, sou super fã do OpenWrt e outros firmwares alternativos para roteadores wireless.

Hoje fui colocar o Dyndns pra funcionar e esbarrei num probleminha e vou postar aqui como resolver.

A maneira mais fácil é utilizar o pacote ndyndns. Basta instala-lo com o comando:

opkg update
opkg install ndyndns

Depois, basta copiar o arquivo de configuração modelo e edita-lo.

cd /etc/ndyndns
cp ndyndns.conf.sample ndyndns.conf
vim ndyndns.conf

Depois, basta habilitar (e iniciar, caso não queira dar boot) o serviço pela interface web em Services - Initscripts.

Até ai tudo bem, o problema é que eu utilizo um modem ADSL roteado, isto é ele mesmo já faz a autenticação e já oferece uma rede privada na porta Ethernet. Em geral estes modems funcionam como bridge e o usuario tem que fazer PPPoE no computador ou roteador.  Com isso, minha porta WAN do roteador wireless tem na verdade uma outra rede privada, como se fosse uma DMZ.

O NAT das portas pra dentro eu resolvi coloando o IP da WAN do roteador como o "DMZ Host IP" no modem. Com isso, todas portas externas são mapeadas para o Roteador Wireless.


O problema é que o ndyndns, por padrão, pega o IP da interface WAN. Com isso, o Dyndns era atualizado com meu IP privadp :-p.

Pra resolver, bastou editar o arquivo de initscript do ndydns:

vim /etc/init.d/ndyndns

Comentei a linha original e criei outra utilizando o parâmetro -r, que irá pegar o Ip externo com o auxilio do host remoto do Dyndns.
Ficou assim:

#/usr/sbin/ndyndns -c $CHROOT -f $CONFIG -i $(config_get wan ifname) $OPTIONS

    /usr/sbin/ndyndns -c $CHROOT -f $CONFIG -r  $OPTIONS


Depois disso, bastou reiniciar o serviço que tudo funcionou maravilhosamente bem.

Em tempo. Não estava a fim de mexer com firmware de modem pra funcionar como bridge.... Além disso, desta forma, o modem fica mais flexivel, caso eu precise dele desta forma.

Até mais!

sábado, 19 de março de 2011

USB no DIR-320 com OpenWrt

Depois das férias em janeiro e um fevereiro bem corrido, segue mais um pequeno post que pode ser útil para alguém.

Pra quem está "brigando" com a porta USB do roteador DIR-320 no OpenWrt, ai vai o macete.

É necessário instalar os pacotes para os módulos OHCI_HCD e EHCI_HCD. Em princípio, apenas o EHCI seria necessário, mas parece que este driver não reconhece o hardware do DIR-320...

Nao instale o UHCI_HCD, se não, não funciona nada.


opkg update
opkg install kmod-usb2
opkg intall kmod-usb-ohci

Se for usar algum pendrive:

opkg install kmod-usb-storage
opkg install kmod-fs-vfat
opkg-install kmod-fs-ntfs

Se for usar impressora:
opkg install kmod-usb-printer
opkg install luci-app-p910nd
opkg install p910nd

Pelo Luci será possível habilitar o p910 ( print spooler)


Referência:
http://wiki.openwrt.org/toh/d-link/dir-320?s[]=dir&s[]=320

quarta-feira, 29 de dezembro de 2010

Como autenticar o squid no LDAP

Olá pessoal,

Ai vai uma dica interessante pra quem quiser autenticar o Squid no LDAP, inclusive Active Directory, sem ter que colocar a máquina Linux no domínio e usar aquele winbind chato.


Crie um script em PHP chamado, por exemplo /etc/squid/authldap.php e marque ele como executável com chmod 755 /etc/squid/authldap.php.

Segue o conteudo:

#!/usr/bin/php

$ldaphost="192.168.0.1";
$ldapport="389";

$ldapconn = ldap_connect($ldaphost, $ldapport)
           or die("Could not connect to $ldaphost");


if ($ldapconn) {

        # Loop infito - cada requisicao do proxy é 
        while(!feof(STDIN)){

                $ldapbind = false;
                # toma a linha e separa usuario e senha
                $line = trim(fgets(STDIN));
                list($user,$pass) = split(" ",$line);
       
                 // binding to ldap server
                $ldapbind = ldap_bind($ldapconn, $user."@seudominiodoad.com.br", $pass);
                #
                # Se ele nao existir, ja retorna ERR
                if($ldapbind){
                        echo "OK\n";
                }
                else{
                        echo "ERR\n";
                }
        }
      }      
?>








No squid.conf utilze o script acima para autenticar:

Adicione as linhas abaixo,

auth_param basic realm   Entre com seu login e senha da rede
auth_param basic program /etc/squid/authldap.php
acl password proxy_auth REQUIRED


Altera a linha correspodente, mais no fim do squid.conf, como se segue. Nao deixe outros "http_access" com o nome da sua rede sobreporem a regra de uso de senha.

http_access allow password


Qualquer dúvida entrem em contato!

terça-feira, 28 de dezembro de 2010

Como um script se suicida?

Como um script se suicida?

rm -f $0 && kill -9 $$

Explicação:
$0 expande para o nome do próprio script
$$ é o PID do script rodando

quinta-feira, 9 de dezembro de 2010

Como compilar o ESD para AR71xx


O ESD é um software muito interessante. Ele permite que você "envie" o som via TCP/IP para tocar em computador remoto. O PulseAudio é compatível com ele, o que torna as coisas bem legais, como poder mandar tocar musicas no meu amplificador de potência estando em qualquer parte da casa sem precisar conectar cabos ao notebook. Como utilizo um roteador com placa USB, resolvi comprar uma dessas placas de audio USB baratinhas e tornar o router um sound server.

Como encontrei o esd pre-compilado somente para processadores Broadcom ( plataforma MIPSEL), tive que compilar o esd para o processador Atheros AR71xx (plataforma MIPS) do TP-Tink WR-1043ND.

Depois de brincar bastante com o DD-WRT, decidi que seria hora de migrar para o OpenWrt, por ser mais versátil e menos "engessado". O DD-WRT é ótimo, mas o OpenWrt é, digamos, mais "hacker friendly". Só peca na interface web, mas usando o X-Wrt achei até melhor que o DD-WRT.

O primeiro passo foi baixar os fontes do OpenWrt, na versão BackFire 10.03, pois contem todos os compiladores e ferramentas necessárias para compilar cruzado. Descompactei o fonte dentro da pasta ~/src do meu home, mas você pode ajustar para o caminho que desejar. Depois de ter as ferramentas instaladas, passei para a compilação dos softwares. É possível criar um pacote, mas isso vai ficar pra uma outra hora, pois exige um pouco mais de estudo...

Em seguida, baixei o fonte do audiofile-0.2.7, que é uma lib necessária para o ESD.

Usei o script abaixo para compilar.
#!/bin/bash
export PATH=$HOME/src/backfire_10.03/staging_dir/toolchain-mips_r2_gcc-4.3.3+cs_uClibc-0.9.30.1/usr/bin:$PATH
export CC=mips-openwrt-linux-uclibc-gcc
export LD=mips-openwrt-linux-uclibc-ld

./configure --prefix=/usr \
--without-libiconv-prefix \
--without-libintl-prefix \
--disable-nls \
--program-transform-name="" \
--host=mips \
--target=mips-openwrt-linux-uclibc
make




Depois, baixei o fonte do esound-0.2.8, e de modo similar, utilizei o script abaixo. Note que tive que adequar os caminhos para a libaudiofile, compilada a pouco.


#!/bin/bash
export PATH=$HOME/src/backfire_10.03/staging_dir/toolchain-mips_r2_gcc-4.3.3+cs_uClibc-0.9.30.1/usr/bin:$PATH
export CC=mips-openwrt-linux-uclibc-gcc
export LD=mips-openwrt-linux-uclibc-ld

export AUDIOFILE_CFLAGS="-I $HOME/src/audiofile-0.2.7/libaudiofile"
export AUDIOFILE_LIBS="-L $HOME/src/audiofile-0.2.7/libaudiofile/libaudiofile.la"

./configure --prefix=/usr \
--without-libiconv-prefix \
--without-libintl-prefix \
--disable-nls \
--enable-arts=no \
--enable-alsa=no \
--program-transform-name="" \
--includedir=$HOME/src/audiofile-0.2.7/libaudiofile \
--libdir=$HOME/src/audiofile-0.2.7 \
--host=mips \
--target=mips-openwrt-linux-uclibc

make

Com isso, temos o binário chamado esd, que pode ser transferido para o router via scp, por exemplo.

Para utilizá-lo, uso o seguinte comando na inicialização:

/opt/bin/esd -tcp -public -nobeeps &


Compilei também o aumix, que é um mixer de linha de comando. O som fica no máximo por padrão, o que pode ser um inconveniente. O procedimento é o mesmo.

#!/bin/bash
export PATH=/home/jones/src/backfire_10.03/staging_dir/toolchain-mips_r2_gcc-4.3.3+cs_uClibc-0.9.30.1/usr/bin:$PATH
export CC=mips-openwrt-linux-uclibc-gcc
export LD=mips-openwrt-linux-uclibc-ld

./configure --prefix=/usr \
--without-gpm \
--without-sysmouse \
--without-libiconv-prefix \
--without-libintl-prefix \
--without-gtk \
--disable-nls \
--host=mips \
--target=mips-openwrt-linux-uclibc \
--libdir=$HOME/src/backfire_10.03/staging_dir/toolchain-mips_r2_gcc-4.3.3+cs_uClibc-0.9.30.1/usr/lib/ \
--includedir=$HOME/src/backfire_10.03/staging_dir/toolchain-mips_r2_gcc-4.3.3+cs_uClibc-0.9.30.1/usr/include/
make

A partir de então, basta apontar o player para utilizar o esd. O mplayer e o audacity são  dois que sei que funcionam. Ainda estou tentando colocar o PulseAudio para usar o ESD, mas ainda não funcionou. Com isso, será possível redirecionar o som de qualquer aplicativo que utilize o som padrão do Ubuntu.


domingo, 28 de novembro de 2010

Optware on TP-Link WR1043ND

UPDATE - 2011 04 23 - Acabei por utilizar o OpenWrt em vez do DD-WRT com Optaware. O opkg já vem nativo e o sistema de overlay é muito mais  interessante. A unica vantagem do DD-WRT é a interface gráfica, mas quem se importa....







Pessoal, desculpem-me por este post apenas em Inglês. Devo mandar essa informação para o pessoal do dd-wrt colocar em um Wiki ou algo assim, dai não preciso reescrever.  Se tiverem dúvidas é só comentar que eu esclareço.

I apologize for the Portuguese readers of my blog for posting this in English. I plan to send it to dd-wrt guys, so I don't need to rewrite it. If you have any doubt, please post a comment that I'll be glad to explain.

I just bought a new Wireless router from TP-Link model TP-WR1043ND. It has  4 Gigabit ports, Wireless N which gives up to 300Mpbs an USB port, which open up for a lot of interesting things like using it as a NAS. After installing DD-WRT on it I wanted to use Optware ( a collection of softwares to be installed on /opt that is mounted on a flash drive).

I found that the usual instructions didn't work, because this model has an Atheros (ar71xx) processor and the scripts around are Broadcom oriented. After a lot of research I came up with these instructions. Hope it would be useful for someone. Please, let me know if you use it. Leave a comment. I assume the reader has already installed Optware on a Broadcom device using these instructions: http://www.dd-wrt.com/wiki/index.php/Optware,_the_Right_Way. If not, take a look at it first. There are the basic steps like formatting the USB storage and enabling USB storage in web configuration.

In a pinch, what Optware does is  extend the softwares available on dd-wrt ( and other linux based firmwares too, for instance). You can have, for example, vim, squid, mc, and the coreutils and bash replacing busybox. As the root file system of wireless devices are read-only and very tight in size,  it has to be installed  on a USB drive, MMC card ( check for MMC mod on dd-wrt site) or even the JFFS ( the remaining space of the router's flash mounted on /jffs), even though it offers only a few hundreds of KB. Optware has a utility called opkg, that is very similar to apt-get from Debian and Ubuntu. It can download and install softwares from a repository. What we'll do is to make opkg work and configure some applications to work with /opt instead of usual /.

I assume from now on that you have an ext3 file system of a flash drive mounted on /opt. You have to auto mount it at boot. There's a lot of ways to do it, like using "Commands" from Web configuration page or creating a script like /jffs/etc/config/automount.startup. Check http://www.dd-wrt.com/wiki/index.php/Script_Execution if in doubt.

At first, I tried to install opkg from OpenWRT Backfire packages (http://downloads.openwrt.org/backfire/10.03/ar71xx/packages/) using the native ipkg.

cd /tmp
wget http://downloads.openwrt.org/backfire/10.03/ar71xx/packages/opkg_513-2_ar71xx.ipk
ipkg -d /opt opkg_513-2_ar71xx.ipk

Then I changed the  /opt/etc/opkg.conf to suit the new root:

src/gz packages http://downloads.openwrt.org/backfire/10.03/ar71xx/packages
dest root /opt
dest ram /tmp
lists_dir ext /opt/var/opkg-lists
option overlay_root /overlay


I tried to run, but it didn't work:

cd /opt/bin
./opkg -f /opt/etc/opkg.conf  update
./opkg: can't resolve symbol 'glob64' in lib './opkg'.

Note that I had to use -f to point to the right path of config file. It defaults to /etc/opkg.conf which doesn't exists.


This is because opkg needs some libs not present in dd-wrt. In this post http://www.dd-wrt.com/phpBB2/viewtopic.php?t=67678 Luyi suggests to compile Openwrt yourself and copy the libs to /opt/lib or use the ones he compiled. This is not necessary, because these libs are available on the backfire packages above, you just need to know  which ones and install with ipkg after downloading them.

Then, I installed the libgcc and libc, that are the minimum for opkg to work.


cd  /tmp
wget http://downloads.openwrt.org/backfire/10.03/ar71xx/packages/libgcc_4.3.3+cs-42_ar71xx.ipk
wget http://downloads.openwrt.org/backfire/10.03/ar71xx/packages/libc_0.9.30.1-42_ar71xx.ipk
ipkg  -d /opt/ install libgcc_4.3.3+cs-42_ar71xx.ipk

ipkg  -d /opt/ install libc_0.9.30.1-42_ar71xx.ipk

In order to use these libs you must change the environment variable LD_LIBRARY_PATH . It's already set to /opt/lib by dd-wrt, but you must put it first, so it has priority over /lib or /usr/lib.



export LD_LIBRARY_PATH=/opt/lib:/opt/usr/lib:$LD_LIBRARY_PATH


After this, the opkg works!

opkg -f /opt/etc/opkg.conf update
opkg -f /opt/etc/opkg.conf list

With the last command you can see a list of available packages. Note that if you logoff, you must export the LD_LIBRARY_PATH again. Let' correct it soon, keep reading.
From now on, you can install whatever you want, like vim, for example:


opkg -f /opt/etc/opkg.conf install vim-full

opkg -f /opt/etc/opkg.conf install vim-runtime



One interessating thing is that it automatically download the dependecies, like libncurses.
My recommended packages for initial setup:


coreutils-ls
coreutils-cp
coreutils-rm
coreutils-rmdir
coreutils-mv
procps
file
vim-full
vim-runtime
mc


Problems and solutions


From now on you have opkg working. You can skip these steps or adptapt for your own needs.


If you try vim you'll see that it has no colors and fancy stuff.  This is necessary to tell vim it uses /opt/usr instead of regular /usr. To do this, you can export the VIMRUNTIME env var.
export VIMRUNTIME=/opt/usr/share/vim/vim71


Also, ncurses needs information about terminal. It search by default on /usr/share/terminfo/ by should look at /opt/usr/share/terminfo/
export TERMINFO=/opt/usr/share/terminfo


To solve this at every boot, I created a startup script called /jffs/etc/config/profile.sh that it'll place some entries in the user .profile at boot ( note that you'll loose .profile if you edit it directly because it is rewritten at boot).
This will solve for other problems too. The PATH of /opt/bin and /opt/usr/bin  is set with higher priority over /bin and /usr/bin. That way, if you install an optware package with a command with the same name of the built in, it will be run instead of the default.


We also set some alias to avoid extra typing, like -f of opkg. The file command ( from file package) was corrected to point to magic file.


One important note.
If you install a package and it don't work complaining missing files or paths, you must find a way to point to the right place. My experience tells that environment variables, config files or some alias with a right argument will do the job in 99% of the cases.


#!/bin/sh

if [ -d /opt/bin ]; then

cat <
<EOF >> /tmp/root/.profile

alias opkg='/opt/bin/opkg -f /opt/etc/opkg.conf'
alias ls='ls --color'
alias file='file -m /opt/usr/share/file/magic'
alias df='df -h'

export LD_LIBRARY_PATH=/opt/lib:/opt/usr/lib:$LD_LIBRARY_PATH
export VIMRUNTIME=/opt/usr/share/vim/vim71
export TERMINFO=/opt/usr/share/terminfo
export PATH=/opt/bin:/opt/usr/bin/:$PATH
EOF

fi
 


To make  vim to work nicelly, I use the script /opt/etc/config/vim.startup


#!/bin/sh
VIMRC=/tmp/root/.vimrc
echo "set nocompatible" > $VIMRC
echo "set backspace=indent,eol,start" >> $VIMRC
echo "syntax on" >> $VIMRC


To make opkg to work is not difficult and and even a non skilled linux user can do if it has basic knowledge. I found this method more interesting than using scripts from http://www.dd-wrt.com/wiki/index.php/Optware,_the_Right_Way. It has less features, but I keep control of what I want. if you need what's posted there, just follow the instructions starting from somewhere ahead. You may need to install some packages manually, just figure it out which.

You have doubts I'm pleased to help, just post a comment.
Good luck!

Nota Importante

O conteúdo deste blog foi desenvolvido por mim e não foi copiado de outros locais, embora alguns poucos tópicos tenham sínteses e adaptações de outras fontes, que neste caso, serão referenciadas para se dar o devido crédito.
A reprodução é permitida desde que citada a fonte e para fins não comerciais. É proibido o uso para fins comercias sem a expressa autorização do autor.
Embora o conteúdo aqui apresentado seja testado pelo autor e/ou passado por sua aprovação, não é oferecida nenhuma garantia de que tudo funcionará corretamente ou não irá danificar os sistemas envolvidos, pois o sucesso dependerá do ambiente e/ou conhecimento do leitor.
Ao utilizar este blog, para qualquer fim, o leitor concorda com estes termos e isenta o autor de qualquer responsabilidade, ficando o uso do conhecimento aqui apresentado por sua conta e risco.
Caso discorde destes termos, gentileza fechar esta página imediatamente.

Copyright Jonathan Araújo 2010