Skip to content
Snippets Groups Projects
Commit 93d2e626 authored by ptangu01's avatar ptangu01
Browse files

format code style pep8 but not on methods yet

git-svn-id: https://redmine.imt-atlantique.fr/svn/xaal/code/Python/trunk@1359 b32b6428-25c9-4566-ad07-03861ab6144f
parent 7fdf8a30
No related branches found
No related tags found
No related merge requests found
# -*- coding: utf-8 -*-
#
# Copyright 2014, Jérôme Colin, Jérôme Kerdreux, Philippe Tanguy, Telecom Bretagne.
# Copyright 2014, Jérôme Colin, Jérôme Kerdreux, Philippe Tanguy,
# Telecom Bretagne.
#
# This file is part of xAAL.
#
......@@ -25,20 +26,18 @@ except ImportError:
import json
from . import config
import array
import datetime
import pysodium
import base64
import struct
import logging
import binascii
logger = logging.getLogger(__name__)
# Time Window in seconds to avoid replay attacks
CIPHER_WINDOW = 60 * 2
class MessageFactoryParserError(Exception):
def __init__(self, value):
......@@ -84,15 +83,18 @@ class MessageFactory():
# Format payload before ciphering
if msg.getBody():
payload = json.dumps({"header":msg.getHeader(),"body":msg.getBody()})
payload = json.dumps(
{"header": msg.getHeader(), "body": msg.getBody()})
else:
payload = json.dumps({"header": msg.getHeader()})
# Payload Ciphering: ciph
ad = json.dumps(msg.getTargets()) # Additionnal Data == json serialization of the targets array
# Additionnal Data == json serialization of the targets array
ad = json.dumps(msg.getTargets())
nonce = buildNonce(msg.getTimestamp())
key = self.getCipherKey()
ciph = pysodium.crypto_aead_chacha20poly1305_encrypt(payload,ad,nonce,key)
ciph = pysodium.crypto_aead_chacha20poly1305_encrypt(
payload, ad, nonce, key)
# Add payload: base64 encoded of payload cipher
result['payload'] = base64.b64encode(ciph)
......@@ -131,10 +133,12 @@ class MessageFactory():
msgTime = dataRx['timestamp'][0]
if msgTime < (now - CIPHER_WINDOW):
raise MessageFactoryParserError("Potential replay attack, message too old")
raise MessageFactoryParserError(
"Potential replay attack, message too old")
if msgTime > (now + CIPHER_WINDOW):
raise MessageFactoryParserError("Potential replay attack, message too young")
raise MessageFactoryParserError(
"Potential replay attack, message too young")
# Payload De-Ciphering
ad = dataRx['targets'].encode("utf8") # Additional Data
......@@ -147,7 +151,8 @@ class MessageFactory():
raise MessageFactoryParserError("Bad Message, no payload found!")
try:
pJson=pysodium.crypto_aead_chacha20poly1305_decrypt(ciph,ad,nonce,key)
pJson = pysodium.crypto_aead_chacha20poly1305_decrypt(
ciph, ad, nonce, key)
except:
raise MessageFactoryParserError("Unable to decrypt msg")
......@@ -155,7 +160,8 @@ class MessageFactory():
try:
payload = json.loads(pJson)
except:
raise MessageFactoryParserError("Unable to parse JSON data in payload after decrypt")
raise MessageFactoryParserError(
"Unable to parse JSON data in payload after decrypt")
if 'header' in payload:
head = {}
......@@ -163,7 +169,8 @@ class MessageFactory():
head[name] = value
msg.setHeader(head)
else:
raise MessageFactoryParserError("Bad Message, none header found in payload!")
raise MessageFactoryParserError(
"Bad Message, none header found in payload!")
if 'body' in payload:
body = {}
......@@ -176,7 +183,13 @@ class MessageFactory():
#####################################################
# MSG builder
#####################################################
def buildMSG(self,dev=None,targets=[],msgtype=None,action=None,body=None):
def buildMSG(
self,
dev=None,
targets=[],
msgtype=None,
action=None,
body=None):
""" the build method takes in parameters :\n
-A device\n
-The list of targets of the message\n
......@@ -197,7 +210,7 @@ class MessageFactory():
message.setMsgtype(msgtype)
if action:
message.setAction(action)
if body!=None and body!={}:
if body is not None and body != {}:
message.setBody(body)
data = self.encodeMSG(message)
......@@ -209,7 +222,12 @@ class MessageFactory():
"""
body = {}
body['timeout'] = timeout
message=self.buildMSG(dev=dev,targets=[],msgtype="notify",action="alive",body=body)
message = self.buildMSG(
dev=dev,
targets=[],
msgtype="notify",
action="alive",
body=body)
return message
def buildErrorMSG(self, dev, errcode, description=None):
......@@ -217,7 +235,8 @@ class MessageFactory():
message = Message()
body = {}
body['code'] = errcode
if description: body['description']=description
if description:
body['description'] = description
message = self.buildMSG(dev, [], "notify", "error", body)
return message
......@@ -244,7 +263,9 @@ class Message():
# Targets
def setTargets(self, values):
if not isinstance(values, list):
raise TypeError("Expected a list for targetsList, got %s" % (type(values),))
raise TypeError(
"Expected a list for targetsList, got %s" %
(type(values),))
self._targets = values
def getTargets(self):
......@@ -333,10 +354,14 @@ class Message():
logger.debug("========= %s =========" % self)
header = self.getHeader()
logger.debug("*****Header*****")
if 'devType' in header: logger.debug("devType \t%s" % header['devType'])
if 'action' in header: logger.debug("action: \t%s" % header['action'])
if 'msgType' in header: logger.debug("msgType: \t%s" % header['msgType'])
if 'source' in header: logger.debug("source: \t%s" % header['source'])
if 'devType' in header:
logger.debug("devType \t%s" % header['devType'])
if 'action' in header:
logger.debug("action: \t%s" % header['action'])
if 'msgType' in header:
logger.debug("msgType: \t%s" % header['msgType'])
if 'source' in header:
logger.debug("source: \t%s" % header['source'])
logger.debug("version: \t%s" % self.getVersion())
logger.debug("targets: \t%s" % self.getTargets())
......@@ -358,6 +383,7 @@ def buildNonce(data):
nonce = struct.pack('>LL', data[0], data[1])
return nonce
def buildTimestamp():
"""Return array [seconds since epoch, microseconds since last seconds]
Time = UTC+0000
......@@ -365,5 +391,3 @@ def buildTimestamp():
epoch = datetime.datetime.utcfromtimestamp(0)
timestamp = datetime.datetime.utcnow() - epoch
return [int(timestamp.total_seconds()), int(timestamp.microseconds)]
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment