Andrew Cooke | Contents | Latest | RSS | 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

Choochoo Training Diary

Last 100 entries

[Programming] React Leaflet; AliExpress Independent Sellers; Applebaum - Twilight of Democracy; [Politics] Back + US Elections; [Programming,Exercise] Simple Timer Script; [News] 2019: The year revolt went global; [Politics] The world's most-surveilled cities; [Bike] Hope Freehub; [Restaurant] Mama Chau's (Chinese, Providencia); [Politics] Brexit Podcast; [Diary] Pneumonia; [Politics] Britain's Reichstag Fire moment; install cairo; [Programming] GCC Sanitizer Flags; [GPU, Programming] Per-Thread Program Counters; My Bike Accident - Looking Back One Year; [Python] Geographic heights are incredibly easy!; [Cooking] Cookie Recipe; Efficient, Simple, Directed Maximisation of Noisy Function; And for argparse; Bash Completion in Python; [Computing] Configuring Github Jekyll Locally; [Maths, Link] The Napkin Project; You can Masquerade in Firewalld; [Bike] Servicing Budget (Spring) Forks; [Crypto] CIA Internet Comms Failure; [Python] Cute Rate Limiting API; [Causality] Judea Pearl Lecture; [Security, Computing] Chinese Hardware Hack Of Supermicro Boards; SQLAlchemy Joined Table Inheritance and Delete Cascade; [Translation] The Club; [Computing] Super Potato Bruh; [Computing] Extending Jupyter; Further HRM Details; [Computing, Bike] Activities in ch2; [Books, Link] Modern Japanese Lit; What ended up there; [Link, Book] Logic Book; Update - Garmin Express / Connect; Garmin Forerunner 35 v 230; [Link, Politics, Internet] Government Trolls; [Link, Politics] Why identity politics benefits the right more than the left; SSH Forwarding; A Specification For Repeating Events; A Fight for the Soul of Science; [Science, Book, Link] Lost In Math; OpenSuse Leap 15 Network Fixes; Update; [Book] Galileo's Middle Finger; [Bike] Chinese Carbon Rims; [Bike] Servicing Shimano XT Front Hub HB-M8010; [Bike] Aliexpress Cycling Tops; [Computing] Change to ssh handling of multiple identities?; [Bike] Endura Hummvee Lite II; [Computing] Marble Based Logic; [Link, Politics] Sanity Check For Nuclear Launch; [Link, Science] Entropy and Life; [Link, Bike] Cheap Cycling Jerseys; [Link, Music] Music To Steal 2017; [Link, Future] Simulated Brain Drives Robot; [Link, Computing] Learned Index Structures; Solo Air Equalization; Update: Higher Pressures; Psychology; [Bike] Exercise And Fuel; Continental Race King 2.2; Removing Lowers; Mnesiacs; [Maths, Link] Dividing By Zero; [Book, Review] Ray Monk - Ludwig Wittgenstein: The Duty Of Genius; [Link, Bike, Computing] Evolving Lacing Patterns; [Jam] Strawberry and Orange Jam; [Chile, Privacy] Biometric Check During Mail Delivery; [Link, Chile, Spanish] Article on the Chilean Drought; [Bike] Extended Gear Ratios, Shimano XT M8000 (24/36 Chainring); [Link, Politics, USA] The Future Of American Democracy; Mass Hysteria; [Review, Books, Links] Kazuo Ishiguro - Never Let Me Go; [Link, Books] David Mitchell's Favourite Japanese Fiction; [Link, Bike] Rear Suspension Geometry; [Link, Cycling, Art] Strava Artwork; [Link, Computing] Useful gcc flags; [Link] Voynich Manuscript Decoded; [Bike] Notes on Servicing Suspension Forks; [Links, Computing] Snap, Flatpack, Appimage; [Link, Computing] Oracle is leaving Java (to die); [Link, Politics] Cubans + Ultrasonics; [Book, Link] Laurent Binet; VirtualBox; [Book, Link] No One's Ways; [Link] The Biggest Problem For Cyclists Is Bad Driving; [Computing] Doxygen, Sphinx, Breathe; [Admin] Brokw Recent Permalinks; [Bike, Chile] Buying Bearings in Santiago; [Computing, Opensuse] Upgrading to 42.3; [Link, Physics] First Support for a Physics Theory of Life; [Link, Bike] Peruvian Frame Maker; [Link] Awesome Game Theory Tit-For-Tat Thing; [Food, Review] La Fabbrica - Good Italian Food In Santiago; [Link, Programming] MySQL UTF8 Broken; [Link, Books] Latin American Authors

© 2006-2017 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