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!

sexta-feira, 19 de novembro de 2010

Trava por afastamento com Bluetooth

Olá pessoal agora a pouco estive conversando com meu amigo Paulo Cotta sobre um dispositivo composto de um chaveiro RF e um dispositivo USB que detecta se o chaveiro está nas proximidades e trava a tela automaticamente quando ele se distancia.

Ele teve a idéia de utilizar o iPhone e uma rede Wireless AD-HOC e um script para ter esta mesma funcionalidade. Isso depois de eu divagar sobre a possibilidade de montar um hardware especializado com um teclado USB de sucata e alguns transistores e CIs.

Foi então que tivemos a ideia de utilizar o Bluetooth, uma vez eu sou pobre e não tenho telefone com wi-fi.

Enquanto ele foi fumar um cigarro e voltou, implementei o script, que pra minha surpresa funcionou de primeira!

Sugue abaixo pra quem quiser brincar. Ainda meio "bugado", uma vez que foi apenas um "Proof of concept".


Basta criar um arquivo com o conteúdo abaixo e marca-lo como executável ( chmod 755 arquivo.sh)


Troque o endereço MAC abaixo pelo MAC do seu telefone. Basta usar o comando hcitool scan para descobrir.

Se der algum problema, você precisar utilizar o ctrl-alt-f1 para logar no console e matar o script.


#!/bin/bash

while true; do
        echo "Scanning..."
        hcitool inq | grep "00:00:E0:CC:EE:15"
        if [ "$?" == "0" ]; then
                echo "Device is near me"
        else
                echo "Device is away"
                gnome-screensaver-command -l
        fi
        sleep 1
done

quarta-feira, 10 de novembro de 2010

Gerador de Lero-lero para TI


Atualizado em 7/3/2014

O Gerador de Lero-lero para TI e informática foi baseado no Fabuloso Gerador de Lero-lero v2.0. Ele é capaz de gerar qualquer quantidade de texto vazio e prolixo, ideal para engrossar uma tese de mestrado, impressionar seu chefe ou preparar discursos capazes de curar a insônia da platéia. Basta informar um título pomposo qualquer (nos moldes do que está sugerido aí embaixo) e a quantidade de frases desejada. Voilá! Em dois nano-segundos você terá um texto - ou mesmo um livro inteiro - pronto para impressão. Ou, se preferir, faça copy/paste para um editor de texto para formatá-lo mais sofisticadamente. Lembre-se: aparência é tudo, conteúdo é nada.


Título da "Obra"
Quantas frases?

quinta-feira, 21 de outubro de 2010

Como desabilitar a verificação de identificação de host do SSH


Esta semana enfrentei um problema interessante. Configurei uma rede aqui em casa com a mesma faixa de IPs so trabalho. Quando fui fazer ssh no roteador, me lembrei de um probleminha. O ssh identificou que o servidor tinha uma chave incorreta, porque eu ja tinha utilzado o ssh no mesmo IP, mas em apontando pra outro serivor. O ssh achou que poderia ser um tipo de ataque do tipo man-in-the-midle.

Eu poderia simplesmente apagar or ~/.ssh/know_hosts ou remover a chave do servidor, mas teria que fazer isso toda vez que alternasse entre as redes.

A mensagem foi esta

$ ssh root@192.168.0.1
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that the RSA host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
3f:1a:f4:ba:c5:aa:c1:1g:bf:4e:2e:cf:a3:fa:d8:59.
Please contact your system administrator.
Add correct host key in /home/user/.ssh/known_hosts to get rid of this message.
Offending key in /home/peter/.ssh/known_hosts:3
RSA host key for 192.168.0.1 has changed and you have requested strict checking.
Host key verification failed.$
 
 
 A solução foi desabilitar a verificação para IPs locais. Como são LANs que eu gerencio, o risco de have um ataque é mínimo.
Não recomendo para servidores com IPs públicos. Para isso, basta editar ou criar o arquivo
~/.ssh/config.
 
 Host 192.168.*.* 
   StrictHostKeyChecking no
   UserKnownHostsFile=/dev/null
 
 
 

quinta-feira, 16 de setembro de 2010

Outra máxima do XKCD

Completo em:
http://www.xkcd.com/792/

domingo, 22 de agosto de 2010

Piadinha para descontrair

Fonte:  http://www.xkcd.com/705/

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