Read the UID from a HID iClass smartcard ( Px G8L )

A couple of guys asked me to create a simple python script to allow the iClass cards to be read and extract their UID to control a few other devices. I thought of sharing with you since there are a few other people asking for the same on the Internet.

from smartcard.CardType import AnyCardType
from smartcard.CardRequest import CardRequest
from smartcard.util import toHexString, toBytes
from smartcard.CardMonitoring import CardMonitor, CardObserver
from smartcard.util import *
import urllib2
import time
 
class printobserver( CardObserver ):
    """A simple card observer that is notified
    when cards are inserted/removed from the system and
    prints its uids. The code is not pretty but it works!
    """
 
    def update( self, observable, (addedcards, removedcards) ):
        apdu = [0xff, 0xca, 0, 0, 0]
        for card in addedcards:
          try:
            cardtype = AnyCardType()
            cardrequest = CardRequest( timeout=1, cardType=cardtype )
            cardservice = cardrequest.waitforcard()
            cardservice.connection.connect()
            response, sw1, sw2 = cardservice.connection.transmit(apdu)
            tagid = toHexString(response).replace(' ','')
            print tagid
            #urllib2.urlopen("http://your_web_servers_waiting_for_card_data/?uid=%s" % tagid, None, 3)
          except Exception as e:
            print "Exception detected: %s" % e
 
print "Card Monitor started..."
cardmonitor = CardMonitor()
cardobserver = printobserver()
cardmonitor.addObserver( cardobserver )
while True:
  time.sleep(3600)

It was tested using an Omnikey 5321 v2 USB reader and it was working perfectly. I know that I’m doing two calls to the device (the first one detects it and the second one requests the UID) and this could probably be done in a single pass. If you know how to do it, please step forward :)

PS: It was also shared on github: https://gist.github.com/zatarra/75df47c8bd5a8d913cb4

Converting the Mindflex into an open source wireless EEG tool

During the last days, I’ve been reading a lot about Lucid Dreaming and the several alternatives of accomplishing it. If you google the subject you’l find dozens of tiny gadgets promising the do it, but very few will really help in that because one of the key actions consists in detecting REM (Rapid Eye Movement) which only seem to be possible either by using some EEG equipment to monitor your brain or by analyzing the eye movement during sleep. The second option seems to be too complex for me because I couldn’t find any similar gadget that could be hacked.

And that’s where the Mindflex comes into play. The Mindflex is a toy developed by Mattel which uses a headband to read brainwaves and control games. It uses a processor from Neurosky very similar to the one on their official Development Kit.

Searching for the available options I’ve stumbled upon an awesome post ( http://frontiernerds.com/brain-hack ) describing in detail this little gadget and how to hook it to an arduino. This was almost perfect except that I wanted that this could remain portable and could be connected to any bluetooth enabled device directly.

 

Tools Required:

HC-06 Bluetooth module ( http://www.ebay.com/sch/i.html?_trksid=p2050601.m570.l1313.TR0.TRC0.H0.Xhc-06+module&_nkw=hc-06+module&_sacat=0&_from=R40 )

hc06

HC-06 Bluetooth mobule

Mindflex headband

500x_mindflex_headset

Bluetooth enabled device.

 

The hardware hack is fairly simple. Just connect the Pin1 of the BT dongle to the T pin on the headband, Pin2 to the R pin, Pin3 to GND and Pin4 to VCC. Just two quick side notes:

* I was lazy enough to solder the BT dongle directly to the battery header. To do a perfect job you should remove the pcb and solder the BT dongle to the power switch (so that it can be turned on/off  without removing the batteries).

* Connecting the Pin2 to the R pin is not necessary because we’re just listening  but it doesn’t hurt doing so. We never know when someone might be able to find a new feature that could require it. :)

 

To parse the data I had to come up with a python script to do it since I couldn’t find anything ready for use other than the arduino lib:

#!/usr/bin/python
import serial
import sys
 
latestByte  = ('c')
lastByte    = ('c')
inPacket    = False
myPacket    = []
PLENGTH     = 0
 
EEGVALUES    = []
EEGRAWVALUES = []
 
def parsePacket():
  if checksum():
    i=1
    while i < len(myPacket) - 1:
      if ord(myPacket[i]) == 0x02:
        POOR_SIGNAL = ord(myPacket[i+1])
        i += 2
      elif ord(myPacket[i]) == 0x04:
        ATTENTION = ord(myPacket[i+1])
        i += 2
      elif ord(myPacket[i]) == 0x05:
        MEDITATION = ord(myPacket[i+1])
        i += 2
      elif ord(myPacket[i]) == 0x16:
        BLINK_STRENGTH = ord(myPacket[i+1])
        i += 2
      elif ord(myPacket[i]) == 0x83:
        for c in xrange(i+1, i+25, 3):
          EEGVALUES.append(ord(myPacket[c]) << 16 | ord(myPacket[c+1]) << 8 | ord(myPacket[c+2]))
        i += 26
      elif ord(myPacket[i]) == 0x80:
        EEGRAWVALUES = ord(myPacket[i+1]) << 8 | ord(myPacket[i+2])         i += 4     print "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d" % (POOR_SIGNAL,ATTENTION,MEDITATION,EEGVALUES[0],EEGVALUES[1],EEGVALUES[2],EEGVALUES[3],EEGVALUES[4],EEGVALUES[5],EEGVALUES[6],EEGVALUES[7])   else:     print "Invalid Checksum!" def checksum():   x = 0   for i in range(1, len(myPacket) -1):     x += ord(myPacket[i])   return ~(x&255) & 0b11111111 == ord(myPacket[len(myPacket)-1]) def readCSV():   global myPacket, lastByte, LatestByte, inPacket, PLENGTH   ser = serial.Serial(       port=sys.argv[1],       baudrate=9600,       parity=serial.PARITY_NONE,       stopbits=serial.STOPBITS_ONE,       bytesize=serial.SEVENBITS   )   ser.isOpen()   try:     while 1 :       while ser.inWaiting() > 0:
        latestByte = ser.read(1)
 
        if ord(lastByte) == 170 and ord(latestByte) == 170 and inPacket == False:
          inPacket   = True
 
        elif len(myPacket) == 1:
          myPacket.append(latestByte)
          PLENGTH = ord(myPacket[0])
 
        elif inPacket == True:
          myPacket.append(latestByte)
          if len(myPacket) > 169:
            print "Error: Data Error too long!"
            del myPacket[:]
            inPacket = False
            del EEGVALUES[:]
          elif len(myPacket) == PLENGTH + 2:
            parsePacket()
            del myPacket[:]
            inPacket = False
            del EEGVALUES[:]
 
 
        lastByte = latestByte
 
  except KeyboardInterrupt:
    print('Exiting...')
    if ser.isOpen():
      ser.close();
    sys.exit(0)
 
if len(sys.argv) < 2:
  print "Mindflex datalogger by David gouveia <david.gouveia[at]gmail[dot]com>"
  print "Usage: %s " % sys.argv[0]
  sys.exit(1)
 
readCSV()

This will be the result (tested on OSX):

brain.py output

PS: I know that this script probably looks like crap. Feel free to improve it or check github for an updated version :)

https://gist.github.com/zatarra/6d2be801010c7eb844f0

Merge Strava’s GPX exported files

Last Weekend something happened during a morning ride on my bike with some friends and my GPS device turned off for no reason. When I turned it back on I didn’t have the choice of continuing a previous ride and I had to create a new ride.

When I got home and tried to upload the information the Strava I couldn’t find any feature which could let me merge rides and fixe the issue. Instead I ended up having two different rides which really annoyed me.

I started googling around and found someone suggesting that I export the rides and merge the contents of the files. They also suggested that this could be done directly concatenating the files which isn’t true. The trick here is to extract the tracking data from the files (GPX files exported from Strava are XML based) and using the first one as the metadata template.

This was the result of a very simple GPX merger:

#!/usr/bin/env php -q
<?php
/*
* StravaMerger © David Gouveia - http://www.davidgouveia.net
* Simple script to merge tracking data from Strava's exported GPX files.
* The backtrack_limit is there because some files could not be parsed due to their size.
* Feel free to raise the limit but be carrefull not to cross the limit.
* Instead of using regex, I could have used a XML cursor to overcome the backtrack limit
* but either I would have to use the php_xml extension or build my own parser.
*/
ini_set("pcre.backtrack_limit", "10000000");
 
if ( !trim( $argv[1] ) || trim( !$argv[2] ) || sizeof($argv) < 4 )
               die("Usage:\n$argv[0] file1.gpx file2.gpx <fileN.gpx> output.gpx\n" );
 
$segments ="";
 
 
for($i = 1; $i < sizeof($argv) - 1; $i++)
{
        echo "Processing $argv[$i] ...";
        if (!is_file( $argv[$i] ) ) die( "Invalid file: $argv[$i]\n" );
 
        $gpx = file_get_contents( $argv[$i] );
        if ( $i == 1 )  preg_match( "/^(.*?)<trkseg>.*?<\/trkseg>(.*?)$/is", $gpx, $metadata );
        preg_match("/<trkseg>(.*?)<\/trkseg>/ims", $gpx, $matches);
        if( trim( $matches[1] ) )
        {
                $segments .= $matches[1];
                echo "[OK]\n";
        }
        else
                echo "[FAIL]\n";
 
}
 
$output_file = $metadata[1] . "<trkseg>" . $segments . "</trkseg>" . $metadata[2];
 
file_put_contents($argv[sizeof($argv) -1], $output_file) or die( "Unable to create destination GPX\n" );
print "File " . $argv[sizeof($argv) -1] . " successfully created.\n";

I’m going to put an online version of this script to make it easier to use. ;-)

Outra forma de desactivar a rede PT-WIFI

Ok, este vai ser um post simples. Existe outra forma de desactivarem o hotspot da PT-WIFI do vosso router e apenas precisam de um cliente de telnet.

1º Acedam via telnet ao endereço IP do router. Utilizem o nome de utilizador sumeo e a password bfd,10ng

telnet 192.168.1.254

2º Executem os seguintes comandos:

wireless
mssid
iflist

Neste momento irá ser listada a lista de SSIDs que são propagados pelo vosso router. Em teoria deverão ser três (dois da PT-WIFI e um da vossa rede).

Para apagar basta usar o comando ifdelete usando a seguinte sintaxe:

ifdelete
ssid
radio

O único valor que muda é o do ssid pois o radio (que identifica a placa de rede associada é sempre o mesmo: 0). Os SSIDs começam no zero o que significa que para apagar o terceiro deveriam usar o seguinte commando:

ifdelete
ssid_id = 2
radio_id = 0

Basta portanto apagarem todos e no final salvar a configuração com:

saveall

E por fim sair:

exit

Como desactivar o Hotspot da PT-WIFI nos routers Thomson

Se tens o serviço de fibra da PT (quer seja MEO ou Sapo) já deves ter reparado que a PT silenciosamente activou um Hotspot da PT-WiFi através da tua ligação um pouco ao estilo das redes ZON Free Internet.

A ideia é boa, a forma como foi implementada é que é simplesmente absurda. Não só o fizeram de forma camuflada, acedendo e alterando a configuração do router sem o conhecimento e consentimento do cliente, como excluiram qualquer hipótese de ser desactivada, ou seja, somos todos forçados a ceder a nossa largura de banda e a patrocinar um servico que pode até beneficiar os clientes mas que foi feito com intuitos meramente comerciais. Mais ainda, os routers como qualquer outro dispositivo possuem limitações, e não sendo estes modelos uma gama profissional (qualquer hotspot PT-WiFi presente num Hotel ou centro comercial utiliza equipamentos Cisco ou Nortel que em NADA se assemelham a estes thomson) podem sofrer degradação de performance da rede wireless pois ainda que seja uma rede virtual diferente, os interfaces fisicos são os mesmos.

Mais! Se a velocidade contratada forem 100Mbits e tendo em conta que esta é também a velocidade máxima do equipamento, isto significa que se alguém estiver ligado na rede irá reduzir a vossa largura de banda contratada!

Dito isto e porque sou a favor da liberdade de escolha por parte do cliente, encontrei uma forma de desactivar novamente o hotspot PT-WIFI:

1º Acedam ao interface web do router via http://192.168.1.254

2º No ecrã de login, activem a consola de javascript ( cada browser tem a sua própria forma de aceder à consola, mais informações aqui) e colem o seguinte código:

var user = "Debug";
var hash2 = "91cd28f3d8d3a503e9839caaa2929123";
 
var HA2 = MD5("GET" + ":" + uri);
document.getElementById("user").value = user;
document.getElementById("hidepw").value = MD5(hash2 + 
                              ":" + nonce +":" + 
                              "00000001" + ":" + 
                              "xyz" + ":" + 
                               qop + ":" + HA2);
document.authform.submit();

Após clicarem no Enter vão entrar no interface de gestão com permissões especiais, entre elas o poder de desligar o hotspot PT-WiFi.

3- Acedam ao painel de configuração da rede Wireless do router. No fundo da página vão encontrar um novo link com a designação “Definições Hotspot”. Cliquem nele.

4- Aqui encontram as definições do Hotspot PT-WiFi. Cliquem em desactivar et voila!

Disfrutem do vosso router livre de qualquer acesso.

Antes de terminar este post no blog, deixo-vos com mais duas perguntas retóricas:

 

PS: Obrigado à malta da ptsec.info por ter disponibilizado os dados de acesso como root (mais informações aqui).

Simple script to check expiry dates on a java keystore (.jks) file

Here in my company we regularly need to check for expired certificates or just to have a proactive management checking which certificates are close to their expiry dates and issue new ones to avoid service disruption.

For that reason I’ve created a simple bash script which can be used in conjunction with nagios to check for expiring certicates.

#!/bin/sh
 
########################################################
#
#       Check certificates inside a java keystore
#
########################################################
TIMEOUT="timeout -k 10s 5s "
KEYTOOL="$TIMEOUT keytool"
THRESHOLD_IN_DAYS="30"
KEYSTORE=""
PASSWORD=""
RET=0
 
ARGS=`getopt -o "p:k:t:" -l "password:,keystore:,threshold:" -n "$0" -- "$@"`
 
function usage {
        echo "Usage: $0 --keystore <keystore> [--password <password>] [--threshold <number of days until expiry>]"
        exit
}
 
 
 
function start {
        CURRENT=`date +%s`
 
        THRESHOLD=$(($CURRENT + ($THRESHOLD_IN_DAYS*24*60*60)))
        if [ $THRESHOLD -le $CURRENT ]; then
                echo "[ERROR] Invalid date."
                exit 1
        fi
        echo "Looking for certificates inside the keystore $(basename $KEYSTORE) expiring in $THRESHOLD_IN_DAYS day(s)..."
 
        $KEYTOOL -list -v -keystore "$KEYSTORE"  $PASSWORD 2>&1 > /dev/null
        if [ $? -gt 0 ]; then echo "Error opening the keystore."; exit 1; fi
 
        $KEYTOOL -list -v -keystore "$KEYSTORE"  $PASSWORD | grep Alias | awk '{print $3}' | while read ALIAS
        do
                #Iterate through all the certificate alias
                EXPIRACY=`$KEYTOOL -list -v -keystore "$KEYSTORE"  $PASSWORD -alias $ALIAS | grep Valid`
                UNTIL=`$KEYTOOL -list -v -keystore "$KEYSTORE"  $PASSWORD -alias $ALIAS | grep Valid | perl -ne 'if(/until: (.*?)\n/) { print "$1\n"; }'`
                UNTIL_SECONDS=`date -d "$UNTIL" +%s`
                REMAINING_DAYS=$(( ($UNTIL_SECONDS -  $(date +%s)) / 60 / 60 / 24 ))
                if [ $THRESHOLD -le $UNTIL_SECONDS ]; then
                        echo "[OK]      Certificate $ALIAS expires in '$UNTIL' ($REMAINING_DAYS day(s) remaining)."
                else
                        echo "[WARNING] Certificate $ALIAS expires in '$UNTIL' ($REMAINING_DAYS day(s) remaining)."
                        RET=1
                fi
 
        done
        echo "Finished..."
        exit $RET
}
 
eval set -- "$ARGS"
 
while true
do
        case "$1" in
                -p|--password)
                        if [ -n "$2" ]; then PASSWORD=" -storepass $2"; else echo "Invalid password"; exit 1; fi
                        shift 2;;
                -k|--keystore)
                        if [ ! -f "$2" ]; then echo "Keystore not found: $1"; exit 1; else KEYSTORE=$2; fi
                        shift 2;;
                -t|--threshold)
                        if [ -n "$2" ] && [[ $2 =~ ^[0-9]+$ ]]; then THRESHOLD_IN_DAYS=$2; else echo "Invalid threshold"; exit 1; fi
                        shift 2;;
                --)
                        shift
                        break;;
        esac
done
 
if [ -n "$KEYSTORE" ]
then
        start
else
        usage
fi

All you have to do is call it like this:

./checkCertificate --keystore [YOUR_KEYSTORE_FILE] --password [YOUR_PASSWORD] --threshold [THRESHOLD_IN_DAYS]

The threshold indicates how many days are left until the expiry date is reached. I’m sure that there are several other ways of doing it but this is my own :-)

Como remover a barra de notificações da IOL (Push by IOL)

Não sei o que acham do sistema de notificações dos portais da rede IOL mas eu simplesmente não SUPORTO. É extremamente intrusivo, não permite ser desactivado e pior que tudo está sistematicamente a repetir-se (basta fazer um refresh da página e já lá está novamente! *g*).

Felizmente há várias formas de acabar com esta praga, e uma delas é usar o fabuloso plugin AdBlock Plus. Nada mais simples que abrir as opções do plugin no vosso browser favorito (Espero que seja o Firefox ou Chrome :p) e acrescentar as seguintes regras nos filtros:

iol.pt###iolpush_wrapBoxPush
iol.pt##.iolpush_open

20130305224231121

Et voila! A caixa de noticias irritante desapareceu! :D

CloudPT: Como resolver o erro “A tentar ligar”

Se por algum motivo a instalação e activação do cliente de desktop windows falhar a autorização à primeira vão-se deparar com uma especie de “deadlock” pois não vão conseguir reinstalar correctamente a aplicação para efectuar o pedido de autorizaçao novamente.

Para variar ... um erro

Para variar … um erro


Fartei-me de procurar no registo do Windows, na pasta da aplicação sem nunca ter encontrado uma pista até que acabei por dar com uma pasta que continha estes dados. Bastou desinstalar o programa e apagar a pasta %UserProfile%\AppData\Local\CloudPT para que o pedido de autorização fosse feito novamente.

Mais uma vez uma salva de palmas para o belíssimo serviço prestado pela PT que depois da barracada com o sistema de convites (que entre erros e páginas em branco ainda tinha o problema de passar os pedidos de cada pessoa para o fim da fila caso o registo do mesmo email fosse efectuado mais que uma vez) ainda não corrigiram um simples bug como uma autorização inválida.

Usar a expressão “BETA” num serviço destes é quase um eufemismo…

Poor Man’s hydroponics system

Have you ever tried to enter the world of hydroponics but never did it because you thought that it would be very expensive?

 

Now you don’t have an excuse! I’ve prepared a howto using (almost) the cheapest parts that I could get. This was not meant to grow large plants but small ones will do just fine. In my case I intend  to grow chilli peppers so this kit is great!

And this is what you need:

  • Small flower box including the water plate. It is important that the water plate fits perfectly on top of the flower box (just like a lid).
  • Some plastic cups
  • Air pump
  • Plastic tubing
  • Air Stone diffuser
  • Tools ( Electric driller, hole saw, duct tape, sharp knife, etc)
  • Perlite & Vermiculite (you can use rock wool or any other substrate)

Try to buy a hole saw with the same diameter as the plastic cups that you are going to use (or vice versa). This will make things easier, trust me!

Continue reading