A friend of mine told me that he was going to do a presentation about the famous Rubber Ducky.

For those of you who don’t know, rubber ducky is a USB dongle that emulates a keyboard disguised of flash drive.


Obviously, this is the perfect solution for a social engineering experiment, but at 44USD it is a bit pricey given that there are a few other devices that can perform in a similar way for less than 1/4 of the price.

Today I’m going to talk about one of those alternatives: The Arduino Beetle.


The arduino beetle is a tiny solution based on the ATMEGA32U4 the same micro controller that you can find in the Arduino Leonardo. It does support USB without any external components which makes it a very good option to build these minified dongles.


For this reason, creating arduino sketches that emulate a keyboard is quite trivial. In fact, it is so easy that it makes this tool look a bit worthless. Nevertheless, I’ve decided to create a small tool that would allow you to convert and use the existing Rubber Ducky Payloads with this little device.


How to Use it?

  1. Pick a payload you like and save it to a file. For instance this one: https://github.com/hak5darren/USB-Rubber-Ducky/wiki/Payload—osx-youtube-blaster
  2. Call rubberduino-convert and pass the payload file as the first argument. Pipe the output to a new file.
  3. Open your favourite arduino IDE and paste the contents of the file previously created.
  4. Upload the sketch to your arduino leonardo/beetle
  5. Enjoy 🙂



This is a very alpha version the code is not polished at all. Even though it does work pretty well there are a few issues:

  • Symbol handling – Special symbols will depend on the keyboard layout that you’re using. Currently it is working with portuguese layouts but it needs to be adjusted in case you have a different one. The way I did it was to run a test sketch that would show you the output of each char mapped between 1 and 100. I then picked them and created a dictionary called symbol_ids inside the python module to map the char. ( e.g. {“/”: 39, “ç”: 11, “&”:24 } and so on ).
  • The sketches are loooooongBecause of the issue mentioned above, I have to rely on keyboard.write to send a char at the time. This can make the sketches look big and makes it uncomfortable to troubleshoot but it was the easiest way for me to do it. Feel free to improve it. This was improved by 15% ( the size of the compiled sketch ).
  • Delay handling – The payloads can be produced either by using a default DELAY command that will stay between actions or by explicitly adding them to the code. Currently I always add a DELAY command between the actions which means that I might be introducing more delays than I should ( e.g. the payload you provided already has them ).

Feel free to check out the code here: https://github.com/zatarra/rubberduino

You can get the Beetle for less than $6 on Aliexpress ( thanks deine0ma! )

PS: You can follow an interesting discussion on reddit

The Micropython binaries for ESP8266 got released last week and I decided to give it a try. As an “Hello World” application, I wanted to try the wireless capabilities and control a few relays. Nothing fancy, but I was just for testing purposes.


Without further due, this is the snippet of code that I used to bring a HTTP servers that was capable of reading GET variables and parse the PATH:


import machine
import socket
import ure
RELAYS = [machine.Pin(i, machine.Pin.OUT) for i in (12, 13, 14, 15)]
def getPinStatus():
  return RELAYS
def setPin(pin, value):
  return "PIN %s set to %s" % (pin, value)
def parseURL(url):
  parameters = {}
  path = ure.search("(.*?)(\?|$)", url) 
  while True:
    vars = ure.search("(([a-z0-9]+)=([a-z0-8.]*))&?", url)
    if vars:
      parameters[vars.group(2)] = vars.group(3)
      url = url.replace(vars.group(0), '')
  return path.group(1), parameters
def buildResponse(response):
  return '''HTTP/1.0 200 OK\r\nContent-type: text/html\r\nContent-length: %d\r\n\r\n%s''' % (len(response), response)
addr = socket.getaddrinfo('', 80)[0][-1]
s = socket.socket()
print('listening on', addr)
while True:
    cl, addr = s.accept()
    print('client connected from', addr)
    request = str(cl.recv(1024))
    print("REQUEST: ", request)
    obj = ure.search("GET (.*?) HTTP\/1\.1", request)
    if not obj:
      cl.send(buildResponse("INVALID REQUEST"))
      path, parameters = parseURL(obj.group(1))
      if path.startswith("/getPinStatus"):
        cl.send(buildResponse("RELAY STATUS:\n%s" % "\n".join([str(x.value()) for x in getPinStatus()])))
      elif path.startswith("/setPinStatus"):
        pin = parameters.get("pin", None)
        value= parameters.get("value", None)
        cl.send(buildResponse("SET RELAY:\n%s" % setPin(pin, value)))
        cl.send(buildResponse("UNREGISTERED ACTION\r\nPATH: %s\r\nPARAMETERS: %s" % (path, parameters)))


You can get the gist here


The code will give you two different endpoints:

  • /getPinStatus -> Check if the relays are on or off
  • /setPinStatus -> Enable/disable pins. you need to pass a pin number (0 to 3) and a state (0 to disable, 1 to enable the relay). E.g.

The code is not pretty, and probably full of bugs, but the basic functionality is there.  All you have to do is to connect to a Wifi network ( or create your own access point), add the relays to GPIO 12, 13, 14 and 15 and you’re done. You have plenty of other tutorials to teach you how to connect things to your esp8266.

The code was based on the official example that you can find here


As always, feel free to suggest improvements 🙂



EDIT: Thank you Chris for identifying an issue with the regular expression!

I’ve been learning a lot about pyQT and definitely started using Sublime as my IDE. There was just one thing that was annoying me, which was the pile of windows that were being left behind each time I called the Build Action in Sublime (I easily forget about closing them).

Fortunately Sublime is so easy and powerful, that changing this behavior was very easy.

First I changed a small file that contains the settings for the Build action for Python (This is the path for OSX, for Windows/Linux it will be different, just google for it):

~/Library/Application Support/Sublime Text 2/Packages/Python/Python.sublime-build

Instead of calling the Python interpreter directly, I’ve piped this to a simple bash script which will handle that. The json file mentioned above contains one child attribute named “cmd”. Change that to a bash script of yours. Don’t forget to keep passing the filename as argument. This is how mine looks like:

“cmd”: [“/usr/local/bin/python-sublime-build”, “$file”]

And this is the content of my python-sublime-build file:

ps -A| grep $1 | grep -v $0 | grep -v grep | cut -d' ' -f1 | xargs kill -9
/usr/local/bin/python -u $1

Aaaaand that’s it. 🙂

There’re lots of different ways of doing it, but this one works for me. I could probably do everything in Sublime without using an external bash script but I’m feeling lazy today 😀

PS: Same principle can be applied to any other language. Just make sure that you edit the sublime build file accordingly (each language has one I think) and have a bash script for it.

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:
            cardtype = AnyCardType()
            cardrequest = CardRequest( timeout=1, cardType=cardtype )
            cardservice = cardrequest.waitforcard()
            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:

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

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 )


HC-06 Bluetooth mobule

Mindflex headband


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:

import serial
import sys
latestByte  = ('c')
lastByte    = ('c')
inPacket    = False
myPacket    = []
PLENGTH     = 0
def parsePacket():
  if checksum():
    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:
          PLENGTH = ord(myPacket[0])
        elif inPacket == True:
          if len(myPacket) > 169:
            print "Error: Data Error too long!"
            del myPacket[:]
            inPacket = False
            del EEGVALUES[:]
          elif len(myPacket) == PLENGTH + 2:
            del myPacket[:]
            inPacket = False
            del EEGVALUES[:]
        lastByte = latestByte
  except KeyboardInterrupt:
    if ser.isOpen():
if len(sys.argv) < 2:
  print "Mindflex datalogger by David gouveia <david.gouveia[at]gmail[dot]com>"
  print "Usage: %s " % sys.argv[0]

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 🙂