예제 #1
0
def getBalance():
    """ Get balance request


    :return: JSON request tous les capteurs de la classe
    """
    sipout = siphash.SipHash_2_4(key)
    sipin = siphash.SipHash_2_4(key)

    now = round(time.time())

    #    if request._headers['Content-Type'] == 'application/json':
    dict_req = request.get_json()

    badge = dict_req['Badge']
    time_req = dict_req['Time']

    hash_verif = badge + time_req
    for c in hash_verif:
        sipin.update(binascii.a2b_qp(c))

    #reqHash = hex(sipin.hash())[2:-1].upper() #This change does not work on Coltello
    reqHash = hex(sipin.hash())[2:].upper()
    reqHash = reqHash.zfill(16)

    if dict_req['Hash'] == reqHash:
        print("Cool hash's OK")
    else:
        print("Pas Cool !!!!!!!!!!")

    badgeId = int(badge, 16)
    element = session.query(User, User.name,
                            User.balance).filter(User.id == badgeId)
    if element.count() == 0:
        messages = ['ERROR', 'UNKNOWN USER']
        ret = {'Melody': "c5", 'Message': messages, 'Time': now}
    else:
        messages = [
            element.one().name, "{:.2f}".format(element.one().balance / 100)
        ]
        ret = {'Melody': "a1c1a1c1a1c1a1c1", 'Message': messages, 'Time': now}

    hash_str = ret['Melody'] + "".join(messages) + now.__str__()
    for c in hash_str:
        sipout.update(binascii.a2b_qp(c))

    #retHash = hex(sipout.hash())[2:-1].upper()  #This change does not work on Coltello works on PI
    retHash = hex(sipout.hash())[2:].upper()
    retHash = retHash.zfill(16)

    ret['Hash'] = retHash

    return json.dumps(ret)
예제 #2
0
    def check_http_signature(self, path, query):
        try:
            qargs = dict([b.split("=") for b in query.split("&")])
            ts = qargs['ts']
            sig = qargs['sig']
            keyid = qargs.get("k", "default")  # not used yet

            if sig in self.replay:
                print("replayed signature " + sig + " in request for " + path)
                return False

            its = int(ts) / 1000
            now = time.time()
            max = self.signature_max_age
            print("request timestamp: " + ts + ", min: " + str(now - max) +
                  ", max: " + str(now + max))
            if (its < (now - max)) or (its > (now + max)):
                return False

            message = (path + "\n" + ts).encode()
            check = siphash.SipHash_2_4(self.get_sign_key(keyid),
                                        message).hexdigest()
            print("request signature: " + sig + ", expecting: " +
                  check.decode())
            if check == sig.encode():
                self.replay.insert(0, sig)
                self.replay = self.replay[:self.replay_memory]
                return True

            return False

        except Exception as e:
            sys.excepthook(*sys.exc_info())
            return False
예제 #3
0
    def _generate_mac_bits(self, secret_key):
        """Compute the internal truncated MAC bits for this message.

        Generate a MAC for this message using the specified secret key.  The
        MAC is a 'truncated_MAC', generated from the 12 MSB from the result of
        a SipHash function applied to the message contents and secret key.  The
        returned result will be a 12-bit bitstream.

        MAC is generated using message ID, type code, and body byte.

        :param secret_key: 16-byte secret key, e.g. b"\xff" * 16
        :type secret_key: `bytes`
        :return: bitstream-packed form of the MAC generated using secret_key.
        :rtype: :class:`bitstring`
        """

        # the hash is computed over a struct representation of the message,
        # struct { uint32_t message_id (LE); uint8_t message_type, uint8_t body }
        structed = ints_to_bytes([
            (self.id_ & 0xFF),
            ((self.id_ & 0x0000FF00) >> 8),
            ((self.id_ & 0x00FF0000) >> 16),
            (self.id_ >> 24),
            (self.message_type.value),
            (self.body),
        ])

        function = siphash.SipHash_2_4(secret_key, structed)
        check_value = function.hash() >> 52  # use 12 most-significant bits

        bits = bitstring.pack("uint:12", check_value)

        return bits
예제 #4
0
def siphash(plaintext, bloomFilter):
    import siphash
    key = '0123456789ABCDEF'
    sip = siphash.SipHash_2_4(key)
    sip.update(plaintext)
    h = sip.hash()
    index = h % SIZE
    bloomFilter[index] = 1
예제 #5
0
 def generate_next_token(cls, last_code, key):
     conformed_token = struct.pack(
         '>Q', last_code)  # We convert the token to bytes
     token_hash = siphash.SipHash_2_4(key,
                                      conformed_token).hash()  # We hash it
     new_token = cls._convert_hash_to_token(
         token_hash)  # We convert to token and return
     return new_token
예제 #6
0
 def pkt_hash(self, key, src_ip):
     family = socket.AF_INET
     if ':' in src_ip:
         family = socket.AF_INET6
     hash_bytes = siphash.SipHash_2_4(key,
                                      socket.inet_pton(family,
                                                       src_ip)).digest()
     hash_num, = struct.unpack('<Q', hash_bytes)
     return hash_num
예제 #7
0
 def generate_next_token(cls, last_code, key):
     conformed_token = struct.pack(
         '>L', last_code)  # We convert the token to bytes
     conformed_token += conformed_token  # We duplicate it to fit the minimum length
     token_hash = siphash.SipHash_2_4(key,
                                      conformed_token).hash()  # We hash it
     new_token = cls._convert_hash_to_token(
         token_hash)  # We convert to token and return
     return new_token
예제 #8
0
 def __init__(self, controller_address):
     self.controller_address = controller_address
     print "initialized FlowBuilder with address : ", controller_address
     self.flow_catalogue = {}
     self.pusher_cfg = {}
     # 100 Kb/s
     self.ub_static_rate = 100
     self.lb_static_rate = 50
     key = '123456789ABCDEFG'
     self.sip = siphash.SipHash_2_4(key)
예제 #9
0
    def forwarding_table_entry(self, index, hosts):
        row_seed = self.calculate_forwarding_table_row_seed(index)

        sorter = lambda ip: int(
            siphash.SipHash_2_4(self.seed_bytes, row_seed + socket.inet_aton(
                ip)).hexdigest(), 16)

        copy = hosts[:]
        copy.sort(key=sorter)
        return copy
예제 #10
0
	def __init__(self, controller):

		self.IpPort = controller
		print "initialized TopologyBuilder with address : ", controller
		self.topology = {}
		self.nodes = []
		self.ports = {}
		self.nx_topology = None
		self.max_capacity = 0.0
		key = '0123456789ABCDEF'
		self.sip = siphash.SipHash_2_4(key)
예제 #11
0
def get_bucket(target, salt, mode):
    if node_to_asn[target] == None or target.find('onion') != -1:
        return -1
    if mode == Mode.ASN_BUCKETS:
        val = node_to_asn[target].replace('AS', '')
    elif mode == Mode.NETGROUP_BUCKETS:
        val = node_to_netgroup[target]
    else:
        assert (0)
    val = str(int(val) + salt)
    hash = siphash.SipHash_2_4(HASH_KEY, val.encode()).hash()
    return hash % BUCKETS
예제 #12
0
    def _compute_auth(full_id, type_, body, secret_key):
        # type: (int, ExtendedSmallMessageType, bitstring.Bits, bytes) -> int

        packed_mac_inputs = bitstring.pack(
            [
                "uintle:32=full_id",
                "uintle:8=extended_type_code",
                "uintle:16=body_for_auth",  # 10 bits, left is 0-padded
            ],
            full_id=full_id,
            extended_type_code=type_.value[0],
            body_for_auth=body.uint)
        mac_input_bytes = packed_mac_inputs.tobytes()
        assert len(mac_input_bytes) == 7
        # 12 MSB bits are MAC/auth
        return siphash.SipHash_2_4(secret_key, mac_input_bytes).hash() >> 52
 def loop(self):
     sequence = 0
     while True:
         command = raw_input("Enter a command: ")
         sip = siphash.SipHash_2_4(
             self.key).update(command + ';' + str(sequence)).hexdigest()
         self.arduino.write(command + ';' + str(sequence) + ';' + str(sip))
         print(command + ';' + str(sequence) + ';' + str(sip))
         sequence += 1
         if (command == 's'):
             break
         while True:
             ack = self.arduino.readline()
             if ack != None:
                 break
         print ack
예제 #14
0
	def pkt_hash(self, key, src_addr=None, dst_addr=None, src_port=None, dst_port=None, fields=('src_addr',)):
		hash_parts = []
		if 'src_addr' in fields:
			hash_parts.append(self._encode_addr(src_addr))
		if 'dst_addr' in fields:
			hash_parts.append(self._encode_addr(dst_addr))
		if 'src_port' in fields:
			hash_parts.append(self._encode_port(src_port))
		if 'dst_port' in fields:
			hash_parts.append(self._encode_port(dst_port))
		
		assert len(hash_parts) > 0
		hash_data = ''.join(hash_parts)

		hash_bytes = siphash.SipHash_2_4(key, hash_data).digest()
		hash_num, = struct.unpack('<Q', hash_bytes)
		return hash_num
예제 #15
0
파일: full.py 프로젝트: angaza/nexus-python
    def _generate_mac(self):
        # generate the internal, *truncated* MAC digits for this message
        # MAC is generated over 9 total bytes:
        # 4 = full_message_id (as uint32_t)
        # 1 = message_type (as uint8_t)
        # 4 = contents of body (as uint32_t)
        function = siphash.SipHash_2_4(self.secret_key)

        packed_for_check = bitstring.pack(
            [
                "uintle:32=full_id",
                "uintle:8=message_type",
                "uintle:32=body_int",
            ],  # uint32_t repr of body digits
            full_id=self.full_id,
            message_type=self.message_type.value,
            body_int=self.body_int,
        )

        function.update(packed_for_check.bytes)

        # check/MAC is the lowest 6 decimal digits from the computed check
        return "{:06d}".format(function.hash() & 0xFFFFFFFF)[-6:]
예제 #16
0
def sync():
    """ return drinks catalog


    :return: JSON request tous les capteurs de la classe
    """
    sip = siphash.SipHash_2_4(key)

    now = round(time.time())
    elements = session.query(
        Inventory, Inventory.name,
        Inventory.price).filter(Inventory.quantity > 0).all()
    elementsID = session.query(
        Inventory, Inventory.id).filter(Inventory.quantity > 0).all()

    catalog = [e.name + " " + "{:.2f}".format(e.price / 100) for e in elements]
    catalogDBID = [e.id for e in elementsID]
    request = {
        'Header': "DrinkingBuddy",
        'Products': catalog,
        'DBID': catalogDBID,
        'Time': now
    }

    hash_str = request['Header'] + "".join(catalog) + now.__str__()
    for c in hash_str:
        sip.update(binascii.a2b_qp(c))

    #reqHash = hex(sip.hash())[2:-1].upper()  #This change is not working on Coltello, but works on the RaspberryPi!!!
    reqHash = hex(sip.hash())[2:].upper()
    reqHash = reqHash.zfill(16)

    request['Hash'] = reqHash

    print(request['Hash'])

    return json.dumps(request)
예제 #17
0
def add_command(args):
    print "*** Add Vlls From Configuration File"

    print "*** Read Previous Vlls Inserted"
    if os.path.exists('./vlls.json'):
        vllsDb = open('./vlls.json', 'r')
        vlllines = vllsDb.readlines()
        vllsDb.close()
    else:
        vlllines = {}

    read_conf_file()

    # We use this algorithm for the name generation
    key = '0123456789ABCDEF'
    sip = siphash.SipHash_2_4(key)
    # Extract from cmd line options the controlller information
    controllerRestIp = args.controllerRestIp
    # Dictionary that stores the mapping port:next_label
    # We allocate the label using a counter, and we associate for each port used in this execution the next usable label
    # Probably in future we can add the persistence for the label
    sw_port_tag = {}
    convert_intf_to_port_number(controllerRestIp)

    # We can have more than one vlls
    for vll in pusher_cfg['vlls']:

        # Retrieve the information
        srcSwitch = vll['lhs_dpid']
        srcPort = vll['lhs_intf']
        dstSwitch = vll['rhs_dpid']
        dstPort = vll['rhs_intf']
        srcLabel = vll['lhs_label']
        dstLabel = vll['rhs_label']

        print "*** Generate Name From VLL (%s-%s-%s) - (%s-%s-%s)" % (
            srcSwitch, srcPort, srcLabel, dstSwitch, dstPort, dstLabel)
        sip.update(srcSwitch + "$" + srcPort + "$" + dstSwitch + "$" +
                   dstPort + "$" + srcLabel + "$" + dstLabel)
        # Generate the name
        digest = sip.hash()
        digest = str(digest)

        print "*** Vll Name", digest

        vllExists = False

        # if the vll exists in the vllDb, we don't insert the flow
        for line in vlllines:
            data = json.loads(line)
            if data['name'] == (digest):
                print "Vll %s exists already Skip" % digest
                vllExists = True
                break

        if vllExists == True:
            continue

        print "*** Create Vll:"
        print "*** From Source Device OSHI-PE %s Port %s" % (srcSwitch,
                                                             srcPort)
        print "*** To Destination Device OSHI-PE %s Port %s" % (dstSwitch,
                                                                dstPort)

        # Retrieving route from source to destination
        # using Routing rest API

        command = "curl -s http://%s/wm/topology/route/%s/%s/%s/%s/json | python -mjson.tool" % (
            controllerRestIp, srcSwitch, srcPort, dstSwitch, dstPort)
        result = os.popen(command).read()
        parsedResult = json.loads(result)

        print
        #print "*** Sent Command:", command + "\n"
        print "*** Received Result:", result + "\n"

        # Dictionary used for store the label of current vll
        temp_sw_port_tag = {}

        # We insert the rule each two json item, because floodlight's getRoute for each dpid, provides
        # A couple of item the in/out port and the out/in port for the rules forward/reverse - see the
        # output of the previous command
        temp_key1 = None
        temp_key2 = None
        temp_tag1 = None
        temp_tag2 = None
        ap1Dpid = None
        ap1Port = None
        ap2Dpid = None
        ap2Port = None

        default = 2
        max_value = 4095

        if int(srcLabel) > max_value or int(dstLabel) > max_value:
            print "Ingress or Egress Label Not Allowable"
            sys.exit(-2)

        # We generate the labels associated for each port, while the ingress/egress and egress/ingress labels
        # come from the configuration file, because they depend on the local network choice
        for j in range(0, (len(parsedResult))):
            # Label for the LHS port
            if j == 0:
                temp_key1 = srcSwitch + "-" + srcPort
                temp_sw_port_tag[temp_key1] = int(srcLabel)
                if sw_port_tag.get(temp_key1, default) <= int(srcLabel):
                    sw_port_tag[temp_key1] = int(srcLabel)
            # Label for the RHS port
            elif j == (len(parsedResult) - 1):
                temp_key1 = dstSwitch + "-" + dstPort
                temp_sw_port_tag[temp_key1] = int(dstLabel)
                if sw_port_tag.get(temp_key1, default) <= int(dstLabel):
                    sw_port_tag[temp_key1] = int(dstLabel)
            # Middle ports
            else:
                apDPID = parsedResult[j]['switch']
                apPORT = parsedResult[j]['port']
                temp_key1 = apDPID + "-" + str(apPORT)
                value = sw_port_tag.get(temp_key1, default)
                temp_sw_port_tag[temp_key1] = value
                value = value + 1
                sw_port_tag[temp_key1] = value

        print "*** Current Route Tag:"
        print json.dumps(temp_sw_port_tag, sort_keys=True, indent=4)
        print
        print "*** Global Routes Tag:"
        print json.dumps(sw_port_tag, sort_keys=True, indent=4)
        print

        # Manage the special case of one hop
        if len(parsedResult) == 2:
            print "*** One Hop Route"
            # The Switch, where we insert the rule
            ap1Dpid = parsedResult[0]['switch']
            # In port
            ap1Port = str(parsedResult[0]['port'])
            temp_key1 = ap1Dpid + "-" + ap1Port
            tag1 = temp_sw_port_tag[temp_key1]
            # ap1Dpid == ap2Dpid
            ap2Dpid = parsedResult[1]['switch']
            # Out port
            ap2Port = str(parsedResult[1]['port'])
            temp_key2 = ap2Dpid + "-" + ap2Port
            tag2 = temp_sw_port_tag[temp_key2]

            if tag1 == 0 and tag2 == 0:
                # Forward's Rule
                command = "curl -s -d '{\"switch\": \"%s\", \"name\":\"%s\", \"cookie\":\"0\", \"priority\":\"32768\", \"ingress-port\":\"%s\",\"active\":\"true\", \"actions\":\"output=%s\"}' http://%s/wm/staticflowentrypusher/json | python -mjson.tool" % (
                    ap1Dpid, ap1Dpid + "." + digest + ".f", ap1Port, ap2Port,
                    controllerRestIp)
                result = os.popen(command).read()
                print "*** Sent Command:", command + "\n"
                print "*** Received Result:", result + "\n"
            elif tag1 != 0 and tag2 == 0:
                # Forward's Rule
                command = "curl -s -d '{\"switch\": \"%s\", \"name\":\"%s\", \"vlan-id\":\"%s\", \"cookie\":\"0\", \"priority\":\"32768\", \"ingress-port\":\"%s\",\"active\":\"true\", \"actions\":\"strip-vlan,output=%s\"}' http://%s/wm/staticflowentrypusher/json | python -mjson.tool" % (
                    ap1Dpid, ap1Dpid + "." + digest + ".f", tag1, ap1Port,
                    ap2Port, controllerRestIp)
                result = os.popen(command).read()
                print "*** Sent Command:", command + "\n"
                print "*** Received Result:", result + "\n"
            elif tag1 == 0 and tag2 != 0:
                # Forward's Rule
                command = "curl -s -d '{\"switch\": \"%s\", \"name\":\"%s\", \"vlan-id\":\"%s\", \"cookie\":\"0\", \"priority\":\"32768\", \"ingress-port\":\"%s\",\"active\":\"true\", \"actions\":\"set-vlan-id=%s,output=%s\"}' http://%s/wm/staticflowentrypusher/json | python -mjson.tool" % (
                    ap1Dpid, ap1Dpid + "." + digest + ".f", "0xffff", ap1Port,
                    tag2, ap2Port, controllerRestIp)
                result = os.popen(command).read()
                print "*** Sent Command:", command + "\n"
                print "*** Received Result:", result + "\n"
            else:
                # Forward's Rule
                command = "curl -s -d '{\"switch\": \"%s\", \"name\":\"%s\", \"vlan-id\":\"%s\", \"cookie\":\"0\", \"priority\":\"32768\", \"ingress-port\":\"%s\",\"active\":\"true\", \"actions\":\"set-vlan-id=%s,output=%s\"}' http://%s/wm/staticflowentrypusher/json | python -mjson.tool" % (
                    ap1Dpid, ap1Dpid + "." + digest + ".f", tag1, ap1Port,
                    tag2, ap2Port, controllerRestIp)
                result = os.popen(command).read()
                print "*** Sent Command:", command + "\n"
                print "*** Received Result:", result + "\n"

            if tag2 == 0 and tag1 == 0:
                # Reverse Forward's Rule
                command = "curl -s -d '{\"switch\": \"%s\", \"name\":\"%s\", \"cookie\":\"0\", \"priority\":\"32768\", \"ingress-port\":\"%s\",\"active\":\"true\", \"actions\":\"output=%s\"}' http://%s/wm/staticflowentrypusher/json | python -mjson.tool" % (
                    ap1Dpid, ap1Dpid + "." + digest + ".r", ap2Port, ap1Port,
                    controllerRestIp)
                result = os.popen(command).read()
                print "*** Sent Command:", command + "\n"
                print "*** Received Result:", result + "\n"

            elif tag2 != 0 and tag1 == 0:
                # Reverse Forward's Rule
                command = "curl -s -d '{\"switch\": \"%s\", \"name\":\"%s\", \"vlan-id\":\"%s\", \"cookie\":\"0\", \"priority\":\"32768\", \"ingress-port\":\"%s\",\"active\":\"true\", \"actions\":\"strip-vlan,output=%s\"}' http://%s/wm/staticflowentrypusher/json | python -mjson.tool" % (
                    ap1Dpid, ap1Dpid + "." + digest + ".r", tag2, ap2Port,
                    ap1Port, controllerRestIp)
                result = os.popen(command).read()
                print "*** Sent Command:", command + "\n"
                print "*** Received Result:", result + "\n"
            elif tag2 == 0 and tag1 != 0:
                # Reverse Forward's Rule
                command = "curl -s -d '{\"switch\": \"%s\", \"name\":\"%s\", \"vlan-id\":\"%s\", \"cookie\":\"0\", \"priority\":\"32768\", \"ingress-port\":\"%s\",\"active\":\"true\", \"actions\":\"set-vlan-id=%s,output=%s\"}' http://%s/wm/staticflowentrypusher/json | python -mjson.tool" % (
                    ap1Dpid, ap1Dpid + "." + digest + ".r", "0xffff", ap2Port,
                    tag1, ap1Port, controllerRestIp)
                result = os.popen(command).read()
                print "*** Sent Command:", command + "\n"
                print "*** Received Result:", result + "\n"
            else:
                # Reverse Forward's Rule
                command = "curl -s -d '{\"switch\": \"%s\", \"name\":\"%s\", \"vlan-id\":\"%s\", \"cookie\":\"0\", \"priority\":\"32768\", \"ingress-port\":\"%s\",\"active\":\"true\", \"actions\":\"set-vlan-id=%s,output=%s\"}' http://%s/wm/staticflowentrypusher/json | python -mjson.tool" % (
                    ap1Dpid, ap1Dpid + "." + digest + ".r", tag2, ap2Port,
                    tag1, ap1Port, controllerRestIp)
                result = os.popen(command).read()
                print "*** Sent Command:", command + "\n"
                print "*** Received Result:", result + "\n"

            store_vll(digest, ap1Dpid)
            # see the image one_hop for details on the switching label procedure

        else:
            # In the other cases we use a different approach for the rule; before we see the label
            # of the inport and outport of the same dpid; with more than one hop we see in general for
            # the forward rule the label of the inport on the next switch, while in the reverse rule the label of the inport on the
            # previous switch. The previous approach is nested in a for loop, we use this loop in the middle dpid, while
            # we manage as special case the ingress/egress node, because the rules are different
            print "*** %s Hop Route" % (len(parsedResult) / 2)
            # We manage first ingress/egress node
            print "*** Create Ingress Rules For LHS Of The Vll - %s" % (
                srcSwitch)
            # see the image more_than_one_hop for details on the switching label procedure
            ap1Dpid = parsedResult[0]['switch']
            ap1Port = parsedResult[0]['port']
            temp_key1 = ap1Dpid + "-" + str(ap1Port)
            tag1 = temp_sw_port_tag[temp_key1]
            print "*** inKey: %s, inTag: %s" % (temp_key1, tag1)
            ap2Dpid = parsedResult[1]['switch']
            ap2Port = parsedResult[1]['port']
            temp_key2 = parsedResult[2]['switch'] + "-" + str(
                parsedResult[2]['port'])
            tag2 = temp_sw_port_tag[temp_key2]
            print "*** outKey: %s, outTag: %s" % (temp_key2, tag2)
            print
            if tag1 == 0 and tag2 != 0:
                command = "curl -s -d '{\"switch\": \"%s\", \"name\":\"%s\", \"vlan-id\":\"%s\", \"cookie\":\"0\", \"priority\":\"32768\", \"ingress-port\":\"%s\",\"active\":\"true\", \"actions\":\"set-vlan-id=%s,output=%s\"}' http://%s/wm/staticflowentrypusher/json | python -mjson.tool" % (
                    ap1Dpid, ap1Dpid + "." + digest + ".f", "0xffff", ap1Port,
                    tag2, ap2Port, controllerRestIp)
                result = os.popen(command).read()
                print "*** Sent Command:", command + "\n"
                print "*** Received Result:", result + "\n"
            elif tag1 != 0 and tag2 != 0:
                command = "curl -s -d '{\"switch\": \"%s\", \"name\":\"%s\", \"vlan-id\":\"%s\", \"cookie\":\"0\", \"priority\":\"32768\", \"ingress-port\":\"%s\",\"active\":\"true\", \"actions\":\"set-vlan-id=%s,output=%s\"}' http://%s/wm/staticflowentrypusher/json | python -mjson.tool" % (
                    ap1Dpid, ap1Dpid + "." + digest + ".f", tag1, ap1Port,
                    tag2, ap2Port, controllerRestIp)
                result = os.popen(command).read()
                print "*** Sent Command:", command + "\n"
                print "*** Received Result:", result + "\n"
            else:
                print "Error Tag"
                sys.exit(-2)

            print "*** Create Egress Rules For LHS Of The Vll - %s" % (
                srcSwitch)
            temp_key2 = temp_key1
            tag2 = tag1
            temp_key1 = ap2Dpid + "-" + str(ap2Port)
            tag1 = temp_sw_port_tag[temp_key1]
            print "*** inKey: %s, inTag: %s" % (temp_key1, tag1)
            print "*** outKey: %s, outTag: %s" % (temp_key2, tag2)
            print
            if tag1 != 0 and tag2 == 0:
                command = "curl -s -d '{\"switch\": \"%s\", \"name\":\"%s\", \"vlan-id\":\"%s\", \"cookie\":\"0\", \"priority\":\"32768\", \"ingress-port\":\"%s\",\"active\":\"true\", \"actions\":\"strip-vlan,output=%s\"}' http://%s/wm/staticflowentrypusher/json | python -mjson.tool" % (
                    ap1Dpid, ap1Dpid + "." + digest + ".r", tag1, ap2Port,
                    ap1Port, controllerRestIp)
                result = os.popen(command).read()
                print "*** Sent Command:", command + "\n"
                print "*** Received Result:", result + "\n"
            elif tag1 != 0 and tag2 != 0:
                command = "curl -s -d '{\"switch\": \"%s\", \"name\":\"%s\", \"vlan-id\":\"%s\", \"cookie\":\"0\", \"priority\":\"32768\", \"ingress-port\":\"%s\",\"active\":\"true\", \"actions\":\"set-vlan-id=%s,output=%s\"}' http://%s/wm/staticflowentrypusher/json | python -mjson.tool" % (
                    ap1Dpid, ap1Dpid + "." + digest + ".r", tag1, ap2Port,
                    tag2, ap1Port, controllerRestIp)
                result = os.popen(command).read()
                print "*** Sent Command:", command + "\n"
                print "*** Received Result:", result + "\n"
            else:
                print "Error Tag"
                sys.exit(-2)

            store_vll(digest, ap1Dpid)

            print "*** Create Egress Rules For RHS Of The Vll - %s" % (
                dstSwitch)
            ap1Dpid = parsedResult[len(parsedResult) - 2]['switch']
            ap1Port = parsedResult[len(parsedResult) - 2]['port']
            temp_key1 = ap1Dpid + "-" + str(ap1Port)
            tag1 = temp_sw_port_tag[temp_key1]
            print "*** inKey: %s, inTag: %s" % (temp_key1, tag1)
            ap2Dpid = parsedResult[len(parsedResult) - 1]['switch']
            ap2Port = parsedResult[len(parsedResult) - 1]['port']
            temp_key2 = ap2Dpid + "-" + str(ap2Port)
            tag2 = temp_sw_port_tag[temp_key2]
            print "*** outKey: %s, outTag: %s" % (temp_key2, tag2)
            print
            if tag1 != 0 and tag2 == 0:
                command = "curl -s -d '{\"switch\": \"%s\", \"name\":\"%s\", \"vlan-id\":\"%s\", \"cookie\":\"0\", \"priority\":\"32768\", \"ingress-port\":\"%s\",\"active\":\"true\", \"actions\":\"strip-vlan,output=%s\"}' http://%s/wm/staticflowentrypusher/json | python -mjson.tool" % (
                    ap1Dpid, ap1Dpid + "." + digest + ".f", tag1, ap1Port,
                    ap2Port, controllerRestIp)
                result = os.popen(command).read()
                print "*** Sent Command:", command + "\n"
                print "*** Received Result:", result + "\n"
            elif tag1 != 0 and tag2 != 0:
                command = "curl -s -d '{\"switch\": \"%s\", \"name\":\"%s\", \"vlan-id\":\"%s\", \"cookie\":\"0\", \"priority\":\"32768\", \"ingress-port\":\"%s\",\"active\":\"true\", \"actions\":\"set-vlan-id=%s,output=%s\"}' http://%s/wm/staticflowentrypusher/json | python -mjson.tool" % (
                    ap1Dpid, ap1Dpid + "." + digest + ".f", tag1, ap1Port,
                    tag2, ap2Port, controllerRestIp)
                result = os.popen(command).read()
                print "*** Sent Command:", command + "\n"
                print "*** Received Result:", result + "\n"
            else:
                print "Error Tag"
                sys.exit(-2)

            print "*** Create Ingress Rules For RHS Of The Vll - %s" % (
                dstSwitch)
            temp_key1 = parsedResult[len(parsedResult) -
                                     3]['switch'] + "-" + str(
                                         parsedResult[len(parsedResult) -
                                                      3]['port'])
            tag1 = temp_sw_port_tag[temp_key1]
            print "*** inKey: %s, inTag: %s" % (temp_key2, tag2)
            print "*** outKey: %s, outTag: %s" % (temp_key1, tag1)
            print
            if tag1 != 0 and tag2 == 0:
                command = "curl -s -d '{\"switch\": \"%s\", \"name\":\"%s\", \"vlan-id\":\"%s\", \"cookie\":\"0\", \"priority\":\"32768\", \"ingress-port\":\"%s\",\"active\":\"true\", \"actions\":\"set-vlan-id=%s,output=%s\"}' http://%s/wm/staticflowentrypusher/json | python -mjson.tool" % (
                    ap1Dpid, ap1Dpid + "." + digest + ".r", "0xffff", ap2Port,
                    tag1, ap1Port, controllerRestIp)
                result = os.popen(command).read()
                print "*** Sent Command:", command + "\n"
                print "*** Received Result:", result + "\n"
            elif tag1 != 0 and tag2 != 0:
                command = "curl -s -d '{\"switch\": \"%s\", \"name\":\"%s\", \"vlan-id\":\"%s\", \"cookie\":\"0\", \"priority\":\"32768\", \"ingress-port\":\"%s\",\"active\":\"true\", \"actions\":\"set-vlan-id=%s,output=%s\"}' http://%s/wm/staticflowentrypusher/json | python -mjson.tool" % (
                    ap1Dpid, ap1Dpid + "." + digest + ".r", tag2, ap2Port,
                    tag1, ap1Port, controllerRestIp)
                result = os.popen(command).read()
                print "*** Sent Command:", command + "\n"
                print "*** Received Result:", result + "\n"
            else:
                print "Error Tag"
                sys.exit(-2)
            store_vll(digest, ap1Dpid)

            # Now we manage the middle nodes
            for i in range(2, (len(parsedResult) - 2)):
                print "index:", i
                if i % 2 == 0:
                    ap1Dpid = parsedResult[i]['switch']
                    ap1Port = parsedResult[i]['port']
                    print ap1Dpid, ap1Port
                else:
                    ap2Dpid = parsedResult[i]['switch']
                    ap2Port = parsedResult[i]['port']
                    print ap2Dpid, ap2Port

                    print "*** Create Rules For %s" % ap1Dpid

                    # send one flow mod per pair in route
                    # using StaticFlowPusher rest API

                    temp_key1 = ap1Dpid + "-" + str(ap1Port)
                    tag1 = temp_sw_port_tag[temp_key1]
                    print "*** inKey: %s, inTag: %s" % (temp_key1, tag1)
                    temp_key2 = parsedResult[i + 1]['switch'] + "-" + str(
                        parsedResult[i + 1]['port'])
                    tag2 = temp_sw_port_tag[temp_key2]
                    print "*** outKey: %s, outTag: %s" % (temp_key2, tag2)
                    print
                    command = "curl -s -d '{\"switch\": \"%s\", \"name\":\"%s\", \"vlan-id\":\"%s\", \"cookie\":\"0\", \"priority\":\"32768\", \"ingress-port\":\"%s\",\"active\":\"true\", \"actions\":\"set-vlan-id=%s,output=%s\"}' http://%s/wm/staticflowentrypusher/json | python -mjson.tool" % (
                        ap1Dpid, ap1Dpid + "." + digest + ".f", tag1, ap1Port,
                        tag2, ap2Port, controllerRestIp)
                    result = os.popen(command).read()
                    print "*** Sent Command:", command + "\n"
                    print "*** Received Result:", result + "\n"

                    temp_key1 = ap2Dpid + "-" + str(ap2Port)
                    tag1 = temp_sw_port_tag[temp_key1]
                    print "*** inKey: %s, inTag: %s" % (temp_key1, tag1)
                    temp_key2 = parsedResult[i - 2]['switch'] + "-" + str(
                        parsedResult[i - 2]['port'])
                    tag2 = temp_sw_port_tag[temp_key2]
                    print "*** outKey: %s, outTag: %s" % (temp_key2, tag2)
                    print
                    command = "curl -s -d '{\"switch\": \"%s\", \"name\":\"%s\", \"vlan-id\":\"%s\", \"cookie\":\"0\", \"priority\":\"32768\", \"ingress-port\":\"%s\",\"active\":\"true\", \"actions\":\"set-vlan-id=%s,output=%s\"}' http://%s/wm/staticflowentrypusher/json | python -mjson.tool" % (
                        ap1Dpid, ap1Dpid + "." + digest + ".r", tag1, ap2Port,
                        tag2, ap1Port, controllerRestIp)
                    result = os.popen(command).read()
                    print "*** Sent Command:", command + "\n"
                    print "*** Received Result:", result + "\n"
                    store_vll(digest, ap1Dpid)
def generate_post_key(image_data) -> str:
    s = str(datetime.datetime.now()) + str(len(image_data))
    return siphash.SipHash_2_4(SIPHASH_KEY, bytearray(
        s.encode('utf-8'))).hexdigest().decode('utf-8')
예제 #19
0
 def obfuscateDecimal(self, blob):
     key = '0123456789ABCDEF'
     sip = siphash.SipHash_2_4(key)
     sip.update(blob)
     return sip.hash() & 0xFFFFFFFFFFFFFFFF
예제 #20
0
    def chunk(iteration):
        hash_function = siphash.SipHash_2_4(fixed_key, int_to_bytes(iteration) + seed)

        return bitstring.pack("uintle:64", hash_function.hash())
예제 #21
0
	def __init__(self):
		self.nx_topology = None
		self.max_capacity = 0.0
		key = '0123456789ABCDEF'
		self.sip = siphash.SipHash_2_4(key)
예제 #22
0
 def obfuscate(self, blob):
     key = '0123456789ABCDEF'
     sip = siphash.SipHash_2_4(key)
     sip.update(blob)
     return str(sip.hash())
예제 #23
0
 def calculate_forwarding_table_row_seed(self, index):
     index_bytes = struct.pack('>I', index)
     return siphash.SipHash_2_4(self.seed_bytes, index_bytes).digest()
def flow_pusher(nx_topology, flow_catalogue, nx_flows, ctrl_endpoint):

    print "*** Add Vlls From Configuration File"

    print "*** Read Previous Vlls Inserted"
    if os.path.exists('./vlls.json'):
        vllsDb = open('./vlls.json', 'r')
        vlllines = vllsDb.readlines()
        vllsDb.close()
    else:
        vlllines = {}

    if os.path.exists('./pws.json'):
        pwsDb = open('./pws.json', 'r')
        pwlines = pwsDb.readlines()
        pwsDb.close()
    else:
        pwlines = {}

    # We use this algorithm for the name generation
    key = '0123456789ABCDEF'
    sip = siphash.SipHash_2_4(key)
    # Extract from cmd line options the controlller information
    controllerRestIp = ctrl_endpoint
    # Dictionary that stores the mapping port:next_label
    # We allocate the label using a counter, and we associate for each port used in this execution the next usable label
    # Probably in future we can add the persistence for the label
    sw_port_label = {}

    for flow_id, (src, dst, flow_dict) in flow_catalogue.iteritems():
        for direction, data in flow_dict.iteritems():

            if data['type'] != 'vll' or data['allocated'] == False:
                break

            # Retrieve the ingress/egress information
            if direction == 'out':
                srcSwitch = src
                srcPort = data['srcPort']
                dstSwitch = dst
                dstPort = data['dstPort']
            elif direction == 'in':
                srcSwitch = dst
                srcPort = data['srcPort']
                dstSwitch = src
                dstPort = data['dstPort']

            srcLabel = 0
            dstLabel = 0

            print "*** Generate Name From VLL (%s-%s-%s) - (%s-%s-%s)" % (
                srcSwitch, srcPort, 0, dstSwitch, dstPort, 0)
            sip.update(srcSwitch + "$" + srcPort + "$" + dstSwitch + "$" +
                       dstPort + "$" + "0" + "$" + "0")
            # Generate the name
            cookie = sip.hash()
            cookie = str(cookie)
            print "*** Vll Name", cookie

            vllExists = False

            # if the vll exists in the vllDb, we don't insert the flow
            for line in vlllines:
                data = json.loads(line)
                if data['name'] == (cookie):
                    print "Vll %s exists already Skip" % cookie
                    vllExists = True
                    break

            if vllExists == True:
                continue

            print "*** Create Vll:"
            print "*** From Source Device OSHI-PE %s Port %s" % (srcSwitch,
                                                                 srcPort)
            print "*** To Destination Device OSHI-PE %s port %s" % (dstSwitch,
                                                                    dstPort)

            # Dictionary used for store the label of current vll
            temp_sw_port_label = {}

            default = 16
            max_value = 131071

            if int(srcLabel) > max_value or int(dstLabel) > max_value:
                print "Ingress or Egress Label Not Allowable"
                sys.exit(-2)

            route = nx_flows[srcSwitch][dstSwitch][flow_id]['path']

            # We generate the labels associated for each port, while the ingress/egress and egress/ingress labels
            # come from the configuration file, because they depend on the local network choice
            for j in range(0, len(route)):
                # Label for the LHS port
                if j == 0:
                    temp_key1 = srcSwitch + "-" + srcPort
                    temp_sw_port_label[temp_key1] = int(srcLabel)
                    if sw_port_label.get(temp_key1, default) <= int(srcLabel):
                        sw_port_label[temp_key1] = int(srcLabel)
                # Label for the RHS port
                elif j == len(route) - 1:
                    temp_key1 = dstSwitch + "-" + dstPort
                    temp_sw_port_label[temp_key1] = int(dstLabel)
                    if sw_port_label.get(temp_key1, default) <= int(dstLabel):
                        sw_port_label[temp_key1] = int(dstLabel)
                # Middle ports
                elif (j > 0 and j < (len(route) - 1)):
                    ap0Dpid = route[j - 1]
                    ap1Dpid = route[j]
                    inlink = retrieve_link_from_id(
                        nx_topology, ap0Dpid, ap1Dpid,
                        "%s-%s" % (flow_id, direction))
                    ap2Dpid = route[j + 1]
                    outlink = retrieve_link_from_id(
                        nx_topology, ap1Dpid, ap2Dpid,
                        "%s-%s" % (flow_id, direction))
                    inPort = inlink['dst_port_no']
                    outPort = outlink['dst_port_no']
                    temp_key1 = ap1Dpid + "-" + str(inPort)
                    value = sw_port_label.get(temp_key1, default)
                    temp_sw_port_label[temp_key1] = value
                    value = value + 1
                    sw_port_label[temp_key1] = value
                    temp_key1 = ap2Dpid + "-" + str(outPort)
                    value = sw_port_label.get(temp_key1, default)
                    temp_sw_port_label[temp_key1] = value
                    value = value + 1
                    sw_port_label[temp_key1] = value

            print "*** Current Route Label:"
            print json.dumps(temp_sw_port_label, sort_keys=True, indent=4)
            print
            print "*** Global Routes Label:"
            print json.dumps(sw_port_label, sort_keys=True, indent=4)
            print

            # Manage the special case of one hop
            if len(route) == 1:
                print "*** One Hop Route"
                # Forward's Rule
                command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\"}, \"actions\":[{\"type\":\"OUTPUT\", \"port\":\"%s\"}]}' http://%s/stats/flowentry/add" % (
                    int(srcSwitch, 16), cookie, pusher_cfg['tableIP'],
                    int(srcPort, 16), int(dstPort, 16), controllerRestIp)
                result = os.popen(command).read()
                print "*** Sent Command:", command + "\n"

                store_vll(cookie, ap1Dpid, pusher_cfg['tableIP'])

            elif (len(route)) >= 2:
                # In the other cases we use a different approach for the rule; before we see the label
                # of the inport and outport of the same dpid; with more than one hop we see in general for
                # the forward rule the label of the inport on the next switch, while in the reverse rule the label of the inport on the
                # previous switch. The previous approach is nested in a for loop, we use this loop in the middle dpid, while
                # we manage as special case the ingress/egress node, because the rules are different
                print "*** %s Hop Route" % len(route)
                # We manage first ingress/egress node
                print "*** Create Ingress Rules For LHS Of The Vll - %s" % (
                    srcSwitch)
                # see the image more_than_one_hop for details on the switching label procedure
                ap1Dpid = route[0]
                ap2Dpid = route[1]
                link = retrieve_link_from_id(nx_topology, ap1Dpid, ap2Dpid,
                                             "%s-%s" % (flow_id, direction))
                ap1Port = link['src_port_no']
                ap2Port = link['dst_port_no']
                temp_key = ap2Dpid + "-" + str(ap2Port)
                label = temp_sw_port_label[temp_key]
                print "*** Key: %s, Label: %s" % (temp_key, label)

                # Rule For IP
                command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\"}, \"actions\":[{\"type\":\"GOTO_TABLE\", \"table_id\":%d}]}' http://%s/stats/flowentry/add" % (
                    int(srcSwitch, 16), cookie, pusher_cfg['tableIP'],
                    int(srcPort,
                        16), "2048", pusher_cfg['tableSBP'], ctrl_endpoint)
                result = os.popen(command).read()
                print "*** Sent Command:", command + "\n"

                # Rule For ARP
                command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\"}, \"actions\":[{\"type\":\"GOTO_TABLE\", \"table_id\":%d}]}' http://%s/stats/flowentry/add" % (
                    int(srcSwitch, 16), cookie, pusher_cfg['tableIP'],
                    int(srcPort,
                        16), "2054", pusher_cfg['tableSBP'], ctrl_endpoint)
                result = os.popen(command).read()
                print "*** Sent Command:", command + "\n"

                store_vll(cookie, srcSwitch, pusher_cfg['tableIP'])

                # Rule For IP
                command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\"}, \"actions\":[{\"type\":\"PUSH_MPLS\", \"ethertype\":\"%s\"}, {\"type\":\"SET_FIELD\", \"field\":\"mpls_label\", \"value\":%s}, {\"type\":\"OUTPUT\", \"port\":\"%s\"}]}' http://%s/stats/flowentry/add" % (
                    int(srcSwitch, 16), cookie, pusher_cfg['tableSBP'],
                    int(srcPort, 16), "2048", "34887", label, int(
                        ap1Port, 16), ctrl_endpoint)
                result = os.popen(command).read()
                print "*** Sent Command:", command + "\n"

                # Rule For ARP
                command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\"}, \"actions\":[{\"type\":\"PUSH_MPLS\", \"ethertype\":\"%s\"}, {\"type\":\"SET_FIELD\", \"field\":\"mpls_label\", \"value\":%s}, {\"type\":\"OUTPUT\", \"port\":\"%s\"}]}' http://%s/stats/flowentry/add" % (
                    int(srcSwitch, 16), cookie, pusher_cfg['tableSBP'],
                    int(srcPort, 16), "2054", "34888", label, int(
                        ap1Port, 16), ctrl_endpoint)
                result = os.popen(command).read()
                print "*** Sent Command:", command + "\n"

                store_vll(cookie, srcSwitch, pusher_cfg['tableSBP'])

                print "*** Create Egress Rules For RHS Of The Vll - %s" % (
                    dstSwitch)
                ap1Dpid = route[(len(route) - 2)]
                ap2Dpid = route[(len(route) - 1)]
                link = retrieve_link_from_id(nx_topology, ap1Dpid, ap2Dpid,
                                             "%s-%s" % (flow_id, direction))
                ap1Port = link['src_port_no']
                ap2Port = link['dst_port_no']
                temp_key = ap2Dpid + "-" + str(ap2Port)
                label = temp_sw_port_label[temp_key]
                print "*** Key: %s, Label: %s" % (temp_key, label)

                # Rule For IP
                command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\", \"mpls_label\":\"%s\"}, \"actions\":[{\"type\":\"POP_MPLS\", \"ethertype\":\"%s\"}, {\"type\":\"OUTPUT\", \"port\":\"%s\"}]}' http://%s/stats/flowentry/add" % (
                    int(dstSwitch, 16), cookie, pusher_cfg['tableSBP'],
                    int(ap2Port, 16), "34887", label, "2048", int(
                        dstPort, 16), ctrl_endpoint)
                result = os.popen(command).read()
                print "*** Sent Command:", command + "\n"

                # Rule For ARP
                command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\", \"mpls_label\":\"%s\"}, \"actions\":[{\"type\":\"POP_MPLS\", \"ethertype\":\"%s\"}, {\"type\":\"OUTPUT\", \"port\":\"%s\"}]}' http://%s/stats/flowentry/add" % (
                    int(dstSwitch, 16), cookie, pusher_cfg['tableSBP'],
                    int(ap2Port, 16), "34888", label, "2054", int(
                        dstPort, 16), ctrl_endpoint)
                result = os.popen(command).read()
                print "*** Sent Command:", command + "\n"

                store_vll(cookie, dstSwitch, pusher_cfg['tableSBP'])

                # Now we manage the middle nodes
                for i in range(0, (len(route) - 2)):
                    print "index:", i
                    ap0Dpid = route[i]
                    ap1Dpid = route[i + 1]
                    inlink = retrieve_link_from_id(
                        nx_topology, ap0Dpid, ap1Dpid,
                        "%s-%s" % (flow_id, direction))
                    ap2Dpid = route[i + 2]
                    outlink = retrieve_link_from_id(
                        nx_topology, ap1Dpid, ap2Dpid,
                        "%s-%s" % (flow_id, direction))
                    ap0Port = inlink['dst_port_no']
                    ap1Port = outlink['src_port_no']
                    ap2Port = outlink['dst_port_no']
                    print ap0Dpid, ap0Port
                    print ap1Dpid, ap1Port
                    print ap2Dpid, ap2Port

                    print "*** Create Rules For %s" % ap1Dpid

                    # send one flow mod per pair in route
                    temp_key = temp_key = ap1Dpid + "-" + str(ap0Port)
                    inlabel = temp_sw_port_label[temp_key]
                    print "*** Key: %s, inLabel: %s" % (temp_key, inlabel)
                    print
                    temp_key = temp_key = ap2Dpid + "-" + str(ap2Port)
                    outlabel = temp_sw_port_label[temp_key]
                    print "*** Key: %s, OutLabel: %s" % (temp_key, outlabel)
                    print

                    # Rule For IP
                    command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\", \"mpls_label\":\"%s\"}, \"actions\":[{\"type\":\"SET_FIELD\", \"field\":\"mpls_label\", \"value\":%s}, {\"type\":\"OUTPUT\", \"port\":\"%s\"}]}' http://%s/stats/flowentry/add" % (
                        int(ap1Dpid, 16), cookie, pusher_cfg['tableSBP'],
                        int(ap0Port, 16), "34887", inlabel, outlabel,
                        int(ap1Port, 16), ctrl_endpoint)
                    result = os.popen(command).read()
                    print "*** Sent Command:", command + "\n"

                    # Rule For ARP
                    command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\", \"mpls_label\":\"%s\"}, \"actions\":[{\"type\":\"SET_FIELD\", \"field\":\"mpls_label\", \"value\":%s}, {\"type\":\"OUTPUT\", \"port\":\"%s\"}]}' http://%s/stats/flowentry/add" % (
                        int(ap1Dpid, 16), cookie, pusher_cfg['tableSBP'],
                        int(ap0Port, 16), "34888", inlabel, outlabel,
                        int(ap1Port, 16), ctrl_endpoint)
                    result = os.popen(command).read()
                    print "*** Sent Command:", command + "\n"

                    store_vll(cookie, ap1Dpid, pusher_cfg['tableSBP'])

            else:
                print "Error Wrong Route"
                sys.exit(-2)
예제 #25
0
        flag_arr[i] = False

    str1 = line.rstrip()
    if is_ascii(str1) == False:
        str1 = removeNonAscii(str1)

    hash_object = hashlib.sha256(str1.encode())  #SHA256
    hex_dig = hash_object.hexdigest()
    index = int(hex_dig, 16)
    index = index % SIZE
    if bloom3[index] == 1:
        flag_arr[0] = True

    import siphash
    key = '0123456789ABCDEF'  #siphash
    sip = siphash.SipHash_2_4(key)
    sip.update(str1)
    h = sip.hash()
    index = h % SIZE
    if bloom3[index] == 1:
        flag_arr[1] = True

    hash_object = mmh3.hash64(str1)  #Murmur
    index = abs(hash_object[1])
    index = index % SIZE
    if bloom3[index] == 1:
        flag_arr[2] = True

    if flag_arr[0] == True and flag_arr[1] == True and flag_arr[2] == True:
        fd_output.write("maybe\n")
    else:
예제 #26
0
파일: epmweb.py 프로젝트: NickeZ/epmweb
def packages_new():
    if 'project' not in request.files:
        return error('No files part')
    file = request.files['project']
    if file.filename == '':
        return error('Empty filename')
    if file and allowed_file(file.filename):
        session = Session()
        filename = secure_filename(file.filename)
        tmp_dir = tempfile.mkdtemp()
        mkdir_p(os.path.join(tmp_dir, 'content'))
        tmp_filename = os.path.join(tmp_dir, filename)
        file.save(tmp_filename)
        with open(tmp_filename, 'rb') as package:
            chksum = siphash.SipHash_2_4(KEY_SIPHASH,
                                         package.read()).hexdigest()
        subprocess.call('tar xf {} -C {}'.format(
            tmp_filename, os.path.join(tmp_dir, 'content')),
                        shell=True)
        with open(os.path.join(tmp_dir, 'content', 'Epm.toml'),
                  'r') as tomlfile:
            manifest = toml.loads(tomlfile.read())
        for author in manifest['project']['authors']:
            matches = re.search(r'<(.*)>', author)
            if matches:
                email = matches.group(1)
            else:
                return error('Invalid author information')
            user = session.query(User).filter_by(email=email).first()
            if user:
                break
        else:
            return error('User not registered')
        if 'description' in manifest['project']:
            desc = manifest['project']['description']
        else:
            desc = None
        if 'repository' in manifest['project']:
            repo = manifest['project']['repository']
        else:
            repo = None
        if 'name' in manifest['project']:
            name = manifest['project']['name']
        else:
            return error('Missing name in manifest file')
        if 'version' in manifest['project']:
            version = manifest['project']['version']
        else:
            return error('Missing version in manifest file')
        pak = session.query(Package).filter_by(name=name).first()
        if not pak:
            pak = Package(
                user_id=user.id,
                name=name,
                max_version=version,
                description=desc,
                repository=repo,
            )
            session.add(pak)
            session.commit()
        else:
            pak.max_version = version
            pak.description = desc
            pak.repository = repo
            pak.updated = datetime.now()
        session.add(Version(package_id=pak.id, version=version))
        session.commit()
    shutil.move(
        tmp_filename,
        os.path.join(
            app.config['UPLOAD_FOLDER'],
            '{}-{}-{}.tar.gz'.format(name, version, chksum.decode('utf-8'))))
    return ok_data({'message': 'Uploaded!', 'chksum': chksum.decode('utf-8')})
예제 #27
0
def add_command(args):
    print "*** Add Vlls From Configuration File"

    print "*** Read Previous Vlls Inserted"
    if os.path.exists('./vlls.json'):
        vllsDb = open('./vlls.json', 'r')
        vlllines = vllsDb.readlines()
        vllsDb.close()
    else:
        vlllines = {}

    if os.path.exists('./pws.json'):
        pwsDb = open('./pws.json', 'r')
        pwlines = pwsDb.readlines()
        pwsDb.close()
    else:
        pwlines = {}

    read_conf_file()

    # We use this algorithm for the name generation
    key = '0123456789ABCDEF'
    sip = siphash.SipHash_2_4(key)
    # Extract from cmd line options the controlller information
    controllerRestIp = args.controllerRestIp
    # Dictionary that stores the mapping port:next_label
    # We allocate the label using a counter, and we associate for each port used in this execution the next usable label
    # Probably in future we can add the persistence for the label
    sw_port_label = {}
    retrieve_port_number_and_mac(controllerRestIp)

    # We can have more than one vlls
    for vll in pusher_cfg['vlls']:

        # Retrieve the information
        srcSwitch = vll['lhs_dpid']
        srcPort = vll['lhs_intf']
        dstSwitch = vll['rhs_dpid']
        dstPort = vll['rhs_intf']
        srcLabel = vll['lhs_label']
        dstLabel = vll['rhs_label']

        print "*** Generate Name From VLL (%s-%s-%s) - (%s-%s-%s)" % (
            srcSwitch, srcPort, srcLabel, dstSwitch, dstPort, dstLabel)
        sip.update(srcSwitch + "$" + srcPort + "$" + dstSwitch + "$" +
                   dstPort + "$" + srcLabel + "$" + dstLabel)
        # Generate the name
        cookie = sip.hash()
        cookie = str(cookie)

        print "*** Vll Name", cookie

        vllExists = False

        # if the vll exists in the vllDb, we don't insert the flow
        for line in vlllines:
            data = json.loads(line)
            if data['name'] == (cookie):
                print "Vll %s exists already Skip" % cookie
                vllExists = True
                break

        if vllExists == True:
            continue

        print "*** Create Vll:"
        print "*** From Source Device OSHI-PE %s Port %s" % (srcSwitch,
                                                             srcPort)
        print "*** To Destination Device OSHI-PE %s port %s" % (dstSwitch,
                                                                dstPort)

        # Retrieving route from source to destination
        # using Routing rest API

        command = "curl -s http://%s/v1.0/topology/route/%s/%s/%s/%s | python -mjson.tool" % (
            controllerRestIp, srcSwitch, srcPort, dstSwitch, dstPort)
        result = os.popen(command).read()
        parsedResult = json.loads(result)

        print
        #print "*** Sent Command:", command + "\n"
        print "*** Received Result:", result + "\n"

        # Dictionary used for store the label of current vll
        temp_sw_port_label = {}

        # We insert the rule each two json item, because floodlight's getRoute for each dpid, provides
        # A couple of item the in/out port and the out/in port for the rules forward/reverse - see the
        # output of the previous command
        temp_key1 = None
        temp_key2 = None
        temp_label1 = None
        temp_label2 = None
        ap1Dpid = None
        ap1Port = None
        ap2Dpid = None
        ap2Port = None

        default = 16
        max_value = 131071

        if int(srcLabel) > max_value or int(dstLabel) > max_value:
            print "Ingress or Egress Label Not Allowable"
            sys.exit(-2)

        # We generate the labels associated for each port, while the ingress/egress and egress/ingress labels
        # come from the configuration file, because they depend on the local network choice
        for j in range(0, (len(parsedResult))):
            # Label for the LHS port
            if j == 0:
                temp_key1 = srcSwitch + "-" + srcPort
                temp_sw_port_label[temp_key1] = int(srcLabel)
                if sw_port_label.get(temp_key1, default) <= int(srcLabel):
                    sw_port_label[temp_key1] = int(srcLabel)
            # Label for the RHS port
            elif j == (len(parsedResult) - 1):
                temp_key1 = dstSwitch + "-" + dstPort
                temp_sw_port_label[temp_key1] = int(dstLabel)
                if sw_port_label.get(temp_key1, default) <= int(dstLabel):
                    sw_port_label[temp_key1] = int(dstLabel)
            # Middle ports
            elif (j > 0 and j < (len(parsedResult) - 1)):
                apDPID = parsedResult[j]['switch']
                apPORT = parsedResult[j]['port']
                temp_key1 = apDPID + "-" + str(apPORT)
                value = sw_port_label.get(temp_key1, default)
                temp_sw_port_label[temp_key1] = value
                value = value + 1
                sw_port_label[temp_key1] = value

        print "*** Current Route Label:"
        print json.dumps(temp_sw_port_label, sort_keys=True, indent=4)
        print
        print "*** Global Routes Label:"
        print json.dumps(sw_port_label, sort_keys=True, indent=4)
        print

        # Manage the special case of one hop
        if len(parsedResult) == 2:
            print "*** One Hop Route"
            # The Switch, where we insert the rule
            ap1Dpid = parsedResult[0]['switch']
            # In port
            ap1Port = str(parsedResult[0]['port'])
            temp_key1 = ap1Dpid + "-" + ap1Port
            label1 = temp_sw_port_label[temp_key1]
            # ap1Dpid == ap2Dpid
            ap2Dpid = parsedResult[1]['switch']
            # Out port
            ap2Port = str(parsedResult[1]['port'])
            temp_key2 = ap2Dpid + "-" + ap2Port
            label2 = temp_sw_port_label[temp_key2]

            # Forward's Rule
            command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\"}, \"actions\":[{\"type\":\"OUTPUT\", \"port\":\"%s\"}]}' http://%s/stats/flowentry/add" % (
                int(ap1Dpid, 16), cookie, pusher_cfg['tableIP'],
                int(ap1Port, 16), int(ap2Port, 16), controllerRestIp)
            result = os.popen(command).read()
            print "*** Sent Command:", command + "\n"

            # Reverse Forward's Rule
            command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\"}, \"actions\":[{\"type\":\"OUTPUT\", \"port\":\"%s\"}]}' http://%s/stats/flowentry/add" % (
                int(ap1Dpid, 16), cookie, pusher_cfg['tableIP'],
                int(ap2Port, 16), int(ap1Port, 16), controllerRestIp)
            result = os.popen(command).read()
            print "*** Sent Command:", command + "\n"

            store_vll(cookie, ap1Dpid, pusher_cfg['tableIP'])
            # see the image one_hop for details on the switching label procedure

        elif (len(parsedResult)) >= 2:
            # In the other cases we use a different approach for the rule; before we see the label
            # of the inport and outport of the same dpid; with more than one hop we see in general for
            # the forward rule the label of the inport on the next switch, while in the reverse rule the label of the inport on the
            # previous switch. The previous approach is nested in a for loop, we use this loop in the middle dpid, while
            # we manage as special case the ingress/egress node, because the rules are different
            print "*** %s Hop Route" % (len(parsedResult) / 2)
            # We manage first ingress/egress node
            print "*** Create Ingress Rules For LHS Of The Vll - %s" % (
                srcSwitch)
            # see the image more_than_one_hop for details on the switching label procedure
            ap1Dpid = parsedResult[0]['switch']
            ap1Port = parsedResult[0]['port']
            temp_key1 = ap1Dpid + "-" + str(ap1Port)
            label1 = temp_sw_port_label[temp_key1]
            print "*** inKey: %s, inLabel: %s" % (temp_key1, label1)
            ap2Dpid = parsedResult[1]['switch']
            ap2Port = parsedResult[1]['port']
            temp_key2 = parsedResult[2]['switch'] + "-" + str(
                parsedResult[2]['port'])
            label2 = temp_sw_port_label[temp_key2]
            print "*** outKey: %s, outLabel: %s" % (temp_key2, label2)
            print

            # Rule For IP
            command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\"}, \"actions\":[{\"type\":\"GOTO_TABLE\", \"table_id\":%d}]}' http://%s/stats/flowentry/add" % (
                int(ap1Dpid, 16), cookie, pusher_cfg['tableIP'],
                int(ap1Port,
                    16), "2048", pusher_cfg['tableSBP'], controllerRestIp)
            result = os.popen(command).read()
            print "*** Sent Command:", command + "\n"

            # Rule For ARP
            command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\"}, \"actions\":[{\"type\":\"GOTO_TABLE\", \"table_id\":%d}]}' http://%s/stats/flowentry/add" % (
                int(ap1Dpid, 16), cookie, pusher_cfg['tableIP'],
                int(ap1Port,
                    16), "2054", pusher_cfg['tableSBP'], controllerRestIp)
            result = os.popen(command).read()
            print "*** Sent Command:", command + "\n"
            store_vll(cookie, ap1Dpid, pusher_cfg['tableIP'])

            # Rule For IP
            command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\"}, \"actions\":[{\"type\":\"PUSH_MPLS\", \"ethertype\":\"%s\"}, {\"type\":\"SET_FIELD\", \"field\":\"mpls_label\", \"value\":%s}, {\"type\":\"OUTPUT\", \"port\":\"%s\"}]}' http://%s/stats/flowentry/add" % (
                int(ap1Dpid, 16), cookie, pusher_cfg['tableSBP'],
                int(ap1Port, 16), "2048", "34887", label2, int(
                    ap2Port, 16), controllerRestIp)
            result = os.popen(command).read()
            print "*** Sent Command:", command + "\n"

            # Rule For ARP
            command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\"}, \"actions\":[{\"type\":\"PUSH_MPLS\", \"ethertype\":\"%s\"}, {\"type\":\"SET_FIELD\", \"field\":\"mpls_label\", \"value\":%s}, {\"type\":\"OUTPUT\", \"port\":\"%s\"}]}' http://%s/stats/flowentry/add" % (
                int(ap1Dpid, 16), cookie, pusher_cfg['tableSBP'],
                int(ap1Port, 16), "2054", "34888", label2, int(
                    ap2Port, 16), controllerRestIp)
            result = os.popen(command).read()
            print "*** Sent Command:", command + "\n"

            print "*** Create Egress Rules For LHS Of The Vll - %s" % (
                srcSwitch)
            temp_key2 = temp_key1
            label2 = label1
            temp_key1 = ap2Dpid + "-" + str(ap2Port)
            label1 = temp_sw_port_label[temp_key1]
            print "*** inKey: %s, inLabel: %s" % (temp_key1, label1)
            print "*** outKey: %s, outLabel: %s" % (temp_key2, label2)
            print

            # Rule For IP
            command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\", \"mpls_label\":\"%s\"}, \"actions\":[{\"type\":\"POP_MPLS\", \"ethertype\":\"%s\"}, {\"type\":\"OUTPUT\", \"port\":\"%s\"}]}' http://%s/stats/flowentry/add" % (
                int(ap1Dpid, 16), cookie, pusher_cfg['tableSBP'],
                int(ap2Port, 16), "34887", label1, "2048", int(
                    ap1Port, 16), controllerRestIp)
            result = os.popen(command).read()
            print "*** Sent Command:", command + "\n"

            # Rule For ARP
            command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\", \"mpls_label\":\"%s\"}, \"actions\":[{\"type\":\"POP_MPLS\", \"ethertype\":\"%s\"}, {\"type\":\"OUTPUT\", \"port\":\"%s\"}]}' http://%s/stats/flowentry/add" % (
                int(ap1Dpid, 16), cookie, pusher_cfg['tableSBP'],
                int(ap2Port, 16), "34888", label1, "2054", int(
                    ap1Port, 16), controllerRestIp)
            result = os.popen(command).read()
            print "*** Sent Command:", command + "\n"

            store_vll(cookie, ap1Dpid, pusher_cfg['tableSBP'])

            print "*** Create Egress Rules For RHS Of The Vll - %s" % (
                dstSwitch)
            ap1Dpid = parsedResult[len(parsedResult) - 2]['switch']
            ap1Port = parsedResult[len(parsedResult) - 2]['port']
            temp_key1 = ap1Dpid + "-" + str(ap1Port)
            label1 = temp_sw_port_label[temp_key1]
            print "*** inKey: %s, inLabel: %s" % (temp_key1, label1)
            ap2Dpid = parsedResult[len(parsedResult) - 1]['switch']
            ap2Port = parsedResult[len(parsedResult) - 1]['port']
            temp_key2 = ap2Dpid + "-" + str(ap2Port)
            label2 = temp_sw_port_label[temp_key2]
            print "*** outKey: %s, outLabel: %s" % (temp_key2, label2)
            print

            # Rule For IP
            command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\", \"mpls_label\":\"%s\"}, \"actions\":[{\"type\":\"POP_MPLS\", \"ethertype\":\"%s\"}, {\"type\":\"OUTPUT\", \"port\":\"%s\"}]}' http://%s/stats/flowentry/add" % (
                int(ap1Dpid, 16), cookie, pusher_cfg['tableSBP'],
                int(ap1Port, 16), "34887", label1, "2048", int(
                    ap2Port, 16), controllerRestIp)
            result = os.popen(command).read()
            print "*** Sent Command:", command + "\n"

            # Rule For ARP
            command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\", \"mpls_label\":\"%s\"}, \"actions\":[{\"type\":\"POP_MPLS\", \"ethertype\":\"%s\"}, {\"type\":\"OUTPUT\", \"port\":\"%s\"}]}' http://%s/stats/flowentry/add" % (
                int(ap1Dpid, 16), cookie, pusher_cfg['tableSBP'],
                int(ap1Port, 16), "34888", label1, "2054", int(
                    ap2Port, 16), controllerRestIp)
            result = os.popen(command).read()
            print "*** Sent Command:", command + "\n"

            print "*** Create Ingress Rules For RHS Of The Vll - %s" % (
                dstSwitch)
            temp_key1 = parsedResult[len(parsedResult) -
                                     3]['switch'] + "-" + str(
                                         parsedResult[len(parsedResult) -
                                                      3]['port'])
            label1 = temp_sw_port_label[temp_key1]
            print "*** inKey: %s, inLabel: %s" % (temp_key2, label2)
            print "*** outKey: %s, outLabel: %s" % (temp_key1, label1)
            print

            # Rule For IP
            command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\"}, \"actions\":[{\"type\":\"PUSH_MPLS\", \"ethertype\":\"%s\"}, {\"type\":\"SET_FIELD\", \"field\":\"mpls_label\", \"value\":%s}, {\"type\":\"OUTPUT\", \"port\":\"%s\"}]}' http://%s/stats/flowentry/add" % (
                int(ap1Dpid, 16), cookie, pusher_cfg['tableSBP'],
                int(ap2Port, 16), "2048", "34887", label1, int(
                    ap1Port, 16), controllerRestIp)
            result = os.popen(command).read()
            print "*** Sent Command:", command + "\n"

            # Rule For ARP
            command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\"}, \"actions\":[{\"type\":\"PUSH_MPLS\", \"ethertype\":\"%s\"}, {\"type\":\"SET_FIELD\", \"field\":\"mpls_label\", \"value\":%s}, {\"type\":\"OUTPUT\", \"port\":\"%s\"}]}' http://%s/stats/flowentry/add" % (
                int(ap1Dpid, 16), cookie, pusher_cfg['tableSBP'],
                int(ap2Port, 16), "2054", "34888", label1, int(
                    ap1Port, 16), controllerRestIp)
            result = os.popen(command).read()
            print "*** Sent Command:", command + "\n"

            store_vll(cookie, ap1Dpid, pusher_cfg['tableSBP'])

            # Rule For IP
            command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\"}, \"actions\":[{\"type\":\"GOTO_TABLE\", \"table_id\":%d}]}' http://%s/stats/flowentry/add" % (
                int(ap1Dpid, 16), cookie, pusher_cfg['tableIP'],
                int(ap2Port,
                    16), "2048", pusher_cfg['tableSBP'], controllerRestIp)
            result = os.popen(command).read()
            print "*** Sent Command:", command + "\n"

            # Rule For ARP
            command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\"}, \"actions\":[{\"type\":\"GOTO_TABLE\", \"table_id\":%d}]}' http://%s/stats/flowentry/add" % (
                int(ap1Dpid, 16), cookie, pusher_cfg['tableIP'],
                int(ap2Port,
                    16), "2054", pusher_cfg['tableSBP'], controllerRestIp)
            result = os.popen(command).read()
            print "*** Sent Command:", command + "\n"

            store_vll(cookie, ap1Dpid, pusher_cfg['tableIP'])

            # Now we manage the middle nodes
            for i in range(2, (len(parsedResult) - 2)):
                print "index:", i
                if i % 2 == 0:
                    ap1Dpid = parsedResult[i]['switch']
                    ap1Port = parsedResult[i]['port']
                    print ap1Dpid, ap1Port
                else:
                    ap2Dpid = parsedResult[i]['switch']
                    ap2Port = parsedResult[i]['port']
                    print ap2Dpid, ap2Port

                    print "*** Create Rules For %s" % ap1Dpid

                    # send one flow mod per pair in route

                    temp_key1 = ap1Dpid + "-" + str(ap1Port)
                    label1 = temp_sw_port_label[temp_key1]
                    print "*** inKey: %s, inLabel: %s" % (temp_key1, label1)
                    temp_key2 = parsedResult[i + 1]['switch'] + "-" + str(
                        parsedResult[i + 1]['port'])
                    label2 = temp_sw_port_label[temp_key2]
                    print "*** outKey: %s, outLabel: %s" % (temp_key2, label2)
                    print

                    # Rule For IP
                    command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\", \"mpls_label\":\"%s\"}, \"actions\":[{\"type\":\"SET_FIELD\", \"field\":\"mpls_label\", \"value\":%s}, {\"type\":\"OUTPUT\", \"port\":\"%s\"}]}' http://%s/stats/flowentry/add" % (
                        int(ap1Dpid, 16), cookie, pusher_cfg['tableSBP'],
                        int(ap1Port, 16), "34887", label1, label2,
                        int(ap2Port, 16), controllerRestIp)
                    result = os.popen(command).read()
                    print "*** Sent Command:", command + "\n"

                    # Rule For ARP
                    command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\", \"mpls_label\":\"%s\"}, \"actions\":[{\"type\":\"SET_FIELD\", \"field\":\"mpls_label\", \"value\":%s}, {\"type\":\"OUTPUT\", \"port\":\"%s\"}]}' http://%s/stats/flowentry/add" % (
                        int(ap1Dpid, 16), cookie, pusher_cfg['tableSBP'],
                        int(ap1Port, 16), "34888", label1, label2,
                        int(ap2Port, 16), controllerRestIp)
                    result = os.popen(command).read()
                    print "*** Sent Command:", command + "\n"

                    temp_key1 = ap2Dpid + "-" + str(ap2Port)
                    label1 = temp_sw_port_label[temp_key1]
                    print "*** inKey: %s, inLabel: %s" % (temp_key1, label1)
                    temp_key2 = parsedResult[i - 2]['switch'] + "-" + str(
                        parsedResult[i - 2]['port'])
                    label2 = temp_sw_port_label[temp_key2]
                    print "*** outKey: %s, outLabel: %s" % (temp_key2, label2)
                    print

                    # Rule For IP
                    command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\", \"mpls_label\":\"%s\"}, \"actions\":[{\"type\":\"SET_FIELD\", \"field\":\"mpls_label\", \"value\":%s}, {\"type\":\"OUTPUT\", \"port\":\"%s\"}]}' http://%s/stats/flowentry/add" % (
                        int(ap1Dpid, 16), cookie, pusher_cfg['tableSBP'],
                        int(ap2Port, 16), "34887", label1, label2,
                        int(ap1Port, 16), controllerRestIp)
                    result = os.popen(command).read()
                    print "*** Sent Command:", command + "\n"

                    # Rule For ARP
                    command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\", \"mpls_label\":\"%s\"}, \"actions\":[{\"type\":\"SET_FIELD\", \"field\":\"mpls_label\", \"value\":%s}, {\"type\":\"OUTPUT\", \"port\":\"%s\"}]}' http://%s/stats/flowentry/add" % (
                        int(ap1Dpid, 16), cookie, pusher_cfg['tableSBP'],
                        int(ap2Port, 16), "34888", label1, label2,
                        int(ap1Port, 16), controllerRestIp)
                    result = os.popen(command).read()
                    print "*** Sent Command:", command + "\n"

                    store_vll(cookie, ap1Dpid, pusher_cfg['tableSBP'])
        else:
            print "Error Wrong Route"
            sys.exit(-2)

    # We can have more than one pws
    for pw in pusher_cfg['pws']:

        # Retrieve the information
        srcSwitch = pw['lhs_dpid']
        srcPort = pw['lhs_intf']
        dstSwitch = pw['rhs_dpid']
        dstPort = pw['rhs_intf']
        srcLabel = pw['lhs_label']
        dstLabel = pw['rhs_label']
        srcMAC = pw['lhs_mac']
        dstMAC = pw['rhs_mac']

        print "*** Generate Name From PW (%s-%s-%s-%s) - (%s-%s-%s-%s)" % (
            srcSwitch, srcPort, srcLabel, srcMAC, dstSwitch, dstPort, dstLabel,
            dstMAC)
        sip.update(srcSwitch + "$" + srcPort + "$" + srcLabel + "$" + srcMAC +
                   "$" + dstSwitch + "$" + dstPort + "$" + dstLabel + "$" +
                   dstMAC)
        # Generate the name
        cookie = sip.hash()
        cookie = str(cookie)

        print "*** Pw Name", cookie

        pwExists = False

        # if the pw exists in the pwDb, we don't insert the flow
        for line in pwlines:
            data = json.loads(line)
            if data['name'] == (cookie):
                print "Pw %s exists already Skip" % cookie
                pwExists = True
                break

        if pwExists == True:
            continue

        print "*** Create Pw:"
        print "*** From Source Device OSHI-PE %s Port %s MAC %s" % (
            srcSwitch, srcPort, srcMAC)
        print "*** To Destination Device OSHI-PE %s port %s MAC %s" % (
            dstSwitch, dstPort, dstMAC)

        # Retrieving route from source to destination
        # using Routing rest API

        command = "curl -s http://%s/v1.0/topology/route/%s/%s/%s/%s | python -mjson.tool" % (
            controllerRestIp, srcSwitch, srcPort, dstSwitch, dstPort)
        result = os.popen(command).read()
        parsedResult = json.loads(result)

        print
        #print "*** Sent Command:", command + "\n"
        print "*** Received Result:", result + "\n"

        # Dictionary used for store the label of current pw
        temp_sw_port_label = {}

        # We insert the rule each two json item, because floodlight's getRoute for each dpid, provides
        # A couple of item the in/out port and the out/in port for the rules forward/reverse - see the
        # output of the previous command
        temp_key1 = None
        temp_key2 = None
        temp_label1 = None
        temp_label2 = None
        ap1Dpid = None
        ap1Port = None
        ap2Dpid = None
        ap2Port = None

        default = 131072
        max_value = 262143

        if int(srcLabel) > max_value or int(dstLabel) > max_value:
            print "Ingress or Egress Label Not Allowable"
            sys.exit(-2)

        # We generate the labels associated for each port
        for j in range(0, (len(parsedResult))):
            # Label for the LHS port
            if j == 0:
                temp_key1 = srcSwitch + "-" + srcPort
                temp_sw_port_label[temp_key1] = int(srcLabel)
                if sw_port_label.get(temp_key1, default) <= int(srcLabel):
                    sw_port_label[temp_key1] = int(srcLabel)
            # Label for the RHS port
            elif j == (len(parsedResult) - 1):
                temp_key1 = dstSwitch + "-" + dstPort
                temp_sw_port_label[temp_key1] = int(dstLabel)
                if sw_port_label.get(temp_key1, default) <= int(dstLabel):
                    sw_port_label[temp_key1] = int(dstLabel)
            # Middle ports
            else:
                apDPID = parsedResult[j]['switch']
                apPORT = parsedResult[j]['port']
                temp_key1 = apDPID + "-" + str(apPORT)
                value = sw_port_label.get(temp_key1, default)
                temp_sw_port_label[temp_key1] = value
                value = value + 1
                sw_port_label[temp_key1] = value

        print "*** Current Route Tag:"
        print json.dumps(temp_sw_port_label, sort_keys=True, indent=4)
        print
        print "*** Global Routes Tag:"
        print json.dumps(sw_port_label, sort_keys=True, indent=4)
        print

        # Manage the special case of one hop
        if len(parsedResult) == 2:
            print "*** One Hop Route"
            # The Switch, where we insert the rule
            ap1Dpid = parsedResult[0]['switch']
            # In port
            ap1Port = str(parsedResult[0]['port'])
            temp_key1 = ap1Dpid + "-" + ap1Port
            label1 = temp_sw_port_label[temp_key1]
            # ap1Dpid == ap2Dpid
            ap2Dpid = parsedResult[1]['switch']
            # Out port
            ap2Port = str(parsedResult[1]['port'])
            temp_key2 = ap2Dpid + "-" + ap2Port
            label2 = temp_sw_port_label[temp_key2]

            # Forward's Rule
            command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\"}, \"actions\":[{\"type\":\"OUTPUT\", \"port\":\"%s\"}]}' http://%s/stats/flowentry/add" % (
                int(ap1Dpid, 16), cookie, pusher_cfg['tableIP'],
                int(ap1Port, 16), int(ap2Port, 16), controllerRestIp)
            result = os.popen(command).read()
            print "*** Sent Command:", command + "\n"

            # Reverse Forward's Rule
            command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\"}, \"actions\":[{\"type\":\"OUTPUT\", \"port\":\"%s\"}]}' http://%s/stats/flowentry/add" % (
                int(ap1Dpid, 16), cookie, pusher_cfg['tableIP'],
                int(ap2Port, 16), int(ap1Port, 16), controllerRestIp)
            result = os.popen(command).read()
            print "*** Sent Command:", command + "\n"

            store_pw(cookie, ap1Dpid, pusher_cfg['tableIP'])
            # see the image one_hop for details on the switching label procedure

        elif (len(parsedResult)) >= 2:
            # In the other cases we use a different approach for the rule; before we see the label
            # of the inport and outport of the same dpid; with more than one hop we see in general for
            # the forward rule the label of the inport on the next switch, while in the reverse rule the label of the inport on the
            # previous switch. The previous approach is nested in a for loop, we use this loop in the middle dpid, while
            # we manage as special case the ingress/egress node, because the rules are different
            print "*** %s Hop Route" % (len(parsedResult) / 2)
            # We manage first ingress/egress node
            print "*** Create Ingress Rules For LHS Of The Pw - %s" % (
                srcSwitch)
            # see the image more_than_one_hop for details on the switching label procedure
            ap1Dpid = parsedResult[0]['switch']
            ap1Port = parsedResult[0]['port']
            temp_key1 = ap1Dpid + "-" + str(ap1Port)
            label1 = temp_sw_port_label[temp_key1]
            print "*** inKey: %s, inLabel: %s" % (temp_key1, label1)
            ap2Dpid = parsedResult[1]['switch']
            ap2Port = parsedResult[1]['port']
            temp_key2 = parsedResult[2]['switch'] + "-" + str(
                parsedResult[2]['port'])
            label2 = temp_sw_port_label[temp_key2]
            print "*** outKey: %s, outLabel: %s" % (temp_key2, label2)
            print

            #match_mac = srcMAC
            src_mac = port_number_to_mac["%s-%s" % (ap2Dpid, ap2Port)]
            dst_mac = port_number_to_mac[temp_key2]

            # Rule For IP
            command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\"}, \"actions\":[{\"type\":\"GOTO_TABLE\", \"table_id\":%d}]}' http://%s/stats/flowentry/add" % (
                int(ap1Dpid, 16), cookie, pusher_cfg['tableIP'],
                int(ap1Port,
                    16), "2048", pusher_cfg['tableSBP'], controllerRestIp)
            result = os.popen(command).read()
            print "*** Sent Command:", command + "\n"

            store_pw(cookie, ap1Dpid, pusher_cfg['tableIP'])

            # Rule For IP
            command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\"}, \"actions\":[{\"type\":\"PUSH_MPLS\", \"ethertype\":\"%s\"}, {\"type\":\"SET_FIELD\", \"field\":\"mpls_label\", \"value\":%s}, {\"type\":\"SET_FIELD\", \"field\":\"eth_src\", \"value\":\"%s\"}, {\"type\":\"SET_FIELD\", \"field\":\"eth_dst\", \"value\":\"%s\"}, {\"type\":\"OUTPUT\", \"port\":\"%s\"}]}' http://%s/stats/flowentry/add" % (
                int(ap1Dpid, 16), cookie, pusher_cfg['tableSBP'],
                int(ap1Port, 16), "2048", "34887", label2, src_mac, dst_mac,
                int(ap2Port, 16), controllerRestIp)
            result = os.popen(command).read()
            print "*** Sent Command:", command + "\n"

            print "*** Create Egress Rules For LHS Of The Pw - %s" % (
                srcSwitch)
            temp_key2 = temp_key1
            label2 = label1
            temp_key1 = ap2Dpid + "-" + str(ap2Port)
            label1 = temp_sw_port_label[temp_key1]
            print "*** inKey: %s, inLabel: %s" % (temp_key1, label1)
            print "*** outKey: %s, outLabel: %s" % (temp_key2, label2)
            print

            match_mac = port_number_to_mac[temp_key1]
            src_mac = dstMAC
            dst_mac = srcMAC

            # Rule For IP
            command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\", \"mpls_label\":\"%s\", \"dl_dst\":\"%s\"}, \"actions\":[{\"type\":\"POP_MPLS\", \"ethertype\":\"%s\"}, {\"type\":\"SET_FIELD\", \"field\":\"eth_src\", \"value\":\"%s\"}, {\"type\":\"SET_FIELD\", \"field\":\"eth_dst\", \"value\":\"%s\"}, {\"type\":\"OUTPUT\", \"port\":\"%s\"}]}' http://%s/stats/flowentry/add" % (
                int(ap1Dpid, 16), cookie, pusher_cfg['tableSBP'],
                int(ap2Port, 16), "34887", label1, match_mac, "2048", src_mac,
                dst_mac, int(ap1Port, 16), controllerRestIp)
            result = os.popen(command).read()
            print "*** Sent Command:", command + "\n"

            store_pw(cookie, ap1Dpid, pusher_cfg['tableSBP'])

            print "*** Create Egress Rules For RHS Of The Pw - %s" % (
                dstSwitch)
            ap1Dpid = parsedResult[len(parsedResult) - 2]['switch']
            ap1Port = parsedResult[len(parsedResult) - 2]['port']
            temp_key1 = ap1Dpid + "-" + str(ap1Port)
            label1 = temp_sw_port_label[temp_key1]
            print "*** inKey: %s, inLabel: %s" % (temp_key1, label1)
            ap2Dpid = parsedResult[len(parsedResult) - 1]['switch']
            ap2Port = parsedResult[len(parsedResult) - 1]['port']
            temp_key2 = ap2Dpid + "-" + str(ap2Port)
            label2 = temp_sw_port_label[temp_key2]
            print "*** outKey: %s, outLabel: %s" % (temp_key2, label2)
            print

            match_mac = port_number_to_mac[temp_key1]
            src_mac = srcMAC
            dst_mac = dstMAC

            # Rule For IP
            command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\", \"mpls_label\":\"%s\", \"dl_dst\":\"%s\"}, \"actions\":[{\"type\":\"POP_MPLS\", \"ethertype\":\"%s\"}, {\"type\":\"SET_FIELD\", \"field\":\"eth_src\", \"value\":\"%s\"}, {\"type\":\"SET_FIELD\", \"field\":\"eth_dst\", \"value\":\"%s\"}, {\"type\":\"OUTPUT\", \"port\":\"%s\"}]}' http://%s/stats/flowentry/add" % (
                int(ap1Dpid, 16), cookie, pusher_cfg['tableSBP'],
                int(ap1Port, 16), "34887", label1, match_mac, "2048", src_mac,
                dst_mac, int(ap2Port, 16), controllerRestIp)
            result = os.popen(command).read()
            print "*** Sent Command:", command + "\n"

            print "*** Create Ingress Rules For RHS Of The Pw - %s" % (
                dstSwitch)
            temp_key1 = parsedResult[len(parsedResult) -
                                     3]['switch'] + "-" + str(
                                         parsedResult[len(parsedResult) -
                                                      3]['port'])
            label1 = temp_sw_port_label[temp_key1]
            print "*** inKey: %s, inLabel: %s" % (temp_key2, label2)
            print "*** outKey: %s, outLabel: %s" % (temp_key1, label1)
            print

            match_mac = dstMAC
            temp_key2 = ap1Dpid + "-" + str(ap1Port)
            src_mac = port_number_to_mac[temp_key2]
            dst_mac = port_number_to_mac[temp_key1]

            # Rule For IP
            command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\"}, \"actions\":[{\"type\":\"PUSH_MPLS\", \"ethertype\":\"%s\"}, {\"type\":\"SET_FIELD\", \"field\":\"mpls_label\", \"value\":%s}, {\"type\":\"SET_FIELD\", \"field\":\"eth_src\", \"value\":\"%s\"}, {\"type\":\"SET_FIELD\", \"field\":\"eth_dst\", \"value\":\"%s\"}, {\"type\":\"OUTPUT\", \"port\":\"%s\"}]}' http://%s/stats/flowentry/add" % (
                int(ap1Dpid, 16), cookie, pusher_cfg['tableSBP'],
                int(ap2Port, 16), "2048", "34887", label1, src_mac, dst_mac,
                int(ap1Port, 16), controllerRestIp)
            result = os.popen(command).read()
            print "*** Sent Command:", command + "\n"

            store_pw(cookie, ap1Dpid, pusher_cfg['tableSBP'])

            # Rule For IP
            command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\"}, \"actions\":[{\"type\":\"GOTO_TABLE\", \"table_id\":%d}]}' http://%s/stats/flowentry/add" % (
                int(ap1Dpid, 16), cookie, pusher_cfg['tableIP'],
                int(ap2Port,
                    16), "2048", pusher_cfg['tableSBP'], controllerRestIp)
            result = os.popen(command).read()
            print "*** Sent Command:", command + "\n"

            store_pw(cookie, ap1Dpid, pusher_cfg['tableIP'])

            # Now we manage the middle nodes
            for i in range(2, (len(parsedResult) - 2)):
                print "index:", i
                if i % 2 == 0:
                    ap1Dpid = parsedResult[i]['switch']
                    ap1Port = parsedResult[i]['port']
                    print ap1Dpid, ap1Port
                else:
                    ap2Dpid = parsedResult[i]['switch']
                    ap2Port = parsedResult[i]['port']
                    print ap2Dpid, ap2Port

                    print "*** Create Rules For %s" % ap1Dpid

                    # send one flow mod per pair in route

                    temp_key1 = ap1Dpid + "-" + str(ap1Port)
                    label1 = temp_sw_port_label[temp_key1]
                    print "*** inKey: %s, inLabel: %s" % (temp_key1, label1)
                    temp_key2 = parsedResult[i + 1]['switch'] + "-" + str(
                        parsedResult[i + 1]['port'])
                    label2 = temp_sw_port_label[temp_key2]
                    print "*** outKey: %s, outLabel: %s" % (temp_key2, label2)
                    print

                    match_mac = port_number_to_mac[ap1Dpid + "-" +
                                                   str(ap1Port)]
                    src_mac = port_number_to_mac[ap2Dpid + "-" + str(ap2Port)]
                    dst_mac = port_number_to_mac[temp_key2]

                    # Rule For IP
                    command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\", \"mpls_label\":\"%s\", \"dl_dst\":\"%s\"}, \"actions\":[{\"type\":\"SET_FIELD\", \"field\":\"mpls_label\", \"value\":%s},  {\"type\":\"SET_FIELD\", \"field\":\"eth_src\", \"value\":\"%s\"}, {\"type\":\"SET_FIELD\", \"field\":\"eth_dst\", \"value\":\"%s\"}, {\"type\":\"OUTPUT\", \"port\":\"%s\"}]}' http://%s/stats/flowentry/add" % (
                        int(ap1Dpid, 16), cookie, pusher_cfg['tableSBP'],
                        int(ap1Port, 16), "34887", label1, match_mac, label2,
                        src_mac, dst_mac, int(ap2Port, 16), controllerRestIp)
                    result = os.popen(command).read()
                    print "*** Sent Command:", command + "\n"

                    temp_key1 = ap2Dpid + "-" + str(ap2Port)
                    label1 = temp_sw_port_label[temp_key1]
                    print "*** inKey: %s, inLabel: %s" % (temp_key1, label1)
                    temp_key2 = parsedResult[i - 2]['switch'] + "-" + str(
                        parsedResult[i - 2]['port'])
                    label2 = temp_sw_port_label[temp_key2]
                    print "*** outKey: %s, outLabel: %s" % (temp_key2, label2)
                    print

                    match_mac = port_number_to_mac[temp_key1]
                    src_mac = port_number_to_mac[ap1Dpid + "-" + str(ap1Port)]
                    dst_mac = port_number_to_mac[temp_key2]

                    # Rule For IP
                    command = "curl -s -d '{\"dpid\": \"%s\", \"cookie\":\"%s\", \"priority\":\"32768\", \"table_id\":%d, \"match\":{\"in_port\":\"%s\", \"eth_type\":\"%s\", \"mpls_label\":\"%s\", \"dl_dst\":\"%s\"}, \"actions\":[{\"type\":\"SET_FIELD\", \"field\":\"mpls_label\", \"value\":%s}, {\"type\":\"SET_FIELD\", \"field\":\"eth_src\", \"value\":\"%s\"}, {\"type\":\"SET_FIELD\", \"field\":\"eth_dst\", \"value\":\"%s\"}, {\"type\":\"OUTPUT\", \"port\":\"%s\"}]}' http://%s/stats/flowentry/add" % (
                        int(ap1Dpid, 16), cookie, pusher_cfg['tableSBP'],
                        int(ap2Port, 16), "34887", label1, match_mac, label2,
                        src_mac, dst_mac, int(ap1Port, 16), controllerRestIp)
                    result = os.popen(command).read()
                    print "*** Sent Command:", command + "\n"

                    store_pw(cookie, ap1Dpid, pusher_cfg['tableSBP'])
        else:
            print "Error Wrong Route"
            sys.exit(-2)
예제 #28
0
def callhash(hashkey, inval):
    return siphash.SipHash_2_4(hashkey, inval).hash()
예제 #29
0
 def get_hash(self, to_hash):
     return siphash.SipHash_2_4(self.tkey, to_hash).hash()
예제 #30
0
def buy():
    """ buy request


    :return: JSON request tous les capteurs de la classe
    """
    sipout = siphash.SipHash_2_4(key)
    sipin = siphash.SipHash_2_4(key)

    now = round(time.time())

    dict_req = request.get_json()

    badge = dict_req['Badge']
    product = dict_req['Product']
    time_req = dict_req['Time']
    print("Buying: " + product + " Badge: " + badge)

    hash_verif = badge + str(product) + str(time_req)
    for c in hash_verif:
        sipin.update(binascii.a2b_qp(c))

    #reqHash = hex(sipin.hash())[2:-1].upper();  #This change not working on coltello, works on raspberry
    reqHash = hex(sipin.hash())[2:].upper()
    reqHash = reqHash.zfill(16)

    if dict_req['Hash'] == reqHash:
        print("Cool hash's OK")
    else:
        print("Hash pas Cool !!!!!!!!!!")
        return json.dumps("ERROR")
    print(badge + " " + product + " " + time_req + " " + dict_req['Hash'])

    currentUser = session.query(User).filter(User.id == int(badge, 16)).one()
    currentItem = session.query(Inventory).filter(
        Inventory.id == int(product)).one()
    currentItem.quantity = currentItem.quantity - 1
    currentUser.balance = currentUser.balance - currentItem.price

    ret = []
    if (currentItem.quantity < 0):
        session.rollback()
        print('product not in stock anymore' + str(currentItem.price) + " " +
              currentItem.name + "  " + str(currentItem.quantity))
        ret = {
            'Melody': "b2c3b2",
            'Message': ['ERROR', 'Not in stock'],
            'Time': now.__str__()
        }
    elif (
            currentUser.balance + currentItem.price < currentItem.price
    ):  #we do the + price again because we need to compare before deducting the price
        session.rollback()
        print('not enough money in the account!')
        ret = {
            'Melody': "b2c3b2",
            'Message': ['ERROR', 'Too poor!'],
            'Time': now.__str__()
        }
    else:
        print([currentUser.name, "{:.2f}".format(currentUser.balance / 100)])
        new_transaction = Transaction(date=datetime.datetime.now(),
                                      value=1,
                                      user=currentUser,
                                      element=currentItem)
        session.add(new_transaction)
        ret = {
            'Melody': "a1b1c1d1e1f1g1",
            'Message': ['Successfull transaction', 'Have a nice day'],
            'Time': now.__str__()
        }
        #if(randint(1,20) != 20 & currentItem.category_id == 2) #If 20 (5% chance) then we give a free beer!  ----> Syntax needs to be corrected
        #    currentUser.balance = currentUser.balance + currentItem.price #Give back the money
        #    ret = {'Melody': "2d2a1f2c2d2a2d2c2f2d2a2c2d2a1f2c2d2a2a2g2p8p8p8p", 'Message': ['YOU WON!!! :)', 'FREE BEER!'], 'Time': now.__str__()}
        session.commit()

    hash_str = ret['Melody'] + "".join(ret['Message']) + now.__str__()
    for c in hash_str:
        sipout.update(binascii.a2b_qp(c))

    #retHash = hex(sipout.hash())[2:-1].upper()  #This change not working on Coltello, works on Raspbbery
    retHash = hex(sipout.hash())[2:].upper()
    retHash = retHash.zfill(16)

    ret['Hash'] = retHash

    return json.dumps(ret)