A couple of weeks ago a friend introduced me to a dirt cheap wifi enabled mains switch. I’ve been creating my own wifi switches for a few years now but at $5 it is not worth it anymore for me to spend time adding electronic modules to make one.

The original device comes loaded with a firmware that can be used with a specific piece of software.  Now  I don’t know about you, but I rather run my own stack of software on it because I do have some trust issues, specially when I have no idea who’s behind the software development.

 

Fortunately there are several tutorials that you can explain everything you need to know to upload a custom firmware. This was the one that I used. TL;DR: solder a 5 pin 0.1in header to access the UART port and use one of those usb->uart converters.

 

 

My requirements were pretty simple: A tiny webserver should be up and running  ( connecting to my home network ) exposing two or three endpoints ( enable, disable, status ). This is the result:

 

 

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
 
const char* ssid = ".....";
const char* password = ".....";
 
ESP8266WebServer server(80);
 
const int led = 13;
bool relayOn = false;
 
void handleRoot() {
  digitalWrite(led, 1);
  server.send(200, "text/plain", "hello from Sonoff\nRelay status:" + ( relayOn ? String("ON") : String("OFF") ) );
  digitalWrite(led, 0);
}
 
void handleNotFound() {
  digitalWrite(led, 1);
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i = 0; i < server.args(); i++) {
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
  digitalWrite(led, 0);
}
 
void setup(void) {
  pinMode(led, OUTPUT);
  pinMode(12, OUTPUT);
  digitalWrite(led, 0);
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");
 
  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
 
  if (MDNS.begin("esp8266")) {
    Serial.println("MDNS responder started");
  }
 
  server.on("/", handleRoot);
  server.on("/enable", []() {
    turnOn();
    server.send(200, "text/plain", "Relay enabled");
  });
  server.on("/disable", []() {
    turnOff();
    server.send(200, "text/plain", "Relay disabled");
  });
  server.on("/toggle", []() {
    toggleRelay();
    if ( relayOn )
      server.send(200, "text/plain", "Relay enabled");
    else
      server.send(200, "text/plain", "Relay disabled");
  });
 
  server.onNotFound(handleNotFound);
 
  server.begin();
  Serial.println("HTTP server started");
}
 
void loop(void) {
  server.handleClient();
}
 
void turnOn() {
  digitalWrite(12, HIGH);
  relayOn = true;
}
 
void turnOff() {
  digitalWrite(12, LOW);
  relayOn = false;
}
 
void toggleRelay() {
  if ( relayOn ) {
    digitalWrite(12, LOW);
    relayOn = false;
  }  else {
    digitalWrite(12, HIGH);
    relayOn = true;
  }
}

 

 

There’s a GPIO pin that you can use for things like 1wire protocol devices ( e.g. ds18b20 temperature sensor, or a DHT22/11 ). I’m planing to add that to this simple sketch. In the meantime feel free to check out the repository . All of the updated will be there.

 

PS: Yes, I know the code is ugly, but that was not the point. Feel free to change it and improve it!

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.

rubber-ducky

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.

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 🙂

 

Issues

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

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 &lt; 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]) &lt;&lt; 16 | ord(myPacket[c+1]) &lt;&lt; 8 | ord(myPacket[c+2]))
        i += 26
      elif ord(myPacket[i]) == 0x80:
        EEGRAWVALUES = ord(myPacket[i+1]) &lt;&lt; 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&amp;255) &amp; 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() &gt; 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) &gt; 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) &lt; 2:
  print "Mindflex datalogger by David gouveia &lt;david.gouveia[at]gmail[dot]com&gt;"
  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

While I was looking for the smallest Arduino available on the market I stumbled on a website from a guy called Fabio Varesano that has developed a tiny one called Femtoduino. Not only he released the schematics, but he also gave the list of components as well as the board. Thanks Fabio!

You can check all the details on the official website: http://www.varesano.net/projects/hardware/Femtoduino

Now I know that snatching a PCB this is the hardest part since they are so small that they are not easy to build at home. So I talked to a local company and I order small batches of 10 PCBs and I can ship them to you for a total cost of 10€ each (including S/H). Ordering all the components from Mouser and assembling it yourself will cost you less than 20€ which is substantially less than the price charged by the website: http://www.femtoduino.com

So, if you are interested, drop me an e-mail (or comment below). Don’t forget that if you really appreciate this project, buy Fabio a beer ( paypal: [email protected] )