2013-04-21

Uniden GMR3040 squelch adjustment


I bought a bunch of Uniden GMR3040 two-way radios at US.

This model seems to be cursed by a squelch calibration defect - so that the radio is always receiving a static noise. In high-end devices the user can select the squelch level, but on this consumer devices it is factory set, and good luck with that.

So I had the option of returning them for warranty repair or try to fix it at home.

I opened it in the hope of finding some pots. And there they were.

Then it was just a question of try one by one to see what were they for.

RT404 Adjusts the squelch. That is the only thing I needed. Problem solved.

I figured out two more adjustments:

RT401 is able to adjust the frequency about +-70KHz.
L401 adjusts the FM demodulation.


You can see the frequency sweep while I give a full turn to RT401. This is measured with a calibrated RTL.


There are some more pots on the board. Probably for battery voltage measurement, VOX threshold, etc. If you know what any of them are for please leave a comment and I will update this article.

2011-01-25

Escape your company network proxy

Your company network is "blocked"? Probably they are using a proxy to filter your outbound connections.

The usual solution is to encapsulate YOUR traffic inside the traffic your COMPANY ALLOWS.

READ FIRST:

  • I will show how to establish a ssh connection to a server over the Internet. Then you will be able to create a socks proxy and use most applications freely.
  • Before all you will need to be able to "browse" the Internet on the company assigned computer. Try opening https://encrypted.google.com/.
  • You may be breaching your employment agreement doing this. You have a read a lot of "this is just academic, don't do this a home", but I really mean it. I've used this kind of "jailbreak" in 3 different companies up to now, but on their best interest. That means this is just a shortcut for having to ask the IT people to open the exception for our computer, or to deal with "that's to complicated"-type IT administrators.
  • No method is perfect and even if the IT staff can't know exactly what are you doing over the tunnel, they can at least notice the potential high bandwidth usage from your machine to that weird server that no one else use.
  • You will need a Linux server accessible over ssh on the Internet. And in most cases you also need root privileges to bind to TCP 443. Can you do this with a Windows server? I don't know, Windows Servers are expensive and I haven't used them that much.

The proxy very probably will be a HTTP proxy(CONNECT Method) that only allows connections to TCP port 443. You might get lucky and get one that allows to TCP port 22.

Start by collecting your proxy configuration. In Windows (supposing this is your company assigned OS) go to "Internet Options->Connections->LAN settings" and you might see something as proxy.mycompany.com:8080.

Then check if you need authentication. Do you type a username and password when you open the Internet Explorer?

I assume you have a linux server with openssh daemon running at myserverontheinternet.com:22

There are at least 3 methods to try to get connectivity. Method A will probably not work on most companies, Method B have worked everywhere I tried, Method C is proxy proof as it gets but will have some processor and network overhead.

I've tested the 3 Methods both on Windows and Linux.

The only tool beside ssh client/server is ncat. Ncat is included with nmap.

To install on windows, download at http://nmap.org/download.html. On linux use your package manager, ex, on ubuntu: sudo apt-get install nmap

Method A:

Server :

(nothing to do)

Client [3]:

ncat -kl 8000 --sh-exec "ncat --proxy proxy.mycompany.com:8080 --proxy-type http --proxy-auth mike:mypassword myserverontheinternet.com 22"

ssh -p 8000 root@localhost

Method B:

Server [1]:

sudo ncat -kl 443 --sh-exec "ncat localhost 22"

Client [3]:

ncat -kl 8000 --sh-exec "ncat --proxy proxy.mycompany.com:8080 --proxy-type http --proxy-auth mike:mypassword myserverontheinternet.com 443"

ssh -p 8000 root@localhost

Method C [4]:

Server [2]:

sudo ncat -kl 443 --ssl --sh-exec "ncat localhost 22"

Client [3]:

ncat -kl 8000 --sh-exec "ncat --ssl --proxy proxy.mycompany.com:8080 --proxy-type http --proxy-auth mike:mypassword myserverontheinternet.com 443"

ssh -p 8000 root@localhost

This client instructions apply to linux with openssh ssh(1). If you are using Windows, just adapt accordingly.

There are quite a lot of other examples of doing this using other tools, probably smaller than nmap/ncat. But nmap is maintained and is available for most distributions, that's why it is my favorite.

OpenWrt have also ncat available now (package ncat and ncat-ssl), so if you are looking for a standalone linux machine for this, consider using a cheap router :).

Please comment if it worked for you.

[1] - You may bind openssh sshd directly to port 443 changing /etc/ssh/sshd_config. This is the recommend way of doing this and you shall replace it. I'm showing with ncat just to keep it similiar to the other examples.

[2] - Unless you have some kind of additional internet connection (like 3G) you can't set this from inside the company (because you haven't yet escaped the firewall). Just set it at home and create a script to start it on boot.

[3] - If you using linux you can set the ncat as a proxy command that will start each time you try to connect. Example, for method C add the following line to the end of /etc/ssh/ssh_config:

ProxyCommand ncat --ssl --proxy proxy.mycompany.com:8080 --proxy-type http --proxy-auth mike:mypassword %h %p

Now run ssh as:

ssh -p 443 root@myserverontheinternet.com

[4] - This way your traffic will look like regular SSL traffic instead of SSH traffic. This might work to go over extensive network filtering. You migh notice that we are not doing any kind of certificate checks, and that is because we are not relying on SSL security, because openssh is secure by itself.

2011-01-15

Use Google Authenticator to login to a Linux PC

Google recently announced two-step authentication for google apps. Fortunately they started from the beginning with open-source code, and released a PAM module that allows us to use it for something else: use a Time-based One-time Password (TOTP) to login to your Linux PC.
TOTP algorithm is still a draft RFC:
TOTP(K,T) = Truncate(HMAC-SHA-1(K,T))
K shared secret between client and server; each TOTP
generator has a different and unique secret K.

T value derived from a time reference.
The TOTP is valid only for one login, and for a short period(usually around 60s), that means that both clocks must be in sync.
The Google implementation also allows one-time scratch codes that can be used if some clock happen to be out of sync, or your phone just doesn't work when you need it.

To configure:
1 - Install Google Authenticator on a Android or Blackberry phone.

2 - Install the Google Authenticator PAM at your linux PC.
3 - Generate the key and provision it to the phone.
4 - Set Linux authentication to use this PAM module.

To authenticate:
1 - Generate the TOTP with the phone.
2 - Use it like a password.

This are the detailed instructions for Ubuntu 10.10 and Android 2.2:


To configure:

1 - Go to the Market app on the phone and search for "Google Authenticator". Install it.
2 - Open a console and type:


To install all the needed dependencies:

sudo apt-get install mercurial libqrencode3 libpam0g-dev
To checkout the Google Authenticator PAM module source code:
hg clone https://google-authenticator.googlecode.com/hg/ google-authenticator
To compile and install[1]:
cd google-authenticator/libpam/
make

make install
Delete the source:
cd ../.. rm -r google-authenticator/
3 - Type:
nuno@test-box1:~$ google-authenticator
https://www.google.com/chart?chs=200x200&chld=M|0&cht=qr&chl=otpauth://totp/nuno@test-box1%3Fsecret%3DIVCTSZVKG6ZJZ5P4




















Your new secret key is: IVCTSZVKG6ZJZ5P4

Your verification code is 853162
Your emergency scratch codes are:
70581448
65775471
40949450
81754434
11625120

Do you want me to update your "~/.google_authenticator" file (y/n) y

Do you want to disallow multiple uses of the same authentication
token? This restricts you to one login about every 30s, but it increases
your chances to notice or even prevent man-in-the-middle attacks (y/n) y
nuno@test-box1:~$
Open the Google Authenticator at your phone and create an account, scanning the barcode.

4 - Type:
sudo bash -c 'cat >/usr/share/pam-configs/google-all <<EOF
Name: Google Authenticator (all)
Default: yes
Priority: 900
Auth-Type: Primary
Auth:
required pam_google_authenticator.so
EOF'

sudo bash -c 'cat >/usr/share/pam-configs/google-enough <<EOF
Name: Google Authenticator (enough)
Default: yes
Priority: 900
Auth-Type: Primary
Auth:
sufficient pam_google_authenticator.so
On the next step you have to decide how you prefer to authenticate. Using only the TOTP, having to enter both the TOTP and the password, or just any of them.
For TOTP only:.................select google-enough, deselect unix
For TOTP or Password:.......select google-enough, select unix
For TOTP and Password [2]:.select google-all, select unix
sudo pam-auth-update
This is all. You can also login with TOTP remotely using ssh, without any change to openssh-server.
If you want to use different authentication schemes for local and remove login, you have to tweak with /etc/pam.d/*. The documentation is not very good, so good luck.
If you have any corrections or improvements please leave a comment.

Thanks for reading!

[1] - I didn't need to type "sudo" before "make install" although some files end up in system locations. If you know why I didn't need to invoke the Lord's name, please leave a comment!
[2] - This will work fine for Gnome login or sudo authentication, both of them will prompt for both codes. On the other hand it will not work for authentication on sshd or Synaptic Package Manager.

2010-11-08

Quick start with the Microchip Explorer 16 board

Quick start with the Microchip Explorer 16 board

(with standard PIC24FJ128GA010 PIM)





1 - Programmer

The board have dedicated connectors for a PICkit 2/PICkit 3 or ICD2/ICD3 programmer.
While I have a ICD3, we really don't need it. A direct USB cable from the computer to the board USB connector(J8) is enough.
The board was designed with a auxiliary MCU, the PIC18LF4550(U2), that was supposed, as it seems, to offer equivalent features to a PICkit 2.
Unfortunately Microchip never shipped the firmware needed to enable this feature.
Fortunately Rafal Waniurski did.

To update the PIC18LF4550(U2) to work as a programmer follow:
1 - Install PICkit 2 tool (latest as of 2010-11-08 PICkit 2 v2.61).
2 - Connect the board to power(J12) and a USB cable from J8 to the PC.
3 - Open PICkit 2 tool.

* you might get a error "PICkit 2 VDD and VPP voltage level errors.", just ignore it. Click OK and continue.
4 - Click Tools -> Download PICkit 2 Operating System, choose file PK2_Explorer16_V0210022.hex. The programming starts. It should take about 15s, and if it completes successfully you can read "PICkit 2 connected. ID = OIHoss".
5 - This will probably fail the first time. That is because the PICkit 2 tool will try to connect to the PIC18LF4550(U2) to verify the programing, but this will happen while windows is installing the driver for the new firmware you just flashed. While it probably is already working, you might repeat the previous step to get the successfully message.
*If this fails, your PIC18LF4550(U2) might be not programed from factory with a USB bootloader. In that case, you will need to use a regular programmer for loading this firmware(use PK2_Explorer16_V0210022-BL.hex instead).






2 - My first program

1 - Install MPLAB IDE and MPLAB C30. MPLAB IDE is free. MPLAB C30 have evaluation and free versions for academic use.
2 - Make sure Jumper J7 is set to "PIC24" Side and Switch S2 is set to "PIM" side
3 - Connect the board to power(J12) and a USB cable from J8 to the PC.
4 - Download explorer16_demo_v1.zip and unzip it.
5 - Double-click explorer16_demo.mcp to load the project in MPLAB.
6 - Click Project -> Build all.
7 - Select Programmer -> Select Programmer -> 8 PICkit 2.
8 - Click Programmer -> Program.

9 - Click Programmer -> Release from Reset.


* If you get a programming error or each time you reconnect the power/usb cable, you will need to click Programmer -> Connect.
* If you click Programmer -> Dowload OS, the vanilla PICkit 2 firmware will be loaded in the PIC18LF4550(U2), and the programmer will not work anymore. You will need to flash the PIC18LF4550(U2) with the Rafal Waniurski modified firmware to get it working again. That must be done with the PICkit 2 tool.


You are done.
The program behavior is explained in the main.c file header.






3 - Starting to write code

Microchip is known for making MCUs with "trilions" of peripherals. A PIC24 will have ADCs, Comparators, Timers, Low-power modes, Watchdog, UARTs, ...
That integration allows to reduce the number of components, saving board space, power and money.

Mastering all this features is not a simple task, and you will need to read the full bible(s).

1 - Peripherals Libraries

(C:\Program Files (x86)\Microchip\MPLABC30\docs\periph_lib\Microchip PIC24F Peripheral Library.chm)
* My demo program is using adc library, notice line "#include <adc.h>".
2 - Standard C Library

(C:\Program Files (x86)\Microchip\MPLAB C30\docs\hlpLib30.chm)
* My demo program is using the standard c input and output library, notice line "#include <stdio.h>".
3 - PIC24FJ128GA010 Family Data Sheet
http://ww1.microchip.com/downloads/en/DeviceDoc/39747e.pdf
4 - PIC24F Family Reference Manuals
http://www.microchip.com/wwwproducts/Devices.aspx?dDocName=en024805
* There is one Reference Manual for each Peripheral/Module. You should check this together with the Data Sheet. The Reference Manual explain in more detail, but might be only partially applicable to your MCU. The datasheet will clarify what your specific MCU has or hasn't.
5 - Explorer 16 Development Board User Guide
http://ww1.microchip.com/downloads/en/DeviceDoc/Explorer%2016%20User%20Guide%2051589a.pdf

Even if you read all this twice you will probably still don't get the entire picture. Buying a book might help:
Lucio Di Jasio, Programming 16-Bit PIC Microcontrollers in C: Learning to Fly the PIC 24, ISBN 0-7506-8292-2

For last, a useful trick to reduce the code/compile/program/debug/code/compile/program/debug/code
cycle is to activate the auto-program option in MPLAB. That way after changing the code, you only need to click "Make" and MPLAB will automatically compile and program the MCU for you.
1 - Select Programmer -> Settings -> Program after a sucessful build.

2 - Select Programmer -> Settings -> Run after a successful program.

References
[1]
Lucio Di Jasio, Programming 16-Bit PIC Microcontrollers in C: Learning to Fly the PIC 24, ISBN 0-7506-8292-2

2010-06-01

e-mail SPAM defense techniques

The following ideas are full of bugs and probably already discussed somewhere else. I don't claim they are original. I only claim I never googled them :)

1st method
E-mail is only accepted from:
Private/personal e-mail: Senders that complete a captcha. The captcha is generated by the receiver server, and extensions to existing protocols(SMTP) will enable transfer and display by e-mail clients to be completed on e-mail send.
Enterprise/mailing lists: E-mail is only accepted from authenticated sender domains, with proper trusted certificates.

Problems: would partially break current e-mail system.

2nd method
Private domain case(ex: johndoe.me):
Each time John wants to give is e-mail to someone/somewhere, he will use is e-mail server, or even a off-line device with a cryptographic algorithm to generate a unique address for that situation, ex, 98ads7@johndoe.me.
Later, when John wants to give away is e-mail again, he will create a new address, ex, fdsr432@johndoe.me, also unique for that transaction.

With this method there are two defenses against spam:
1 - Few addresses at johndoe.me are valid, so a random attack is harder.
2 - If John wants to give is e-mail to a untrusted site, that he suspects that can end in a spam list, he can rest assured that if that e-mail ends compromised, he can just block it at his e-mail server.

Shared domain case(ex gmail.com):
The extension for the private domain case is to use a subdomain instead of the name, so the same e-mail addresses for John could be:
johndoe@98ads7.gmail.com
johndoe@fdsr432.gmail.com


Problems: adds complexity for the user.

2010-03-24

Nuno, o mentiroso

Em Novembro disse que tinha perdido as fotos dos jogos da lusofonia.
Por culpa do sistema de ficheiros esquisito do Mac.

Há umas semanas, graças ao maravilhoso Ubuntu, consegui encontrar ficheiros "fantasma" no disco rígido, e recuperar TUDO.

É com muito prazer que hoje digo que as fotos estão aqui.
É com muito prazer que prometo nunca mais usar um Mac. Falhaste a convencer-me Hugo.

Obrigado ao Rui por me ter feito perceber que Macbooks não eram a minha cara, nomeadamente ao deixar cair um armário em cima dele. Obrigado.

2010-02-17

Nigeria, a quarta vez.

Ai e tal, vou ali à Nigéria.
Ai e tal, fico lá 4 semanas.
Sim...dificilmente seria pior.

Uma pequena ideia do ambiente na provincia:


Destruir uma torre:


Escolta policial:

2009-12-26

Como reparar o router do Sapo - 2

Pronto, depois de descobrir a Roda, descobri a Cerveja:

Afinal basta fazer o pedido:

http://192.168.10.1/ad_voice_voip_profile_account.xgi?set/runtime/web/voiplock=0&set/runtime/web/pppoelock=0

(substituir o endereço se o router não estiver no IP normal, e fazer login no interface web antes do pedido)

Isto desbloqueia todas as possibilidades de configuração até ser feito um restart(o que não destrói as configurações, apenas será necessário voltar a fazer este truque para alterar alguma configuração não-permitida pelo Sapo).

Melhor do que isto só mexendo no firmware do bicho...

2009-12-25

Como reparar o router do Sapo

Chegou-me às mãos um D-Link DVA-G3170i, que é vendido pelo Sapo ADSL.

Fiquei logo decepcionado quando vejo um transformador que é mesmo transformador, coisa que já não se usa.

Pior quando vi que o firmware que vem com este Router não estava a deixar configurar outros fornecedores de VOIP SIP.

Como se consegue tarifários estupidamente mais baratos em coisas como JustVoip, decidi ver se era possível configurar o router para isso. E é.

Antes de mais a porque de não se conseguir configurar com o interface normal:

A configuração do voip neste router é feita pelo interface web, por omissão em http://192.168.10.1/.

Aí, em ADVANCED -> Voice > Lines and Accounts, configura-se, pelo menos o Voip Profile e Voip Line. Em geral o Voip profile escolhe o operador e o Voip Line um utilizador especifico.
Quem quiser ter duas linhas("números") no Sapo só teria de criar 2 "Voip Line" para o mesmo "Voip profile"

O que acontece é que o Voip profile não aceita valores de operadores simpáticos.

Mergulhei no interface web do router e vi que isso devia-se a uma função JavaScript de validação que recusa valores fora do domínio do Sapo. Certamente engano da engenharia do Sapo.

Felizmente é possível ultrapassar isso fazendo um pedido de configuração HTML.

Para isso basta criar os Voip profile que se desejar, deixando por enquanto tudo como Sapo.

A seguir basta usar o gerador nesta pagina para configurar esses Voip profile como se pretenda.
O Profile number é o numero de sequência na tabela. Sempre 1 se só tiverem um profile.

O gadget calcula um URL que devem fazer copy&paste para a frente do endereço do router no browser. É fundamental que ainda estejam com sessão aberta no router, ou seja, que não deixem passar muitos minutos.

Para configurar JustVoip num router que esteja em http://192.168.10.1/, basta abrir o seguinte endereço no browser:

http://192.168.10.1/ad_voice_voip_profile_account.xgi?&set/voice_service:1/profile:1/name=justvoip&set/voice_service:1/profile:1/sip/user_agent_domain=sip.justvoip.pt&set/voice_service:1/profile:1/sip/user_agent_port=5060&set/voice_service:1/profile:1/sip/proxy_server=sip.justvoip.pt&set/voice_service:1/profile:1/sip/proxy_server_port=5060&set/voice_service:1/profile:1/sip/proxy_server_transport=UDP&set/voice_service:1/profile:1/sip/outbound_proxy_enable=0&CMT=0&EXE=voip_phone,0&EXE=qos

Depois disto resta configurar a Voip Line com o username/password :)

2009-11-29

Jogos da lusofonia 2009




Este verão estive na equipa de voluntários dos Jogos da Lusofonia 2009, no Voleibol e Voleibol de praia.

No Voleibol de Praia era condutor no transporte dos atletas.
Estavam a jogar Portugal, Brasil, Angola, Moçambique, STomé, Cabo verde, Índia (Goa) e Sri Lanka.
Foi muito giro para conviver com as delegações dos países. Umas mais simpáticas do que outras.

Andar a conduzir em contra-relógio por Oeiras destruiu o meu instinto de hypermiler. Descobri uso para o travão do carro, finalmente.

Também estavam no hotel os sub-21 de Futebol. Mas com esses só falava quando me pediam o numero da "Telminha"...

E em Setembro perdi as fotos todas disto por nabice :( Desde 2004 que não perdia fotos...

Mas sem duvida que comer ao lado dos jogadores Portugueses (campeões!), foi muito cool!

2009-11-21

S. Tome e Príncipe



3 horas depois de passar numa escola secundária em Palmela para um trabalho publicitário, estava a sair de Lisboa para S. Tomé e Príncipe.

Fui lá fazer um biscate para a Universidade da Beira Interior. Montar um GPS que não é TomTom.

Antes já me tinham avisado para levar "Blazer e gravata" para o 10 de Junho na embaixada.

> Estive 30m a nadar no mar (Nada mau!).
> Calor, calor, calor, odeio o calor :( Ou se está na praia ou em casa com ar condicionado, de resto é calor, calor, calor!
> Fiquei no Bairro da cooperação Portuguesa (IPAD). Muitos portugueses, muita animação. Muito porreiro pá!
> Explicaram-me que quando alguém diz "Blazer e gravata" também quer dizer "Calças e sapatos". Estava escuro e acho que só por isso é que me deixaram entrar na embaixada.
> Os miúdos não paravam de dizer o meu nome: "Branco, branco, branco!". Por momentos senti-me famoso novamente.

2009-11-11

Isto não se faz a um emigrante trabalhador de biscates!




Estimado Cliente,

Informamos que já detectamos a causa para o problema que nos reporta.

A equipa de segurança do serviço Caixadirecta detectou tentativas de acesso ao seu contrato, a partir da Nigéria, através de um IP suspeito.

Por questões de segurança o seu contrato Caixadirecta telefone foi imediatamente bloqueado e o Caixadirecta on-line desactivado.

Foram efectuadas 4 tentativas de contacto nos dias 2, 3 e 4 para o seu tmv: 9******** e para o seu número de telefone fixo, a informar do sucedido, mas sem êxito.
Mas suspeito porque?
Se esses senhores da Caixa lá fossem percebiam que qualquer vigarista treinado na Nigéria que seja bom na sua arte, emigra para os Estados Unidos!

Isto não se faz a um emigrante trabalhador de biscates! Quem vos *******!

2009-11-08

CFCB 2009

Deixaram-me fazer 1 turno.

1º turno, Secretaria, Clãs.

Cansativo, muito mais do que das outras vezes. Quanto voltei a casa descobri que é possível dormir 13 horas seguidas.

Muito bom, como sempre.


2009-01-19

Parvoices


Depois da ida de bicicleta ao Algarve em 2006 (será que ainda tenho o registo de GPS disso?), de uma descida do Tejo em Cayake, teve agora o Nuno a ideia de se por a andar para Este, muito para Este. E depois parar em St. Gallen.

Foi assim na Sexta das 15h00m as 00h45m e o GPS gravou isto:

Summary Data
Total Time 9:48:14
Moving Time 9:39:55
Distance (km) 63.65
Moving Speed (kph) 6.6 avg.
Elevation Gain (m) +2,321 / -2,125
Temperature (°C) -2.7°C
Wind Speed ( kph) SW 3.4 avg. SW 7.4 max.






Cheguei vivo, mas já houve alturas em que estava mais bem disposto.

2008-11-30

Thank an Engineer

Thank an Engineer

For making our lives safer, more productive and fun








Politica de oposição do costume

Odete Santos ‘superstar’ sonha com o fim do capitalismo

«desse dia imenso, do fim do capitalismo. Nesse dia, disse, nós cantaremos a Internacional!»

«voos de vítimas e algozes» e da legislação que Sarkozy aprovou dando «imunidade a Rumsfeld».

«Sonhar pode ser mesmo um pecado, pelo menos sonhar que se tem liberdade de expressão»

Odete, amor, se fores para a praia de bikini também fazes "a gente" rir-se e já não precisas de dizer tanta merda.