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


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.

C-ORM: docs, API.

Last 100 entries

China Gamifies Real Life; Can't Help Thinking It's Thoughtcrime; Mefi Quotes; Spray Painting Bike Frame; Weeks 10 + 11; Change: No Longer Possible To Merge Metadata; Books on Old Age; Health Tree Maps; MRA - Men's Rights Activists; Writing Good C++14; Risk Assessment - Fukushima; The Future of Advertising and Surveillance; Travelling With Betaferon; I think I know what I dislike so much about Metafilter; Weeks 8 + 9; More; Pastamore - Bad Italian in Vitacura; History Books; Iraq + The (UK) Governing Elite; Answering Some Hard Questions; Pinochet: The Dictator's Shadow; An Outsider's Guide To Julia Packages; Nobody gives a shit; Lepton Decay Irregularity; An Easier Way; Julia's BinDeps (aka How To Install Cairo); Good Example Of Good Police Work (And Anonymity Being Hard); Best Santiago Burgers; Also; Michael Emmerich (Vibrator Translator) Interview (Japanese Books); Clarice Lispector (Brazillian Writer); Books On Evolution; Looks like Ara (Modular Phone) is dead; Index - Translations From Chile; More Emotion in Chilean Wines; Week 7; Aeon Magazine (Science-ish); QM, Deutsch, Constructor Theory; Interesting Talk Transcripts; Interesting Suggestion Of Election Fraud; "Hard" Books; Articles or Papers on depolarizing the US; Textbook for "QM as complex probabilities"; SFO Get Libor Trader (14 years); Why Are There Still So Many Jobs?; Navier Stokes Incomplete; More on Benford; FBI Claimed Vandalism; Architectural Tessellation; Also: Go, Blake's 7; Delusions of Gender (book); Crypto AG DID work with NSA / GCHQ; UNUMS (Universal Number Format); MOOCs (Massive Open Online Courses); Interesting Looking Game; Euler's Theorem for Polynomials; Weeks 3-6; Reddit Comment; Differential Cryptanalysis For Dummies; Japanese Graphic Design; Books To Be Re-Read; And Today I Learned Bugs Need Clear Examples; Factoring a 67 bit prime in your head; Islamic Geometric Art; Useful Julia Backtraces from Tasks; Nothing, however, is lost with less discomfort than that which, when lost, cannot be missed; Article on Didion; Cost of Living by City; British Slavery; Derrida on Metaphor; African SciFi; Traits in Julia; Alternative Japanese Lit; Pulic Key as Address (Snow); Why Information Grows; The Blindness Of The Chilean Elite; Some Victoriagate Links; This Is Why I Left StackOverflow; New TLS Implementation; Maths for Physicists; How I Am 8; 1000 Word Philosophy; Cyberpunk Reading List; Detailed Discussion of Message Dispatch in ParserCombinator Library for Julia; FizzBuzz in Julia w Dependent Types; kokko - Design Shop in Osaka; Summary of Greece, Currently; LLVM and GPUs; See Also; Schoolgirl Groyps (Maths); Japanese Lit; Another Example - Modular Arithmetic; Music from United; Python 2 and 3 compatible alternative.; Read Agatha Christie for the Plot; A Constructive Look at TempleOS; Music Thread w Many Recommendations; Fixed Version; A Useful Julia Macro To Define Equality And Hash; k3b cdrom access, OpenSuse 13.1; Week 2

© 2006-2015 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.



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:
  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

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

PUBLIC_KEY = PublicKey.load_pkcs1('''-----BEGIN RSA PUBLIC KEY-----

def nonce(request):
    def log(value):
        #logging.debug('Adding to nonce: %r' % value)
        return value
    hash = sha1()
    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']
            return HttpResponse(content='No named signature parameter in URL',
        nonce = memcache.get('nonce', namespace='nonce')
        if not nonce:
            return HttpResponse(content='No nonce found', status=403)
            signature = signature.encode('ascii')
            signature = urlsafe_b64decode(signature)
            rsa_verify(nonce, signature, PUBLIC_KEY)
        except Exception, 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()
    print >> stderr, "\nPrivate key written to %s" % path

def sign(path, nonce):
    inp = open(path, 'r')
    pkcs1 = inp.read()
    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':
    elif len(argv) == 4 and argv[1] == 'sign':
        sign(argv[2], argv[3])
        print >> stderr, '''
  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=
when it's fixed (and it saves me from tracking down your contact details).


Sybren A. St=C3=BCvel


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:


  if [ -e backup.json ]
    mv backup.json backup.json.old
  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`


Comment on this post