deploy.py 2.64 KB
#-*- coding: utf-8 -*-
from flask import Flask, render_template, json, request, url_for
from werkzeug.datastructures import FileStorage
import os
import ipdb
from process_message import Process
import time, threading
from python_arptable import get_arp_table

app = Flask(__name__)
retry_timer = 10

@app.route('/')
def main():
  return render_template('index.html')

@app.route('/init', methods = ['GET', 'POST'])
def init():
  mac = mac_from_ip(request.remote_addr)
  if mac == None:
    return "Error de inicializacion, no se pudo conseguir la MAC"
  if not os.path.exists(mac):
    os.mkdir(mac)
  return key(mac)

def key(dir):
  os.system("openssl genrsa -out ./" + dir + "/rsa_key.pri 2048") # private key
  os.system("openssl rsa -in ./" + dir + "/rsa_key.pri -out ./" + dir + "/rsa_key.pub -outform PEM -pubout") # public key

  f = open("./" + dir + "/rsa_key.pub", "r")
  key = f.read()
  f.close()
  return key

def mac_from_ip(ip):
  os.system("ping " + ip + " c1")
  for i in get_arp_table():
    if i['IP address'] == ip:
      return i['HW address']
  return None

@app.route('/data', methods = ['POST'])
def data():
  dir = mac_from_ip(request.remote_addr)
  if not os.path.exists(dir):
    return "Debe llamar a /init primero"

  key = request.files.get('key')
  if key != None:
    key.save("./" + dir + "/key")
  request.files['data'].save("./" + dir + "/data")
  return ""

@app.route('/msg', methods = ['POST'])
def msg():
  process = Process('messages.db')

  dir = mac_from_ip(request.remote_addr)
  if not os.path.exists(dir):
    return "Debe llamar a /init primero"

  # symetric key was sent, decrypt data
  if os.path.exists("./" + dir + "/key"):
    # decrypt random key with stored private key and store in host folder
    os.system("openssl rsautl -decrypt -inkey ./" + dir + "/rsa_key.pri -in ./" + dir + "/key -out ./" + dir + "/key")
    # decrypt JSON with decrypted random key and store in dir folder
    os.system("openssl enc -d -aes-256-cbc -in ./" + dir + "/data -out ./" + dir + "/data -pass file:./" + dir + "/key")
    # delete key
    os.system("rm ./" + dir + "/key")

  query = {
    'dir' : dir,
    'serv' : request.values['serv'],
    'dest' : request.values['dest'],
    'type' : request.values['type']
  }
  id = process.store(query)
  os.system("mv ./data ./" + id)

@app.route('/cons', methods = ['POST'])
def cons():
  process = Process('messages.db')
  id_query = request.form['id']
  query_state = process.lookup(id_query)
  return query_state

def attempt():
  process = Process('messages.db')
  process.send()
  threading.Timer(retry_timer, attempt).start()

if __name__ == "__main__":
  # starts attempt daemon
  attempt()
  app.run("0.0.0.0")