From: Matt Webb Date: Sun, 21 Sep 2014 17:02:07 +0000 (+0100) Subject: base app with websockets and sending an encryption key X-Git-Url: https://git.aero2k.de/?a=commitdiff_plain;h=efdc43734dc29e84f1fc51d27a7ee0856bd7e1b5;p=sirius.git base app with websockets and sending an encryption key --- diff --git a/app/__init__.py b/app/__init__.py old mode 100644 new mode 100755 index 347a0ef..7fa4701 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,10 +1,25 @@ from flask import Flask, render_template from flask.ext.bootstrap import Bootstrap from flask.ext.sqlalchemy import SQLAlchemy +from flask_sockets import Sockets from config import config +from pprint import pprint +import json +import gevent + bootstrap = Bootstrap() db = SQLAlchemy() +sockets = Sockets() + +from . import commands + + +# @TODO +# for this to work, I have to put the following line at line 38 of +# flask_sockets, to inject it into the environment +# environment.environ['HTTP_SEC_WEBSOCKET_PROTOCOL'] = 'bergcloud-bridge-v1' + def create_app(config_name): app = Flask(__name__) @@ -13,9 +28,41 @@ def create_app(config_name): bootstrap.init_app(app) db.init_app(app) + sockets.init_app(app) # attach routes and custom error pages from .main import main as main_blueprint app.register_blueprint(main_blueprint) + # shouldn't be here, should be attached as a blueprint + @sockets.route('/api/v1/connection') + def echo_socket(ws): + print "here" + done_once = False + while True: + message = ws.receive() + pprint(message) + print "" + + # temporary logic + try: + event = json.loads(message) + if event['type'] == 'BridgeEvent' and event['json_payload']['name'] == 'encryption_key_required': + print "==> encryption_key_required" + j = commands.add_device_encryption_key().to_json() + ws.send(j) + gevent.sleep(0.5) + print "===> %s" % j + j = commands.set_delivery_and_print().to_json() + ws.send(j) + if event['type'] == 'BridgeEvent' and done_once == False: + j = commands.set_delivery_and_print().to_json() + ws.send(j) + print "===> tried to send image" + done_once = True + except: + pass + + #ws.send(message) + return app diff --git a/app/claiming.py b/app/claiming.py new file mode 100755 index 0000000..95ad768 --- /dev/null +++ b/app/claiming.py @@ -0,0 +1,160 @@ +from crc16 import crc16 +from Crypto.Cipher import AES, XOR + +import struct +import base64 + +ZBEE_SEC_CONST_BLOCKSIZE = 16 + +CLAIM_CODE_SALT = [ 0x38, 0x96, 0x10, 0xd9, + 0xb6, 0xb1, 0x0d, 0x16, + 0x9e, 0xe9, 0xbf, 0x87, + 0x95, 0x32, 0x62, 0x5b ] + +# This dictionary maps base32 digits to five-bit values. +# +# Letter 'A' is omitted and not valid in a claim code. +# Letter 'I' is mapped to number '1' (i.e. claim code is '1', user enters 'I' by mistake). +# Letter 'L' is mapped to number '1' (i.e. claim code is '1', user enters 'L' by mistake). +# Letter 'U' is mapped to letter 'v' (i.e. claim code is 'V', user enters 'U' by mistake). +CLAIMCODE_BASE32_DICT = { + '0': 0x00, + '1': 0x01, + '2': 0x02, + '3': 0x03, + '4': 0x04, + '5': 0x05, + '6': 0x06, + '7': 0x07, + '8': 0x08, + '9': 0x09, +# 'A': omitted + 'B': 0x0A, + 'C': 0x0B, + 'D': 0x0C, + 'E': 0x0D, + 'F': 0x0E, + 'G': 0x0F, + 'H': 0x10, + 'I': 0x01, # mapped to '1' + 'J': 0x11, + 'K': 0x12, + 'L': 0x01, # mapped to '1' + 'M': 0x13, + 'N': 0x14, + 'O': 0x15, + 'P': 0x16, + 'Q': 0x17, + 'R': 0x18, + 'S': 0x19, + 'T': 0x1A, + 'U': 0x1B, # mapped to 'V' + 'V': 0x1B, + 'W': 0x1C, + 'X': 0x1D, + 'Y': 0x1E, + 'Z': 0x1F +} + +class InvalidClaimCode(Exception): + pass + +def unpack_claim_code(claim_code): + clean = claim_code.replace("-", "").upper() + + if len(clean) != 16: + raise InvalidClaimCode("claim codes should be 16 characters") + + value = 0 + + for i, c in enumerate(clean): + if c in CLAIMCODE_BASE32_DICT.keys(): + value += CLAIMCODE_BASE32_DICT[c] * (32 ** (15 - i)) + else: + raise InvalidClaimCode("%s is not a valid character" % c) + + device = value & 0xffffff # 24 bit hardware address xor + secret = (value >> 24) & 0xffffffffff # 40 bit secret + crc = value >> 64 # 16 bit crc + + # Return the components, and the raw 80 bit value + return (device, secret, crc, value) + +# This method is inspired by dissectors/packet-zbee-security.c from Wireshark +# input should be a binary string of 5 bytes in length +def generate_link_key(input): + input_length = len(input) + len(CLAIM_CODE_SALT) + + if len(input) <= 5: + # Padding begins with 1000000 + # Then pad with zeroes until we're at 14 bytes + input = input + b'\x80' + b'\x00' * (ZBEE_SEC_CONST_BLOCKSIZE - 2 - len(input) - 1) + + # Pad with the original length encoded as a 16bit int + # Python3 + #input = input + bytes( [((input_length * 8) >> 8 & 0xff)] ) + #input = input + bytes( [((input_length * 8) >> 0 & 0xff)] ) + # Python2 + input = input + chr((input_length * 8) >> 8 & 0xff) + input = input + chr((input_length * 8) >> 0 & 0xff) + + elif input_length != ZBEE_SEC_CONST_BLOCKSIZE: + raise InvalidClaimCode("cannot handle input size %d" % input_length) + + # We encrypt the salt and the input bytes + # blocks = [bytes(CLAIM_CODE_SALT), input] # Python3 + blocks = [str(bytearray(CLAIM_CODE_SALT)), input] # Python2 + + #output = bytes(16) # Works in Python3 + output = bytearray(16) # Works in Python2 + + for block in blocks: + # aes_encoder = AES.new(output, AES.MODE_ECB) # Python3 + aes_encoder = AES.new(str(output), AES.MODE_ECB) # Python2 + h = aes_encoder.encrypt(block) + output = bytearray(16) + for i in range(len(output)): + # output[i] = h[i] ^ block[i] # Python3 + output[i] = ord(h[i]) ^ ord(block[i]) # Python2 + output = bytes(output) + + return output + + +# Codes go through the following process: +# +# 1. Cleaning +# 2. Convert from 5-bit to 8-bit (16 chars down to 10 chars) +# 3. Checksum is checked +# 4. XOR EUI64 + Base64 security hash + CRC are returned +# +# Return the link key in Base64, and the XORed hardware_address +def process_claim_code(claim_code): + hardware_address_xor, secret, crc, raw_value = unpack_claim_code(claim_code) + + # Generate our own CRC from the raw_value, and confirm it matches the extracted crc + data_for_crc = struct.pack("cxHL + # - payload header + # - length >L + # - payload + # - len(header plus image) + 1 >L + # - pad x + # - encode_header_region + # - pad x + # - length of following >L + # - append_printer_control_header (a bunch o bytes) + # - UC05 controls c, reserved byte >c, + # command_name >H (short), file_id >L (long) + command_header = struct.pack(">cxHL", '\x01', 1, 1) + + # get the encoded image now, because we'll need the data later + pixel_count, encoded_image = rle_image(png_fn) + + # payload header region + printer_control = struct.pack("xL", len(printer_control) + len(printer_data)) + header_region += printer_control + printer_data + + # payload including the header + payload = struct.pack(">Lx", len(header_region) + len(encoded_image) + 1) + payload += header_region + encoded_image + + entire_payload = command_header + struct.pack(">L", len(payload)) + payload + + return entire_payload + +def set_delivery_and_print(): + command = DeviceCommand( + device_address='000d6f000273ce0b', + binary_payload=base64.b64encode(set_delivery_and_print_payload(TEST_FILE_ID, TEST_PNG_FN)), + state='ready', + deliver_at=datetime.utcnow() + ) + command.id = 1 + return command \ No newline at end of file diff --git a/app/crc16.py b/app/crc16.py new file mode 100644 index 0000000..73ec189 --- /dev/null +++ b/app/crc16.py @@ -0,0 +1,39 @@ +def crc16(buf, crc = 0xffff): + for b in buf: + crc = ((crc<<8) ^ CCITT_16[(crc>>8) ^ b]) & 0xffff + return crc + +CCITT_16 = [ + 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7, + 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, + 0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6, + 0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, + 0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485, + 0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, + 0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4, + 0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC, + 0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823, + 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B, + 0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12, + 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A, + 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41, + 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49, + 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70, + 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, + 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F, + 0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, + 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E, + 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, + 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D, + 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, + 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C, + 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634, + 0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, + 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3, + 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, + 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, + 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, + 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, + 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, + 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0 + ] diff --git a/app/image_encoding.py b/app/image_encoding.py new file mode 100644 index 0000000..beaec47 --- /dev/null +++ b/app/image_encoding.py @@ -0,0 +1,78 @@ +from PIL import Image +from itertools import groupby +import array +import struct + +WHITE = 0 +BLACK = 1 +THRESHOLD = 127 +TRANSLATE = [ (1536, 255), (1152, 254), (768, 253), (384, 252), (251, 251) ] + +def pixel_to_bw(p): + if p == (0, 0, 0, 0): + return WHITE + elif p[0] > THRESHOLD or p[1] > THRESHOLD or p[2] > THRESHOLD: + return WHITE + else: + return BLACK + +def ilen(i): return sum(1 for _ in i) + +# so what we have is a list of runs, alternating white and black, +# starting with white. +# the scheme for our little printer RLE is: +# - runs of 0..251 inclusive are stored as a byte +# - if larger, pull off chunks of 1536, 1152, 768, 384, 251 (encoded as +# 255, 254, 253, 252, 251) until small enough +# when a large number is broken into chunks, each chunk needs +# to be suffixed by a zero so it snaps back to swap it back to the +# correct colour +def rle(lengths): + for length in lengths: + if length == 0: + yield length + elif length <= 251: + yield length + elif length > 251: + remainder = length + done_first = False + while remainder > 251: + chunk, code = [t for t in TRANSLATE if remainder >= t[0]][0] + remainder -= chunk + if done_first: + yield 0 + else: + done_first = True + yield code + else: + if remainder > 0: + yield 0 + yield remainder + +def rle_image(image_fn): + # get image pixels + im = Image.open(image_fn) + im = im.convert('RGBA') + pixels = im.getdata() + + # convert to B&W and group each run length into lists + # each list is (result of identity function, [actual pixels]) + grouped = groupby(pixels, pixel_to_bw) + + # create list of tuples (WHITE|BLACK, run_length) + groups = [] + for k, g in grouped: + groups.append( (k, ilen(g)) ) + + # the decoder assumes that the first run is white, so if the + # first pixel is black, add a zero run of white + if groups[k][0] == BLACK: + groups.insert(0, (WHITE, 0)) + + # encode using our custom encoding + lengths = [g[1] for g in groups] + x = bytearray(rle(lengths)) + output = struct.pack(">%ds" % len(x), str(x)) + + # return (number of pixels, output) + return len(pixels), output diff --git a/app/models.py b/app/models.py old mode 100644 new mode 100755 index e69de29..58dce89 --- a/app/models.py +++ b/app/models.py @@ -0,0 +1,54 @@ +from . import db + +import json + +# BridgeCommand has +# - timestamp (datetime in UTC) +# - bridge_address (store the hex value as a string) +# - id (primary key) +# - return_code -- init as null, integer +# - json_payload -- text +class BridgeCommand(db.Model): + __tablename__ = 'bridge_commands' + id = db.Column(db.Integer, primary_key=True) + timestamp = db.Column(db.DateTime, nullable=False) + bridge_address = db.Column(db.String, nullable=False) + json_payload = db.Column(db.UnicodeText, nullable=False) + return_code = db.Column(db.SmallInteger, nullable=True) + + def to_json(self): + try: + json_payload = json.loads(self.json_payload) + except: + json_payload = None + json_hash = { + 'type': 'BridgeCommand', + 'bridge_address': self.bridge_address, + 'command_id': self.id, + 'json_payload': json_payload, + 'timestamp': self.timestamp.isoformat() + } + return json.dumps(json_hash, encoding='utf-8') + +# DeviceCommand has +# - device_address (store the hex value as a string) +# - id (primary key) +# - binary_payload (store base64 encoded) +# - state (ready, failed, delivered, skipped) +# - deliver_at (timestamp) +class DeviceCommand(db.Model): + __tablename__ = 'device_commands' + id = db.Column(db.Integer, primary_key=True) + device_address = db.Column(db.String, nullable=False) + binary_payload = db.Column(db.Text, nullable=False) + state = db.Column(db.Enum('ready', 'failed', 'delivered', 'skipped'), nullable=False) + deliver_at = db.Column(db.DateTime, nullable=False) + + def to_json(self): + json_hash = { + 'command_id': self.id, + 'type': 'DeviceCommand', + 'device_address': self.device_address, + 'binary_payload': self.binary_payload + } + return json.dumps(json_hash, encoding='utf-8') diff --git a/config.py b/config.py old mode 100644 new mode 100755 diff --git a/manage.py b/manage.py index 460e9b7..eccb675 100755 --- a/manage.py +++ b/manage.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python3 +#!/usr/bin/env python2.7 import os @@ -17,13 +17,13 @@ app = create_app(os.getenv('FLASK_CONFIG') or 'default') manager = Manager(app) migrate = Migrate(app, db) - def make_shell_context(): - return dict(app=app, db=db, User=User, Follow=Follow, Role=Role, - Permission=Permission, Post=Post, Comment=Comment) + return dict(app=app, db=db) manager.add_command("shell", Shell(make_context=make_shell_context)) manager.add_command('db', MigrateCommand) - if __name__ == '__main__': manager.run() + +# run with +#gunicorn -b 0.0.0.0:5000 -k flask_sockets.worker manage:app diff --git a/requirements.txt b/requirements.txt old mode 100644 new mode 100755 index 8dc21d9..a7d3eb8 --- a/requirements.txt +++ b/requirements.txt @@ -3,10 +3,18 @@ Flask-Bootstrap==3.2.0.2 Flask-Migrate==1.2.0 Flask-SQLAlchemy==2.0 Flask-Script==2.0.5 +Flask-Sockets==0.1 Jinja2==2.7.3 Mako==1.0.0 MarkupSafe==0.23 +Pillow==2.5.3 SQLAlchemy==0.9.7 Werkzeug==0.9.6 alembic==0.6.7 +gevent==1.0.1 +gevent-websocket==0.9.3 +greenlet==0.4.4 +gunicorn==19.1.1 itsdangerous==0.24 +pycrypto==2.6.1 +wsgiref==0.1.2 diff --git a/tests/iconrethink.png b/tests/iconrethink.png new file mode 100644 index 0000000..4e8a530 Binary files /dev/null and b/tests/iconrethink.png differ