Tuesday, November 25, 2014

Not dead, just busy!

Happy thanksgiving holiday.
It's been some 7 weeks since my last post, simply because I've been pretty occupied with stuff at work and haven't come across anything really blog-worthy lately. But it's coming.

Some brief bits and pieces:
  • Been crazy-busy at work, including a server migration in a few days over the TG weekend. Huzzah for virtualization and how it makes migrations relatively simple. Ask me about it some time.
  • OSX Yosemite trashed my Mac, so I spent a day reinstalling the OS and then the whole build chain. My own blogs came in quite handy here, and I'm glad to say they're still quite applicable. The only annoyance was that virtually every package in the stack had an update: iOS 8 meant updating Xcode, meant updating to Yosemite, ... (the second upgrade from Snow Leopard to Yosemite went just fine, no sweat)
  • I've begun porting over an old jQuery Mobile application from 2012, into Cordova to form a mobile app. I don't expect much in the way of surprises, but it will be the most complex phone app I've ever done. Fortunately the already-working prototype provides a clear picture of expectations and some lessons on what works well and what can be streamlined.
  • Still no progress on trying to find a new HTML5 framework for building mobile apps. Just too busy on other tasks. Though the mental process is guiding me toward something very much like Ratchet but with a real page-turning behavior. (I mentioned that a while ago) I do hope to get some slack time soon to tinker around and find/invent something.
So yeah... Not a lot worth blogging, but a promise that more will come soon. :)

Thursday, October 9, 2014

Raspberry Pi binary clock

And as promised, here is my exciting, awesome world-changing invention... a Raspberry Pi application which shows the time... in binary! Okay, not that killer, but a simple project demonstrating some wiring, some code, and a visual output.

You'll need:


Hardware (GPIO, Wires, LEDs)

The circuitry itself is dead simple: just five LEDs in a row, with their anodes (+ side, long leg) connected to 5 GPIO pins and their cathodes (- end, short leg) connected to the GND. Just pick any five GPIO pins, connect your GND to the breadboard, and insert the LEDs.

Here it is, as both a photo and  a circuit diagram.



The choice of GPIO pins is up to you. I picked the 5 nearest the end of the bank on my B+.

Question: Why would I show only the last 5 bits of the time, instead of a nice nerdy number like 8? I didn't have 8 LEDs: I lost a bag of two LEDs and burned out another LED during an experiment, so I only had 5.

The RPi.GPIO Library

My favorite GPIO programming API, is RPi.GPIO

You can grab a copy and install it manually, here on its Python package page

Or you can let the package manager do it for you:   sudo apt-get install python-rpi.gpio


The Program (Python)

# CONSTANTS
LIGHT_PIN_0 = 21
LIGHT_PIN_1 = 20
LIGHT_PIN_2 = 16
LIGHT_PIN_3 = 12
LIGHT_PIN_4 = 26

# SETUP
import RPi.GPIO as GPIO
from time import sleep
from time import time as epoch

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

# initialization: setup the pins for output
# and set all pins HIGH for an initial blast of light, like how a car tests its lights
def init():
    GPIO.cleanup()
    GPIO.setup(LIGHT_PIN_0, GPIO.OUT)
    GPIO.setup(LIGHT_PIN_1, GPIO.OUT)
    GPIO.setup(LIGHT_PIN_2, GPIO.OUT)
    GPIO.setup(LIGHT_PIN_3, GPIO.OUT)
    GPIO.setup(LIGHT_PIN_4, GPIO.OUT)

    GPIO.output(LIGHT_PIN_0, GPIO.HIGH)
    GPIO.output(LIGHT_PIN_1, GPIO.HIGH)
    GPIO.output(LIGHT_PIN_2, GPIO.HIGH)
    GPIO.output(LIGHT_PIN_3, GPIO.HIGH)
    GPIO.output(LIGHT_PIN_4, GPIO.HIGH)

# convert an interger into binary, then pull out the 1s and 0s to light the pins
# count back from the end, so we get the last 5 digits; the first 5 digits won't change for years
def updateLightsFromInteger(value):
    bits = bin(value)
    GPIO.output(LIGHT_PIN_0, bits[-1] == '1')
    GPIO.output(LIGHT_PIN_1, bits[-2] == '1')
    GPIO.output(LIGHT_PIN_2, bits[-3] == '1')
    GPIO.output(LIGHT_PIN_3, bits[-4] == '1')
    GPIO.output(LIGHT_PIN_4, bits[-5] == '1')

# THE MAIN LOOP
# JUST SIT AND UPDATE THE BLINKY, AND WHEN IT'S TIME TO QUIT BE GRACEFUL ABOUT IT
if __name__ == '__main__':
    init()
    sleep(3)
    print("Running. Hit ctrl-c to terminate.")

    try:
        while True:
            sleep(1)
            value = round(epoch())
            updateLightsFromInteger(value)
    except KeyboardInterrupt:
        print('Shutting down')
        GPIO.cleanup()


Pretty darn simple, huh? Just keep looping forever, fetching the time and converting it into 1s and 0s for the lights. And I'm almost ashamed at how cute and entrancing it is... shiny...

For yourself, feel free to pack the LEDs more tightly and add a few more. With only 5 bits, it recycles every 32 seconds, but if it has 12 it would recycle every 4096 seconds (68 minutes).


My next project should be more interesting. As soon as I quit... watching the... blinky... lights...

Monday, October 6, 2014

Raspberry Pi and a brief primer on GPIO (still coming, a binary clock!)

I mentioned that I got my Raspberry Pi B+ last week. Sadly I've had fairly little free time to play with it. Still, a few days ago, about 24 hours after I received it, I put together a cute program I thought I'd share. It's a clock that counts out the time in binary. Nothing too earth-shaking, but a little more involved than the tutorials.


Before I get into that project, though, I want to lay out some information on how GPIO works.

My goal is to provide a tutorial and technical explanation, for those who already know what a Python comment is, but who need something more meaty than "here's a photo my my Pi, now copy-paste this Python code" The tutorials are cool, but they often lack background information and (for example, in my first project) I had to find a different site to explain how GPIO ports really work since the light wasn't blinking when it should have been.

First off, go find a copy of the Raspberry Pi GPIO diagram for your model. My personal favorite is this one for the B+. And I'll assume that you know a little bit about electricity, e.g. that GND means "ground" or "negative terminal".

GPIO ! OMG !

What's GPIO? General Purpose Input and Output. It means that there's a bank of pins on the computer, and that these pins can be connected to things that generate input (buttons, thermometers, motion sensors) and to things that generate output (LEDs, motors and relays, radio transmitters). The GPIO bank also has several pins to act as grounds (- terminals) and power supplies (+ terminals at both 3.3V and 5V).

What decides whether a GPIO pin is input or output, and when it generates voltage? Software! That's the awesome part. The same GPIO pin may attach to a button (input) in one program or to a LED to light up (output) in another program, and that choice of behaviors is controlled by your Python program.

GPIO Output

In Output mode, what defines whether a GPIO output is on or off?

Well, that's a little more involved...

When a GPIO pin is defined as Output (or GPIO.OUT in Python) the pin can be in either a High state or a Low state (GPIO.HIGH and GPIO.LOW, or True/False, or 1/0).
  • When it's in a High state the pin is generating +3V DC If you connect that pin to the anode (+ side) of a LED and connect the LED's cathode (- side) to the ground, the LED would light.
  • When it's in a Low state, the pin is grounded and acts as a negative terminal. In this case, you could still connect an LED but the - would go to the GPIO pin and the + would go to a power source.
So it's not quite as simple as "on and off" or "the LED lights when the pin is High" as much as "the GPIO pin will go to +3V (High) or to 0V (Low), and the behavior of your circuit depends on the structure of your circuit"

Check out the following photo and diagram.



In my initial experiments, I simply didn't quite grok this simple relationship between voltage and tyhe High/Low state, and I had plugged in an LED backwards. As a result, High meant that the LED was off and Low turned it on -- the opposite of my intent! It all makes sense now that I know these basics.


GPIO Input

When a GPIO pin is set to receive input, what is it looking for? A button being pushed, or what?

When a GPIO pin is set to GPIO.IN mode, it listens for incoming voltage, e.g. +3V being applied to the GPIO pin. When there is voltage coming in, the pin reads High. And when there is no voltage... it reads randomly!

A pin in GPIO.IN state is floating, meaning that it is not clearly energized to +3V nor is it clearly grounded out. If you have a Python program doing While True: print input(12); you'll see that the input fluctuates between 0 and 1, even if there's nothing connected to the pin at all!

This is not a signal from your button, but simply line noise. To correct for this, you must pull down the line voltage to force it to clearly be Low. This means to connect the GPIO pin to ground so it is constantly draining voltage (and constantly reads 0 or Low), until such time as you hit the switch and connect +3V to the GPIO input.








It's not as convenient as having just the button that is clearly reading High or Low. On higher end hardware they have cleaner line voltage and built-in pull down mechanisms. But not here.

That resistor is important! When you engage the switch, you're connecting +3V directly to GND, and that's a short circuit. Putting in the resistor, reduces the voltage sufficiently so as not to reboot your Raspi with a short circuit, while also "encouraging" the power to flow up the GPIO pin.


So Now What ?

Well, those are the rudiments of GPIO, that took me an evening to figure out. Hopefully it saved you some time.

Coming shortly, the walkthrough of my binary clock.

Saturday, October 4, 2014

HTML5 mobile framework: part 3, Bootstrap & Ratchet

Sorry to keep splitting up threads here. A few weeks back, I posted that we're using jQuery Mobile to make our mobile apps, and that while it's good it's not awesome. So the R&D continued for a new HTML5 framework to build our mobile apps using Cordova/Phonegap.

Again, it's opinions and impressions as I try things out to see how they fit our needs. If your opinion varies please share it in the comments! I'd love your input on HTML5 and hybrid mobile apps.

Here's the next one I tried out (this was a good 3 weeks ago): Ratchet.


Bootstrap / Ratchet


Bootstrap is a rich set of CSS classes and mobile-friendly behaviors. It looks a little bit cartoonish for my tastes, and it really stands out where it's in use, but it is the current vogue and it is quite flexible as far as modifying the theme. You start with a rich set of utility classes but you're not constrained to use only what you're given. That counts for a lot!

However, Bootstrap is not a mobile development framework. There is no page swapping, no interception of # hyperlinks to swap which panel/page is currently showing, and so on. And while it is mobile-friendly and responsive, it is not designed to "look native".

Ratchet attempts to fill this gap by adding more CSS classes for listviews, thumbnail icons, badges and mini icons that float to the right-hand side, and so on. Ratchet was created for quickly prototyping mobile apps using HTML web pages: "visit this URL; after we create the app, here's what it would look like."


I was quite excited to find this, since my own idea had been to write some jQuery wrappers over Bootstrap to roll our own framework. But as they say, why reinvent the wheel? (obviously a phrase from before we had Github, where literally thousands of projects are out there reinventing wheels)

What I saw, got me excited quickly:
  • It's pretty, it's pure CSS. It's tiny. It's a superset of Bootstrap.
  • We're not tied down to a specific development technique. It's just CSS.
  • The documentation is quite well organized, and there's not much of it.
  • Separate CSS for iOS and Android, trying for a more-native look. Using Cordova's merge capability, this could turn out well.
  • A nice set of glyphicons.
  • Again, it's just a bunch of CSS, so could work with any programming and eventing toolkit, e.g. jQuery. (I repeat this cuz it's really core to the uber-flexible "style first then redesign repeatedly" approach we need)
  • There's virtually no overhead, so rendering and response is quite swift.
But then things took a turn as I tried to use it to develop a real app:
  • No events. We'd need to add jQuery to add click and tap handlers, which is fine. Then again, this could be addressed with TouchSwipe, adding swipe and pinch handlers to jQuery. Not a problem, but does illustrate that Ratchet is intended for prototyping apps, not for building real apps.
  • The prefab behaviors do not include popup dialogs. Again, not killer but if we want to show a Please Wait there's no supplied way to do that.
But then the show-stopper!
  • All that page-changing behavior is done with Push.js, which loads HTML pages from the server. It does not (as far as I could tell from the source and the docs) in any way support switching pages within the document. You're loading up HTML pages, not switching visibility to show and hide a specific panel.
  • This means that you can't just switch over to the results page; you load results.html from the server (or from the in-app device storage)... but without any of your DOM changes. A typical use case, is a search function which populates a results list on another page, then switches over to that page. Even if you got the page-change timing right so the results content were visible at the right time... switching away from the results and then back again would effectively lose the results.
So ultimately, we had to say no here and shelve it. Push.js is cute for what it is, but isn't suitable for even a moderately simple use case of showing/hiding/adding DOM elements in another panel. (again, Ratchet doesn't claim to be this)

But it's not over...


Still, I'm reluctant to let it go entirely. My current line of thinking, is to make a fork of Ratchet minus Push.js, then replace Push.js with something that simply switches which <div class="page"> is currently visible. Given this, we would have a nice set of CSS utility classes and a homegrown page-management framework. All that's missing is support for dialogs, which doesn't sound difficult on the surface.

So this one was shelved, but remains on the radar. It's the closest thing I've found so far, to the ideally-minimal CSS toolkit we need. I'm gonna try out a few more such as Ionic and Sencha,before I go for reinventing a framework.

Wednesday, October 1, 2014

My first tastes of Raspberry Pi (and next, a binary clock project!)

I received my Raspberry Pi on Monday night. It's quite nifty.

What Is It ?


A Raspberry Pi is essentially a small computer, the size of a pack of playing cards. It has a microprocessor (ARM 700 MHz), 512 MB of RAM, 4 USB ports, and an Ethernet adapter... and it can run Linux. That means that any USB stuff that works on Linux should work here, e.g. wifi adapters, packet radio adapters, even a GSM adapter for cell service. Even better -- it has a bank of GPIO and I2C slots so you can plug in physical inputs and outputs such as temperature sensors, motors and relays, motion sensors, cameras, LEDs, LCD readouts, touchscreens, and serial I/O such as GPSs. And it all runs off a USB phone charger, and doesn't even have a fan to make noise.

More info here:  http://www.raspberrypi.org/products/model-b-plus/

The whole concept of the Raspberry Pi is a dirt-cheap prototyping platform. Remember those electronics kits we had as kids, where you wire up resistors to antennas and make a crystal radio? Same idea, except one of the components is a Linux computer connected to the Internet. And that computer has 26 software-controlled input and output ports.

And of course, there's a real thrill and "tee-hee" value to a working computer that's the size of a hamburger patty, which runs X Window and a SMTP server and a MySQL server, and just about anything else that runs under Debian Linux.

Anyway, it's not really map related at all but is some cool stuff. In upcoming weeks, expect a few raspi postings mingled in with my usual map postings and my (overdue) series on choosing a HTML5 framework for mobile dev.

Thursday, September 25, 2014

Shellshock! A forgotten feature becomes a major security hole

My prior post, was that my next series would be about HTML5 frameworks for mobile. But I've been busy on other projects, and mobile stuff hasn't been on the high-pri list. Speaking of today's high-pri list, how about that Shellshock bash bug?

I'm gonna jump on the bandwagon a bit here,  and admit that this bug should scare the heck out of you. If you run anything that hands out shells to the unknown Internet, then anybody smart enough to make a fake User Agent can run arbitrary shell commands on your server. I tried it and verified it: it took me 30 minutes to write a working exploit, starting from when I first typed "bash bug" into Google.

In a Nutshell


What is the "bash" Unix shell? Briefly, this means "the thing that's used to type commands after you connect via SSH" but for web folks working in PHP this also means "the thing used to execute command-line scripts such as passthru() and the `` operator" If you use shell_exec() et cetera then you're using a shell, and it's probably bash.

Bash has a feature going back some 25 years, that it can auto-execute code when you start a new shell. This code will conveniently set "environment variables" which facilitate other work. The problem with this very-obscure feature, was only discovered last week: Web programs such as CGI and PHP also set environment variables, some of them read directly from the browser without any sanitization or checking. So any browser on the Internet, may be able to:
  • Send an environment variable that will be passed as-is to your shell. The most common such variable would be your User Agent (your browser's name), which is loaded as-is into an environment variable called HTTP_USER_AGENT
  • Which your shell would then interpret as a command to be executed before it executes your shell command.
But that means technical skill to set your browser's User Agent, right? Wrong. Browser add-ons already exist to set your User Agent string to some common values (Firefox can pretend it's GoogleBot) and it's also trivially simple to set it in your browser's config. (Firefox is described below) Again, I hadn't heard about this bug before today and it took me about 30 minutes to craft an exploit against one of our servers which was vulnerable.

The Limits


The exploit allows command execution, only if the following conditions are met:
  • A remotely-executable program exists which does not require trust and authentication, e.g. a PHP script or a CGI script which executes under bash. Services which do not execute shells, or which execute them only for trusted individuals, are of significantly less concern, e.g. FTP and MySQL servers don't run subshells and don't read user-supplied data for environment variables anyway, and SSH only gives you a shell after you have logged in.
  • That program executes a subshell. In PHP this is the `` or shell_exec() functions. Any program which does not use those functions is fine... until you need to use those functions.
  • The system's default shell /bin/sh is in fact Bash and not an alternative such as ksh or dash. On Ubuntu 12.04 /bin/sh is in fact Dash and is not affected by this bug unless you have a CGI script which specifically uses Bash.

A Quick Test

Login to your server, and run this from your shell:
env x='() { :;}; echo vulnerable' /bin/sh -c "echo this is a test"
Hopefully you'll see an error about a function definition:
    ./bash: warning: x: ignoring function definition attempt

If you see "vulnerable" in the output, then your system shell is Bash and is a version which is potentially affected by this issue. And remember, it's not Bash here at the command-line that should worry you, but any web program which launches shells.

If you don't see vulnerable, you may not be entirely safe. Try again, this time replacing /bin/sh with /bin/bash Even if Bash isn't your system default shell, any CGI programs or launched shells whicyh specifically use Bash may still be affected.

A Quick Exploit (A)

Like I said, it's not rocket science, just setting your User Agent.

Load up Firefox.

Go into about:config Create a new value (or edit if it already exists) called
general.useragent.override
and set it to this odd-looking string:
() { :; }; touch /tmp/shellshock
Congratulations, your browser will now supply an auto-executing function in the environment... if you hit up something that spawns a subshell.

On your webserver, try creating this very small PHP program. Or, try simply hitting any program of your own which uses shell_exec() or similar functions.
<?php
# anything that uses any shell function, will trigger the bad HTTP_USER_AGENT variable
print "Tmp Folder:\n";
passthru('/bin/ls /tmp');

Now visit that PHP program in your browser, and then have your sysadmin check out the new /tmp/shellshock file. And imagine for a moment what happens if someone were to do this repeatedly, and knew their way around a shell.

P.S.: Don't forget to "reset" that User Agent override when you're done.


Another Quick Exploit (B)

For command-line wonks, here's an even simpler version of the exploit using cURL from the command line:
curl 'http://www.example.org/whatever.php' -H 'User-Agent: () { :; }; touch /tmp/shellshock'
Point it at any web service which uses a subshell (e.g. a PHP using shell_exec() ) and they'll be surprised to find a new file on their server.

Okay, I'm Scared... Now What?

The most expedient fix, is to upgrade bash. There is already a patch (4.3-25) available.

This page gives practically copy-and-paste instructions:
    https://news.ycombinator.com/item?id=8364385

Now give everything a test again, and breathe a sigh of relief!

Update: Looks like the 25 patch to Bash fixes only one of two so-far-determined methods of attack. A second version has been named CVE-2014-7169 and is not fixed by 4.3-25  The "A Quick Test" for this second vulnerability is:
env X='() { (a)=>\' sh -c "echo date"; cat echo
If the output has the date in it, then the date command was executed and you're still vulnerable.



Thursday, September 18, 2014

What HTML5 mobile framework to use?

Yeah, it's been a month. Again, been working instead of talking about working. :)

Today I'll start touching on a topic as emotionally charged as religion and politics... a choice of HTML5 mobile frameworks for use with Cordova/Phonegap. That's me, always the troll, pushing the envelope of good taste and social acceptability, pushing buttons just to get a reaction. ;)

I've been using jQuery Mobile, but it has some bugs, and isn't exactly swift and fluid; on the other hand, it does have some nice button icons and default styles, and works well with jQuery. But there are other HTML5 mobile frameworks out there which may be more fluid, less buggy, have richer icons and styles.

So this next series of postings isn't really a "How I did it" sort of tech bragging, as much as current opinions on several HTML5-for-mobile setups. Some of them are subject to change as I learn something later, so if your opinion differs, this is a place where your comments would be appreciated!

Our Needs

jQuery is very visual -- you start with a HTML mockup and then you make it interactive. This is how our clients and designers think. They start with cosmetic mockups and designs, which will change often (sometimes 2-3 times in a week) as more visually-thinking people give input and do 180-degree spec changes. The "real programmers" shudder when I press the point, that the design (as implemented in HTML) defines the application, and that project specifications are typically defined after the fact based on budget leftovers and feedback. But that's the reality. We don't need a framework to build apps out of widgets, as much as a HTML/JS toolkit for making app-like behaviors starting with HTML.
  • We're building our apps with Cordova / Phonegap. Virtually everything should work well with Cordova, but then again let's not presume. If the final product doesn't work well once we've plugged it into Phonegap and tried it on a few devices, it's a loss. (see Ionic in a future posting)
  • The HTML/JS API must not be dogmatic, forcing us to use prefab widgets that cannot be quickly customized. The designers and the clients decide what we do; they can be quite capricious, and we never say no to any customization. If they want THIS selector to have its handle on the left while OTHERS have the handle on the right, that needs to happen and pronto. Right off the bat, this means that a lot of programming-heavy frameworks which let you "just tie widgets together" via a configuration file, are right out. (see Sencha in a future posting)
  • But that said, we  do want the prefab widgets... just ones that we can ignore or modify, preferably in HTML. Utility classes are awesome, and so are glyphicons. (see jQuery Mobile and Ratchet in a future posting)
  • We do most of our programming in jQuery, so anything that plays well with jQuery is a big bonus.

jQuery Mobile


Well, let's start with the framework we are already using.

- Good. It's highly visual. As I described above, you start with your HTML and then program behaviors into it. This fits perfectly into the paradigm of our project managers, designers, and clients.

- Good. A very large community and great documentation. There isn't much about jQuery Mobile that remains mysterious after five minutes in Google and StackOverflow and/or ten minutes with JQM's docs. We still need to do some tedious CSS discovery sometimes, but 90% of questions have already been answered.

- Good. Page management. Attractive cross-platform CSS. Decent widget set. Custom event handlers and DOM manipulation. It's pretty sweet.

- Bad. It's a little slow. Even with FastClick, there is a noticeable lag between tapping a button and going somewhere. I've tried changing the delay, disabling page animations, FastClick of course, ... It's not killer slow, but it's not really smooth.

- Bad. Rendering bugs. I find myself implementing corrective CSS on every new project. a) Hyperlinks that are a[data-role="button"] has a visible underlines on the text. This is easily corrected in CSS, but seems a silly thing to need to correct. b) Buttons in the header, will sometimes "stick" in their highlighted/active state long after the finger has moved on, sometimes even after switching to a different page, and then coming back minutes later. This means that the active color needs to be the same as the inactive color (CSS fixes), which sort of misses the point.

- Mediocre. The data-role paradigm is nice, but not as rich and flexible as a good set of utility classes, e.g. class="button button-panic button-wide"  We get two themes (data-theme="a" and data-theme="b"), but need to write custom HTML to simulate a third theme if we want a third button color (but need to replicate that for header buttons and so on. By comparison, Bootstrap and Ionic have several types of button.

- Dicey. Lazy rendering. One of the first executing statements in our programs is $('div[data-role="page"]').page() to effectively disable lazy rendering. Our typical use case, is that a listview needs to be populated programmatically, but we cannot guarantee that the user has previously visited the page and caused the listview to render into DOM, allowing the refresh to happen. Lazy rendering is intended to reduce memory usage, but realistically it's just a race condition waiting to happen.


So, what are other options? That's the focus of upcoming articles...