| 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

Re: Python's sad, unimaginative Enum; Some explanation; Printing binary trees sideways; About "Python's sad, unimaginative Enum"; Atoms in python; Some good feedback here; Frustration Understood; I agree with you #nt; What would be imaginative?; Re: Enum; this is fucking useless; Enum; Python's sad, unimaginative Enum; Possible Fix; Work, Exhaustion, Vacation; VirtualBox with Centos 6.3 to 6.4, client; Matasano - Programming Lessons Learned; PDF to HTML; Alternate Substitution; Why RSA Works; Trigger; Dreaming of Death; Example: Tracing; Using Coroutines In Protocol Simulations; Python 3.3 Only; Pure Python SHA1 and MD4 Implementations; Ubuntu on VirtualBox; Starting TOR as a service on OpenSuse 12.3; 1001 Albums; Using fail2ban on OpenSuse 12.3; PPPoE on OpenSuse 12.3; Good Article on Unified Physics; It's Police (Carabineros); Linux Software for Listening to and Exploring Music; Android is Pretty Bad; Lucky Number; 3D Printing for Casting; Cover Art for MPDroid; Who'd a thought the French were so bigoted?; PS Input Signal; Small Problem with Roksan K2 Amp; Roksan K2 Amp + ATC SCM7 Speakers; Do What Makes Sense; Re: Arguing About Tests, Still; Arguing About Tests, Still; Images; Good Article on NY Drummers; Related Bug Report; Getting Python 3.3 and Virtualenv Working in OpenSuse 12.3; How I Am; Awesome video about digital audio; The Difference Between Dimensional and Normalized Databases; The rise of the new Chinese bogeyman; Updated Syntax; Very First Steps to C-ORM; The Ideal User Interface For Music Exploration; Can The Republicans Be Saved?; Rate Limiting Calls to EchoNest; Mods to Cache; Comparing UYKFG and UYKFD/E/F; Someone Else is Concerned; EchoNest-based Playlist Generator for MPD; Example Voting Results; A Heavyweight Python Cache; Identifying Artists with EchoNest; Notes on Pregalex / Pregabalina / Lyrica; The Neil Cowley Trio; Drake - Make for Data; A Reliable Python Web Service; Useful Python Date/Time Library?; Need to Sleep, But this is Good; Command Line Set Difference; Little Details...; Linux Command Line Tricks; AutoTools Tutorial; Hangman Tactics; A Tor Proxy Embedded In A Web Page; Tree (Nested Dicts) in Python; Sleeping at Parties; I Know Someone Who Hurts Other People; Light and Tea; Description of the LCS35 Time Capsule Crypto-Puzzle; Re: I can relate to that ...; I can relate to that ...; Re: It's 2012 Why Does My IDE Suck?; My Own Alternative Medicine; Nice explanation of SVM; Why and How Writing Crypto is Hard; Re: It's 2012 Why Does My IDE Suck?; Incremental Regular Expressions; BBC Map Confused at Pole; Social Media: Ground Zero in the Culture War; My Visit to the Psycho Doc; Learning Modern 3D Graphics Programming; Hope you got some crackers to go with the cheese; Re: But how easy would it be ...; But how easy would it be ...; Powerline Freq Fingerprinting of Audio; The Folly of Scientism; Cheese - Because You're Going to Die Anyway; Another GPU Success - PyCUDA, Cross-Correlations

© 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