deploy.py 2.71 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 import Process
import time, threading
from python_arptable import get_arp_table
import random
from enums import States, Table

app = Flask(__name__)
retry_timer = 10
prefix_lenght = 16
filename = {}

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

@app.route('/key', methods = ['GET', 'POST'])
def key():
  f = open("rsa_key.pub", "r")
  key = f.read()
  f.close()
  return key

@app.route('/data', methods = ['POST'])
def data():
  prefix = newprefix()
  key = request.files.get('key')
  if key != None:
    key.save(prefix + "_key")
  request.files['data'].save(prefix)
  filename[prefix] = request.files['data'].filename
  return prefix

def newprefix():
  prefix = ""
  i = 0
  while i < prefix_lenght:
    range = random.randrange(3)
    if range == 0:
      prefix += chr(random.randrange(48,58))
    if range == 1:
      prefix += chr(random.randrange(65,91))
    if range == 2:
      prefix += chr(random.randrange(97,123))
    i += 1
  return prefix

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

  prefix = request.values['id']
  if not os.path.exists(prefix):
    return "El id de la data es invalido"

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

  query = {
    'path' : prefix,
    'file' : filename.pop(prefix),
    'serv' : request.values['serv'],
    'dest' : request.values['dest'],
    'type' : request.values['type']
  }
  id = process.store(query)
  return str(id)

@app.route('/cons', methods = ['POST'])
def cons():
  process = Process('messages.db')
  id_query = request.form['id']
  row = process.lookup(id_query)
  if type(row) == str:  # error message
    return row 
  if row[Table.state] == States.delivered:
    os.system("rm " + row[Table.path])
  return str(row[Table.state])

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

if __name__ == "__main__":
  # generate keys
  os.system("openssl genrsa -out rsa_key.pri 4096") # private key
  os.system("openssl rsa -in rsa_key.pri -out rsa_key.pub -outform PEM -pubout") # public key
  # starts attempt daemon
  attempt()
  app.run("0.0.0.0")