| Andrew Cooke | Contents | Latest | RSS | Twitter | Previous | Next

C[omp]ute

Welcome to my blog, which was once a mailing list of the same name and is still generated by mail. Please reply via the "comment" links.

Always interested in offers/projects/new ideas. Eclectic experience in fields like: numerical computing; Python web; Java enterprise; functional languages; GPGPU; SQL databases; etc. Based in Santiago, Chile; telecommute worldwide. CV; email.

Personal Projects

Lepl parser for Python.

Colorless Green.

Photography around Santiago.

SVG experiment.

Professional Portfolio

Calibration of seismometers.

Data access via web services.

Cache rewrite.

Extending OpenSSH.

Last 100 entries

Santiago 30m Bike Route; Mapa de Ciclovias en Santiago; How Unreliable is UDP?; SE Santiago 20m Bike Route; Cameron's Rap; Configuring libxml with Eclipse; Reducing Combinatorial Complexity With Occam - AI; Sentidos Comunes (Chilean Online Magazine); Hilary Mantel: The Assassination of Margaret Thatcher - August 6th 1983; NSA Interceptng Gmail During Delivery; General IIR Filters; What's happening with Scala?; Interesting (But Largely Illegible) Typeface; Retiring Essentialism; Poorest in UK, Poorest in N Europe; I Want To Be A Redneck!; Reverse Racism; The Lost Art Of Nomography; IBM Data Center (Photo); Interesting Account Of Gamma Hack; The Most Interesting Audiophile In The World; How did the first world war actually end?; Ky - Restaurant Santiago; The Black Dork Lives!; The UN Requires Unaninmous Decisions; LPIR - Steganography in Practice; How I Am 6; Clear Explanation of Verizon / Level 3 / Netflix; Teenage Girls; Formalising NSA Attacks; Switching Brakes (Tektro Hydraulic); Naim NAP 100 (Power Amp); AKG 550 First Impressions; Facebook manipulates emotions (no really); Map Reduce "No Longer Used" At Google; Removing RAID metadata; New Bike (Good Bike Shop, Santiago Chile); Removing APE Tags in Linux; Compiling Python 3.0 With GCC 4.8; Maven is Amazing; Generating Docs from a GitHub Wiki; Modular Shelves; Bash Best Practices; Good Emergency Gasfiter (Santiago, Chile); Readings in Recent Architecture; Roger Casement; Integrated Information Theory (Or Not); Possibly undefined macro AC_ENABLE_SHARED; Update on Charges; Sunburst Visualisation; Spectral Embeddings (Distances -> Coordinates); Introduction to Causality; Filtering To Help Colour-Blindness; ASUS 1015E-DS02 Too; Ready Player One; Writing Clear, Fast Julia Code; List of LatAm Novels; Running (for women); Building a Jenkins Plugin and a Jar (for Command Line use); Headphone Test Recordings; Causal Consistency; The Quest for Randomness; Chat Wars; Real-life Financial Co Without ACID Database...; Flexible Muscle-Based Locomotion for Bipedal Creatures; SQL Performance Explained; The Little Manual of API Design; Multiple Word Sizes; CRC - Next Steps; FizzBuzz; Update on CRCs; Decent Links / Discussion Community; Automated Reasoning About LLVM Optimizations and Undefined Behavior; A Painless Guide To CRC Error Detection Algorithms; Tests in Julia; Dave Eggers: what's so funny about peace, love and Starship?; Cello - High Level C Programming; autoreconf needs tar; Will Self Goes To Heathrow; Top 5 BioInformatics Papers; Vasovagal Response; Good Food in Vina; Chilean Drug Criminals Use Subsitution Cipher; Adrenaline; Stiglitz on the Impact of Technology; Why Not; How I Am 5; Lenovo X240 OpenSuse 13.1; NSA and GCHQ - Psychological Trolls; Finite Fields in Julia (Defining Your Own Number Type); Julian Assange; Starting Qemu on OpenSuse; Noisy GAs/TMs; Venezuela; Reinstalling GRUB with EFI; Instructions For Disabling KDE Indexing; Evolving Speakers; Changing Salt Size in Simple Crypt 3.0.0; Logarithmic Map (Moved); More Info; Words Found in Voynich Manuscript

© 2006-2013 Andrew Cooke (site) / post authors (content).

Automating Access to AppEngine with Federated Logins

From: andrew cooke <andrew@...>

Date: Sun, 7 Aug 2011 07:06:11 -0400

I've been using Google's AppEngine, which has been great, except that
automated authentication for the infrastructure breaks when you use their
"experimental" federated login.  This means that if you support OpenID logins
(in addition to Google logins) then you cannot do things like use the remote
shell, or dump data.

Being unable to backup/restore data is a serious problem.  Luckily, the amount
of data is small, so it can be embedded within a web page.  That only leaves
the small problem of authenticating access.  OpenID works (the root cause of
this whole problem being that I've enabled OpenID...), but I can't work out
how to script it reliably.

One solution is to add my own authentication scheme.  Obviously this is less
than ideal, and one reason I am writing this post is to get feedback on both
the implementation and alternative solutions.  Remember that this is very
limited in scope - it does not need to handle multiple, parallel connections,
for example.

So, what follows is a simple challenge/response scheme that uses RSA
signatures.  It works as follows:

 - A URL on the server provides a random value (the "nonce").

 - A script on the client signs the nonce (with the private key) and makes a 
   new request with the signature.

 - The server validates the signature against the stored nonce (with
   the public key) and, if it is correct, generates the data dump.

The reasons for chosing a public key / signature approach rather than a hashed
secret were:

 - I wanted to be able to share the code without worrying about accidentally
   sharing a secret.

 - I was worried that I am going to make some stupid mistake similar to the
   MAC/HMAC issue.  The signature approach uses just three clear API methods:
   generate keys; generate signature; validate signature.

The reason for using RSA (in particular, python-rsa) was that I couldn't get
pycrypto (which is supplied by Google) to work.  I don't know if this was a
documentation problem (the Google version is old, and pycrypto documentation
is poor at the best of times) or because the public key crypto part is
unsupported (the final error looked like it was related to a missing C
library), but I had to look for an alternative pure-Python public key crypto
library, and found python-rsa.

The one issue I have had with python-rsa is that the "key.py" module in
release 3.0 includes "import abc".  This is not used, but causes problems in
Python 2.5.  It can be safely deleted and I will report it as a bug.

The code itself, which I will include below, includes brief details on use -
don't forget to install both python-rsa and pyasn1 (which python-rsa requires
for serialisation of keys) in your application.

Andrew


#LICENCE

'''
If this file is run as a program, then it expects 2  or 3 arguments.  the
first argument should be either 'new_keys' or 'sign', the second is always
a file name.
- 'new_keys': write a public key to stdout and a private key to the given file
- 'sign': use the private key from the given file to sign the third argument

A new user of this library should run the program with 'new_keys' and
then update the public key below.  This library can then be deployed to
the app engine.

To allow validated, remote access, the library should be used as follows:

- Within the application code:
  - run this file with "new_keys" and update PUBLIC_KEY below
  - some URL should be associated with "nonce()"
  - each URL that performs a validated action should include a URL value
    for "signature" and be decorated with "verify()"

- To make a verified call:
  - the remote user calls the generate URL and receives the nonce value
  - the remote user calls this file with "sign" to sign the nonce
  - the remote user calls the action URL with the signature

For example, the dhango URL configuration might be:
  ('^nonce$', 'this_module.nonce')
  ('^do_stuff/(?P<signature>.*)$', 'my_site.do_stuff')
and the view my_site.do_stuff would look like:
  @verify
  def do_stuff(request, signature, ...):
      do stuff here that requires validation

This can all be scripted using, for example, wget.  In this way automatic
backup of data is possible using validated requests.  Note that for full
security you must also use HTTPS, protect your keys, etc.

This does not use pycrypto because the version available on appengine is
incomplete, and the library as a whole appears to be poorly implemented and
documented.  As a consequence, you must include pyasn1 and python-rsa in
your project (both are pure-python and fairly small).
'''

import logging
from os import environ, urandom
from base64 import urlsafe_b64encode, urlsafe_b64decode
from hashlib import sha1
from sys import argv, stderr
from time import time

from django.http import HttpResponse
from rsa.key import newkeys, PrivateKey, PublicKey
from rsa import sign as rsa_sign, verify as rsa_verify

try:
    from google.appengine.api import memcache
except ImportError:
    print >> stderr, 'Failed to import appengine; assuming you are running
    locally'


PUBLIC_KEY = PublicKey.load_pkcs1('''-----BEGIN RSA PUBLIC KEY-----
MIGJAoGBAL7SLyF//4YgqVlE1ppv9eZ++/pFtju3cNJT2RFSIZs8Ulk0HEjT8b7O
lRCEOchL79w/ID8CQA6dNCcs/Ok8miswg+2GNRJCJvQKDgdmn6uAyoEXvpFLXEbz
c4ayBIWLDmAKgaKk5or05M57ScJ/hfZ1h0/MUV76bmNAFMxHilwXAgMBAAE=
-----END RSA PUBLIC KEY-----
''')


def nonce(request):
    def log(value):
        #logging.debug('Adding to nonce: %r' % value)
        return value
    hash = sha1()
    hash.update(log(urandom(8)))
    hash.update(log(environ['REQUEST_ID_HASH']))
    hash.update(log(environ['INSTANCE_ID']))
    hash.update(log(str(time())))
    hash.update(log(urandom(8)))
    nonce = urlsafe_b64encode(hash.digest())
    logging.info('New nonce: %s' % nonce)
    memcache.add('nonce', nonce, namespace='nonce', time=60)
    return HttpResponse(content=nonce)


def verify(view):
    def wrapper(request, *args, **kargs):
        if 'signature' in kargs:
            signature = kargs['signature']
        else:
            return HttpResponse(content='No named signature parameter in URL',
    status=403)
        nonce = memcache.get('nonce', namespace='nonce')
        if not nonce:
            return HttpResponse(content='No nonce found', status=403)
        try:
            signature = signature.encode('ascii')
            signature = urlsafe_b64decode(signature)
            rsa_verify(nonce, signature, PUBLIC_KEY)
        except Exception, e:
            logging.error(e)
            return HttpResponse(content='Bad signature', status=403)
        logging.debug('Verified %r with %r' % (nonce, signature))
        return view(request, *args, **kargs)
    return wrapper


def new_keys(path):
    print >> stderr, "\nGenerating new keys (please wait)"
    (public_key, private_key) = newkeys(1024)
    print >> stderr, "\nPublic key (copy to code):"
    print >> stderr, "'''%s'''" % public_key.save_pkcs1()
    out = open(path, 'w')
    print >> out, private_key.save_pkcs1()
    out.close()
    print >> stderr, "\nPrivate key written to %s" % path


def sign(path, nonce):
    inp = open(path, 'r')
    pkcs1 = inp.read()
    inp.close()
    private_key = PrivateKey.load_pkcs1(pkcs1)
    print >> stderr, "\nPrivate key read from %s" % path
    print >> stderr, "\nSignature to stdout:"
    signature = rsa_sign(nonce, private_key, 'SHA-1')
    #print repr(signature)
    print urlsafe_b64encode(signature)

    
if __name__ == '__main__':
    if len(argv) == 3 and argv[1] == 'new_keys':
        new_keys(argv[2])
    elif len(argv) == 4 and argv[1] == 'sign':
        sign(argv[2], argv[3])
    else:
        print >> stderr, '''
Usage:
  verify.py new_keys path/to/key_file
  verify.py sign path/to/key_file nonce
'''

Python-RSA update released

From: =?UTF-8?Q?Sybren_A=2E_St=C3=BCvel?= <sybren@...>

Date: Sun, 7 Aug 2011 16:31:31 +0200

Hey Andrew,

I've removed the "import abc" statement from python-rsa.

Thanks for entering a bug report. Next time, please log in at Bitbucket
before entering such a bug report. That way, you'll be automatically update=
d
when it's fixed (and it saves me from tracking down your contact details).

Cheers,
Sybren

--=20
Sybren A. St=C3=BCvel

http://stuvel.eu/

Small Correction and Script

From: andrew cooke <andrew@...>

Date: Sun, 7 Aug 2011 20:37:02 -0400

I have "memcache.add()" above, where it should be "memcache.set()".
Otherwise, this works nicely.  The following script grabs the data:

  #!/bin/bash

  if [ -e backup.json ]
  then
    mv backup.json backup.json.old
  fi
  wget -O nonce http://www.parti.cl/nonce
  export PYTHONPATH=particl:~/pkg/google_appengine/lib/django_1_2/
  echo -n "http://www.parti.cl/dump/" > signature
  python2.5 particl/particlsite/verify.py sign key `cat nonce` >> signature
  wget -O backup.json `cat signature`


Andrew

Comment on this post