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

C-ORM: docs, API.

Last 100 entries

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; 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; From outside, the UK looks less than stellar; Huge Fonts in VirtualBox; Keen - Complex Emergencies; The Fallen of World War II; Some Spanish Fiction; Calling C From Fortran 95; Bjork DJ Set; Z3 Example With Python; Week 1; Useful Guide To Starting With IJulia; UK Election + Media; Review: Reinventing Organizations; Inline Assembly With Julia / LLVM; Against the definition of types; Dumb Crypto Paper; The Search For Quasi-Periodicity...; Is There An Alternative To Processing?; CARDIAC (CARDboard Illustrative Aid to Computation); The Bolivian Case Against Chile At The Hague; Clear, Cogent Economic Arguments For Immigration; A Program To Say If I Am Working; Decent Cards For Ill People; New Photo; Luksic And Barrick Gold; President Bachelet's Speech; Baltimore Primer; libxml2 Parsing Stream; configure.ac Recipe For Library Path; The Davalos Affair For Idiots; Not The Onion: Google Fireside Chat w Kissinger; Bicycle Wheels, Inertia, and Energy; Another Tax Fraud; Google's Borg; A Verion That Redirects To Local HTTP Server; Spanish Accents For Idiots; Aluminium Cans; Advice on Spray Painting; Female View of Online Chat From a Male; UX Reading List; S4 Subgroups - Geometric Interpretation; Fucking Email; The SQM Affair For Idiots; Using Kolmogorov Complexity; Oblique Strategies in bash; Curses Tools; Markov Chain Monte Carlo Without all the Bullshit; Email Para Matias Godoy Mercado; The Penta Affair For Idiots; Example Code To Create numpy Array in C; Good Article on Bias in Graphic Design (NYTimes); Do You Backup github?; Data Mining Books; SimpleDateFormat should be synchronized; British Words; Chinese Govt Intercepts External Web To DDOS github; Numbering Permutations; Teenage Engineering - Low Price Synths; GCHQ Can Do Whatever It Wants; Dublinesque; A Cryptographic SAT Solver; Security Challenges; Word Lists for Crosswords; 3D Printing and Speaker Design; Searchable Snowden Archive; XCode Backdoored; Derived Apps Have Malware (CIA); Rowhammer - Hacking Software Via Hardware (DRAM) Bugs; Immutable SQL Database (Kinda); Tor GPS Tracker; That PyCon Dongle Mess...; ASCII Fluid Dynamics; Brandalism; Table of Shifter, Cassette and Derailleur Compatability; Lenovo Demonstrates How Bad HTTPS Is; Telegraph Owned by HSBC; Smaptop - Sunrise (Music); Equation Group (NSA); UK Torture in NI

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

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