Fly4Free deals filter – The Chrome Extension

I love to travel.

Because of this, I can spend lots of time searching for the best deal I can find on a given destination. Fortunately there are several web ninjas that simplify this hard task for you. Some of these ninjas, are the guys from Fly4Free.

Checking on their website on a regular basis is quite trivial and they do have everything categorized, but I wanted to take it one step further to the ultimate lazy level 🙂

Actually, I was also looking for an excuse to learn how to create Chrome extensions and this sounded like the perfect one.

 

Screen Shot 2016-09-14 at 12.12.03

The workflow is pretty simple:

a) Download the RSS feed.

b) Look for interesting keywords ( you can customize which ones ) such as destinations.

c) Create a notification with this information.

d) Store the current information for later presentation.

 

 

The chrome extension is open source, so feel free to improve it or just check it out either on the chrome store or on github

Controlling relays using Micropython and an ESP8266

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):
  RELAYS[int(pin)].value(int(value))  
  return "PIN %s set to %s" % (pin, value)
 
def parseURL(url):
  #PARSE THE URL AND RETURN THE PATH AND GET PARAMETERS
  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), '')
    else:
      break
 
  return path.group(1), parameters
 
def buildResponse(response):
  # BUILD DE HTTP RESPONSE HEADERS
  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('0.0.0.0', 80)[0][-1]
 
s = socket.socket()
s.bind(addr)
s.listen(1)
 
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"))
    else:
      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)))
      else:
        cl.send(buildResponse("UNREGISTERED ACTION\r\nPATH: %s\r\nPARAMETERS: %s" % (path, parameters)))
 
    cl.close()

 

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. http://192.168.4.1/setPinStatus?pin=0&value=1

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!

ZSUN Wifi card reader part 2 – EAGET A50

This is going to be a quick one.

Remember ZSUN Wifi Card reader? It seems that there’s a new device that does the same thing. In fact it does look like a clone:

 

EAGET

 

I just bought one of these from a Chinese supplier. It costed $7.5 USD and it does exactly the same. Using NMAP to scan for open ports I get the same results. So it was not surprising when I got access to it using the very same password “zsun1188”.

Screen Shot 2016-04-21 at 20.40.08

 

In order for you to flash the existing firmware you need to edit /etc/producttype and replace the A50 for SD100.  The rest of the process should be pretty straight forward.

 

Enjoy your dirt cheap new router 🙂

How to setup Ozone Strike Battle keyboard on OSX

Today I decided to buy a mechanical keyboard. I was looking for a minimalist TKL and the one I picked was an Ozone Strike Battle with brown cherry mx switches. What I wasn’t counting on is the crappy support provided by a vendor that could render useless a simple device just like a keyboard.

 

The first time I plugged the keyboard in my macbook, the keys were completely messed up. And I’m not talking about the symbols or special keys. Several keys were bound to the same value and some others didn’t even have a valued assigned.  After spending a few minutes googling, I found a thread that gave me the first hint about what was happening. Unfortunately this didn’t work for me and it took me some time to understand why. It seems that newer keyboards have different ids which are not configured. The solution was to clone the repository found in the previous link, use their tool to detect the bcdDevice, add it to the config and compile the kernel extension.

 

I’m not an expert and it took me a couple of hours to do so because I couldn’t find the right sources for one of the dependencies that are required – IOKit – but once I did it, everything worked as expected and right now I’m writing this post using my new mechanical keyboard 🙂

 

good meme

 

Step by Step: How to make it work for you?

  • Navigate to the link mentioned above and download the kernel extension mentioned there ( or use this direct link )
  • Try to installed it. If you’re using El Capitan, you’ll have to disable System Integrity protection to load the kernel extension. Try the following:
    1. Reboot your computer and press cmd + R during boot to enter recovery mode.
    2. Open a console and type csrutil disable; rebootThis will allow you to use kernel extensions that were not signed by Apple.
  • If you are running a previous version of OSX, then you can just do sudo nvram boot-args=kext-dev-mode=1
  • Load the extension: kextutil -v /System/Library/Extensions/IOUSBHIDDriverDescriptorOverride.kext
  • Plug in the keyboard. If your keyboard is now responding correctly then everything is OK. If not, you might have one of the new versions that have a different bcdDevice.  You can download this custom version  of the kernel extension that I compiled and see if it works for you: http://davidgouveia.net/goodies/IOUSBHIDDriverDescriptorOverride.kext.tar.gz

If you want to compile it by yourself, make sure you have xcode installed and ruby 2.2.0.

brew install libusb
bundle install --without ""

rake scan
  • Check the idVendor, idProduct, and bcdDevice. Open the Info.plist file, locate the blocks of code related to the strike battle keyboard ( just search for “strike” ). Change those blocks of code to match the idVendor, idProduct, and bcdDevice values that you found using the previous command.

Screen Shot 2016-03-27 at 12.52.16

  • Compile the code using the instructions that you can find on the repository’s README.md:
# dependencies
gem install bundler
bundle install --without scan

# build
xcodebuild
sudo cp -r build/Release/IOUSBHIDDriverDescriptorOverride.kext \
    /System/Library/Extensions
sudo kextutil \
    /System/Library/Extensions/IOUSBHIDDriverDescriptorOverride.kext

This is it, you should now have a working kernel extension that suits your needs. Enjoy your new keyboard 🙂

Avoid being locked out of your ZSUN wifi reader

zsun

I was one of the guys that got the Zsun fever 🙂

I’m not going to get into details. For those you can check the Warsaw Hackerspace’s website. Those guys did an awesome job compiling information related to this tiny yet powerful device.

Originally it comes with a custom firmware that provides you with an access point that can be used to share files ( it has a microsd slot ). By flashing OpenWRT it allows you to unleash all it power and use it to several different things (access point, range extender, file server using different protocols, IoT, Tor server,  you name it), but since you can only access it via wifi ( there’s a physical ethernet port that you can use if you don’t mind tearing apart the case and solder an ethernet jack)  it can be very easy to lose access to the devices.

I’ve seen some people talking about a trick using the sd card slot during boot to force a software reset but it didn’t work for me, so I just decided to do something different.

 

The approach is easy. Create a script  that is loaded on boot and checks for a file on the memory card. If it’s there, then it issues a firstboot command to reset everything. This is similar to the update process of several gadgets and it’s easy to implement.

 

1º Flash the OpenWRT firmware ( check the hackerspace link )

2º Open the web interface. Enable the SD card automount feature and mount it on /mnt/sda1 (this should be the default). Enable enable SSH.

3º Log on using SSH. Create a file called restore inside /etc/init.d/ and dump the following contents there:

 

#!/bin/sh /etc/rc.common
# Copyright (C) 2009-2012 OpenWrt.org
 
START=50
 
start() {
  if [ -f "/mnt/sda1/restore" ]
  then
    echo "y" | /sbin/firstboot
    rm /mnt/sda1/restore
    /sbin/reboot
    echo "Rebooting to apply changes"
  fi
}
 
stop() {
  echo "Stop action not used."
}
 
reload() {
  echo "Reload action not used."
}
 
shutdown() {
  echo "Shutdown action not used."
}

 

4º Save the file and change the permissions to 755 ( chmod 0755 /etc/init.d/restore )

5º Enable the script on boot. To do so execute the following command: /etc/init.d/restore enable

And that’s it. If for any reason you mess up the wireless interface and lose access to the device, all you have to do is create a blank file inside the SD card called restore and the next time you boot the device it will detect this and force the reset.

Warsaw Hackerspace: https://wiki.hackerspace.pl/projects:zsun-wifi-card-reader

 

esp8266 Witty ( kind of ) intro

A couple of months ago a new development board based on the popular esp8266 was created.

It seems like a compact version of the popular nodemcu board that includes an RGB led and an LDR. It is called esp8266 witty ( you’ll find them for just a couple of dollars on ebay or aliexpress) and the idea was to split the UART interface into a dedicated board that can be attached to the esp8266 whenever you need to program it or access the serial interface to read data (clever design guys).

The board comes with a custom firmware flashed which I honestly didn’t try to explore because I’m used to nodemcu firmware. Connection was established using the ESPlorer at 115200bps. After connecting this is what we can see:

Welcome screen ESPlorer esp8266 witty version

Flashing the nodemcu firmware is straightforward just like any with any nodemcu dev board… keep the flash button pressed while pressing reset and use the esp tool to flash the firmware:

esptool flashing esp8266

And there you go, nodemcu firmware is now running:

nodemcu firmware flashed by esptool.py

On a side note, the baud rate changed from 115200 to 74880. This is an unusual value for it, but if it doesn’t work for you, just play with the values until you find what works for you.

I couldn’t find a lot of documentation regarding this module and how to access the LDR and the RGB led. Fortunately it was very easy to find out.

The esp8266 modules have a single pin with analog reading capabilities ( pin 0 ) and that was it. For the digital pins controlling the led channels all I had to do was a simple for loop to iterate over all the digital pins and find out which ones were triggering the blue, read and green channels. It ended up being pin 6, 7 and 8.

The following lua snippet will output green under good light conditions and red under low light:

-- Output pins:
-- 6: Green
-- 7: Blue
-- 8: Red
 
-- Input pins:
-- 0: LDR
 
 
function clearOutput()
  for i=6,8 do
    gpio.mode(i, gpio.OUTPUT)
    gpio.write(i, gpio.LOW)
  end
end
 
 
tmr.alarm(1, 1000, 1, function()
  -- Output LOW on all channels
  ldr_value = adc.read(0)
  print(string.format("Current LDR value: %d", ldr_value))
 
   clearOutput()
   if ldr_value > 600 then
     gpio.write(6, gpio.HIGH)
     gpio.write(8, gpio.LOW)
   else
     gpio.write(6, gpio.LOW)
     gpio.write(8, gpio.HIGH)
   end
 
end )

Have fun! 🙂

Useful links:
esptool.py – https://github.com/themadinventor/esptool
nodemcu firmware binaries – https://github.com/nodemcu/nodemcu-firmware/releases
ESPlorer – http://esp8266.ru/esplorer/

NodeMCU based Greenhouse Controller

Winter is coming!

A few days ago I started a new project to help me take care of my peppers. Winter is coming ( pun intended ) and unfortunately it’s a bit harsh here in Portugal for people who likes to grow peppers, specially tropical strains that are used to good weather.

For that reason, it all started as simple thermostat that could tell me the temperature over the internet but soon lots of other ideas started to pop up in my mind. So I started developing a tiny appliance that could allow me to control a few things and that’s how this project started.

I don’t plan on creating something super fancy and for that reason these are the initial hardware requirements:

  • NodeMCU
  • DHT11 – Temperature and Humidity sensor
  • Digital light sensor
  • 3v Relay module with four relays
  • 16×02 LCD module with an I2C adapter

The idea is very simple: The NodeMCU will create a tiny web api that can be used to retrieve data about the sensors and trigger the relays. That information can also be seen on the LCD so that you can check the sensors when you enter the greenhouse.

The webapp will output the information in json format so that you can easily integrate it with another application.

NodeMCU Greenhouse Controller

I’ll post the rest of the howto in the next days but feel free to check the repository containing the code. If you can contribute with ideas or some code, feel free to! 🙂

https://github.com/zatarra/nodemcu-greenhouse-controller

Unlocking Netflix contents on OSX – The easy way

Netflix was launched here in Portugal one day ago. I was really excited because I was finally going to be able to get an account and start enjoying all the contents that they have to offer.

That was until I checked the catalog…

Currently the catalog has 354 movies or tv shows which is a very poor selection. I didn’t want to turn to VPNs or DNS services that could route traffic through their services but unfortunately I had no choice. Since I work in security, I know how these things can turn south like people found out recently.

But the truth is that I need to trust in a foreign node at some point because without a US IP address netflix wouldn’t show me the full catalog. Searching for netflix and DNS the first link that popped up seemed exactly what I was looking for except that I didn’t want to use their DNS servers for all the requests ( again, security ringing a bell ) a vector for Pharming attacks.

So the idea was to use one of those DNS providers that route traffic through their servers whenever we wanted to access netflix, but only for netflix related requests. Sure I could just setup a DNS server and create a custom zone for netflix but that seemed an overkill. That is how I discovered that OSX supports a feature which allows you to do exactly that: the “/etc/resolver/” folder.

The idea is simple, you just create a folder ( if it doesn’t exist already ) and create a file inside it using the name of the domain that you want to use custom DNS servers. Inside that file you just put the address of the custom DNS servers for that domain and you’re all set!

laptop:resolver xxxXXXxxx$ pwd
/etc/resolver
laptop:resolver xxxXXXxxx$ ls -altr
total 8
drwxr-xr-x  95 root  wheel  3230 Oct 22 09:31 ..
-rw-r--r--   1 root  wheel    51 Oct 22 09:32 netflix.com
drwxr-xr-x   3 root  wheel   102 Oct 22 10:14 .
laptop:resolver xxxXXXxxx$ cat netflix.com
nameserver 46.101.36.120 
nameserver 46.101.149.135
laptop:resolver xxxXXXxxx$

In this case I used the IP addresses of tvunblock but you can try other ones.

Bear in mind that if you use tvunblock, you need to open their website from time to time to keep active your IP address.

Enjoy your improved list of contents 🙂

How to use Sublime to develop and run code without launching duplicate processes

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:

#!/bin/bash
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.

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