Ejemplo n.º 1
0
 def __exit__(self, *args, **kwargs):
     """
     Desc:   Close cursor and database connections
     Input:  args -> [*args] :: redundant data
             kwargs -> [**kwargs] :: redundant data
     """
     try:
         self.cursor.close()
         self.connection.close()
     except Exception as e:
         Error.log(e)
Ejemplo n.º 2
0
 def __exit__(self, *args, **kwargs):
     """
     Desc:   Close cursor and database connections
     Input:  args -> [*args] :: redundant data
             kwargs -> [**kwargs] :: redundant data
     """
     try:
         self.cursor.close()
         self.connection.close()
     except Exception as e:
         Error.log(e)
Ejemplo n.º 3
0
 def test(self):
     """
     Test the MySQL connection
     :return: Boolean
     """
     sql = "SELECT version()"
     try:
         self.cursor.execute(sql)
     except Exception as e:
         Error.log(e)
         return False
     else:
         return True
Ejemplo n.º 4
0
 def test(self):
     """
     Test the MySQL connection
     :return: Boolean
     """
     sql = "SELECT version()"
     try:
         self.cursor.execute(sql)
     except Exception as e:
         Error.log(e)
         return False
     else:
         return True
Ejemplo n.º 5
0
 def __enter__(self):
     """
     Desc:   Attempt to connect to database
     Output: self
     """
     try:
         database = pymysql.connect(option_files=self.conf_file)
         cursor = database.cursor()
     except Exception as e:
         Error.log(e)
         return e  # Development only!
     else:
         self.cursor, self.connection = cursor, database
         return self
Ejemplo n.º 6
0
 def query(self, sql, args):
     """
     Desc:   Execute SQL query
     Input:  sql -> [string] :: valid SQL query
             args -> [tuple] :: arguments required in query
     Output: Boolean
     """
     try:
         self.cursor.execute(sql, args)
     except Exception as e:
         Error.log(e)
         return False
     else:
         return True
Ejemplo n.º 7
0
 def __enter__(self):
     """
     Desc:   Attempt to connect to database
     Output: self
     """
     try:
         database = pymysql.connect(option_files=self.conf_file)
         cursor = database.cursor()
     except Exception as e:
         Error.log(e)
         return e  # Development only!
     else:
         self.cursor, self.connection = cursor, database
         return self
Ejemplo n.º 8
0
 def query(self, sql, args):
     """
     Desc:   Execute SQL query
     Input:  sql -> [string] :: valid SQL query
             args -> [tuple] :: arguments required in query
     Output: Boolean
     """
     try:
         self.cursor.execute(sql, args)
     except Exception as e:
         Error.log(e)
         return False
     else:
         return True
Ejemplo n.º 9
0
def plain_upload(data):
    """
    Decode non-encrypted file stream
    :param data: [MiniFieldStorage] file stream
    :return: JSON formatted string
    """
    try:
        data = bytes.decode(data.file.read()).strip()
        data = bytes.decode(base64.b64decode(str.encode(data))).replace("'", '"')
        data = json.loads(data)
    except Exception:
        Error.load_error_page('Your file has been corrupted or is invalid.')
        sys.exit()
    else:
        return json.dumps(data)
Ejemplo n.º 10
0
def plain_upload(data):
    """
    Decode non-encrypted file stream
    :param data: [MiniFieldStorage] file stream
    :return: JSON formatted string
    """
    try:
        data = bytes.decode(data.file.read()).strip()
        data = bytes.decode(base64.b64decode(str.encode(data))).replace(
            "'", '"')
        data = json.loads(data)
    except Exception:
        Error.load_error_page('Your file has been corrupted or is invalid.')
        sys.exit()
    else:
        return json.dumps(data)
Ejemplo n.º 11
0
def secure_upload(data, password):
    """
    Decrypt AES an encrypted file stream
    :param data: [MiniFieldStorage] file stream
    :param password: [string] password
    :return: JSON formatted string
    """
    password = hashlib.sha256(str.encode(password)).digest()  # Calculate SHA-256
    try:
        data = bytes.decode(data.file.read()).strip()
        data = bytes.decode(Database.aes_decrypt(password, data)).replace("'", '"')
        data = json.loads(data)
    except Exception:
        Error.load_error_page('Your file has been corrupted, is invalid, or a wrong password was used.')
        sys.exit()
    else:
        return json.dumps(data)
Ejemplo n.º 12
0
def access_session(session_id, session_key, is_save=False, **kwargs):
    """
    Retrieve user data from database based on session data
    :param session_id: [string] session identifier
    :param session_key: [string] session checksum
    :param is_save: [boolean] save/read mode
    :param kwargs: [**] optional parameters
    :return: JSON string, session identifier, session checksum | None
    """
    with Database.DatabaseGet() as db:
        user_ref = db.validate_session(session_id, session_key)
    if user_ref and not is_save:
        with Database.DatabaseGet() as db:
            data = db.retrieve_user_data(user_ref)
            enc_key = db.retrieve_user_key(user_ref)  # Get AES key
        with Database.DatabaseDrop() as db:
            db.delete_session(session_id)  # Delete login session
        with Database.DatabasePut() as db:
            session_id, session_key = db.register_new_session(user_ref)
        # Decrypt data
        data = bytes.decode(Database.aes_decrypt(enc_key,
                                                 data)).replace("'", '"')
        data = json.loads(data)
        return json.dumps(data), session_id, session_key
    elif user_ref and is_save:
        #with Database.DatabaseDrop() as db:
        #    db.delete_session(session_id)
        with Database.DatabaseGet() as db:
            enc_key = db.retrieve_user_key(user_ref)
        with Database.DatabasePut() as db:
            db.update_user_data(
                Database.aes_encrypt(enc_key, parse.unquote(kwargs['data'])),
                user_ref)
        #kwargs['callback'].load_home()
        print("Content-Type: application/json\n\n")
        print(json.dumps({'status': 'OK'}))
    else:
        Error.load_error_page(
            'Your session expired or is invalid. {} {} {}'.format(
                user_ref, session_id, session_key))
        sys.exit()
Ejemplo n.º 13
0
def secure_upload(data, password):
    """
    Decrypt AES an encrypted file stream
    :param data: [MiniFieldStorage] file stream
    :param password: [string] password
    :return: JSON formatted string
    """
    password = hashlib.sha256(
        str.encode(password)).digest()  # Calculate SHA-256
    try:
        data = bytes.decode(data.file.read()).strip()
        data = bytes.decode(Database.aes_decrypt(password,
                                                 data)).replace("'", '"')
        data = json.loads(data)
    except Exception:
        Error.load_error_page(
            'Your file has been corrupted, is invalid, or a wrong password was used.'
        )
        sys.exit()
    else:
        return json.dumps(data)
Ejemplo n.º 14
0
def access_session(session_id, session_key, is_save=False, **kwargs):
    """
    Retrieve user data from database based on session data
    :param session_id: [string] session identifier
    :param session_key: [string] session checksum
    :param is_save: [boolean] save/read mode
    :param kwargs: [**] optional parameters
    :return: JSON string, session identifier, session checksum | None
    """
    with Database.DatabaseGet() as db:
        user_ref = db.validate_session(session_id, session_key)
    if user_ref and not is_save:
        with Database.DatabaseGet() as db:
            data = db.retrieve_user_data(user_ref)
            enc_key = db.retrieve_user_key(user_ref)  # Get AES key
        with Database.DatabaseDrop() as db:
            db.delete_session(session_id)  # Delete login session
        with Database.DatabasePut() as db:
            session_id, session_key = db.register_new_session(user_ref)
        # Decrypt data
        data = bytes.decode(Database.aes_decrypt(enc_key, data)).replace("'", '"')
        data = json.loads(data)
        return json.dumps(data), session_id, session_key
    elif user_ref and is_save:
        #with Database.DatabaseDrop() as db:
        #    db.delete_session(session_id)
        with Database.DatabaseGet() as db:
            enc_key = db.retrieve_user_key(user_ref)
        with Database.DatabasePut() as db:
            db.update_user_data(Database.aes_encrypt(enc_key, parse.unquote(kwargs['data'])), user_ref)
        #kwargs['callback'].load_home()
        print("Content-Type: application/json\n\n")
        print(json.dumps({'status': 'OK'}))
    else:
        Error.load_error_page('Your session expired or is invalid. {} {} {}'.format(user_ref, session_id, session_key))
        sys.exit()
Ejemplo n.º 15
0
def main():
    """
    Supervise the POST requests and assign them to the right functions
    :return: None
    """
    cgitb.enable()  # development only!
    if 'CONTENT_TYPE' in os.environ and 'multipart/form-data' in os.environ[
            'CONTENT_TYPE']:
        parameters = cgi.FieldStorage()
    else:
        parameters = cgi.FieldStorage(
            environ={'REQUEST_METHOD':
                     'POST'})  # Fix for x-www-form-urlencoded
    protocol = parameters.getvalue('prc')
    # Determine action based on protocol value
    actions = {
        # Check if user name exists
        'checkName':
        lambda: Comms.check_username(parameters.getvalue('username')),
        # Register a new cloud user, includes anonymous and regular
        'newUser':
        lambda: Comms.create_new_user(parameters),
        # Generate a new encrypted profile file and parse it back
        'newSecureFile':
        lambda: Comms.create_new_file(parameters.getvalue('data'),
                                      pwd=parameters.getvalue('pwd'),
                                      encrypted=True,
                                      cookieId=parameters.getvalue('cookieId'),
                                      additional=parameters),
        # Generate a new plain profile file and parse it back
        'newPlainFile':
        lambda: Comms.create_new_file(parameters.getvalue('data'),
                                      additional=parameters,
                                      cookieId=parameters.getvalue('cookieId')
                                      ),
        # Check if access code is valid
        'checkCode':
        lambda: Comms.validate_user_code(parameters.getvalue('code')),
        # Interpret user data and load profile Dashboard HTML; cloud only
        'loadProfile':
        lambda: Page.load_profile(parameters.getvalue('sid'),
                                  parameters.getvalue('skey')),
        # Load the configurator page
        'loadConfig':
        lambda: Page.load_config(
            parameters.getvalue('code') if ACCESS_RESTRICTION else None),
        # Validate login credentials and return session key
        'standardLogin':
        lambda: Comms.standard_login(parameters.getvalue('username'),
                                     parameters.getvalue('pwd')),
        # Upload encrypted file and load Dashboard
        'secureUpload':
        lambda: Page.load_profile(0,
                                  0,
                                  local=True,
                                  encrypted=True,
                                  pwd=parameters.getvalue('pwd'),
                                  data=parameters['data']),
        # Upload plain file and display in Dashboard
        'plainUpload':
        lambda: Page.load_profile(
            None, None, local=True, data=parameters['data']),
        # Re-encrypt user data and parse file back
        'saveSecureFile':
        lambda: Comms.repackage_file(parameters.getvalue('data'),
                                     pwd=parameters.getvalue('pwd'),
                                     cookieId=parameters.getvalue('cookieId')),
        # Re-encode user data and parse it back
        'savePlainFile':
        lambda: Comms.repackage_file(parameters.getvalue('data'),
                                     cookieId=parameters.getvalue('cookieId')),
        # Save user session data to database
        'saveUser':
        lambda: Comms.access_session(parameters.getvalue('sid'),
                                     parameters.getvalue('skey'),
                                     is_save=True,
                                     data=parameters.getvalue('data'),
                                     callback=None),
        # Delete user session from database when no data is saved
        'noSaveUser':
        lambda: Comms.kill_session_no_save(parameters.getvalue('sid'))
    }
    try:
        actions[protocol]() if protocol in actions else Page.load_home()
    except Exception as e:
        Error.log(e)
        print("Content-Type: text/html\n\n",
              traceback.format_exc())  # development only!