Example #1
0
def do_login():

    # This post function will create the first administrator if there is no user database.

    # As a safety measure check if the auth.db file exists

    if os.path.isfile(os.path.dirname(os.path.abspath(__file__)) + "/lib/auth.db"):
        # Userdatabase is found!
        # Kick user away from page.
        response.status = 303
        response.set_header('Location', '/logout')
    else:
        # Get the user details from the registration form.
        username = request.forms.get('username')
        password = request.forms.get('password')

        # Hash the password.
        hash = sha512_crypt.encrypt(password)

        # Create the sqlite database with the right path.
        con = sqlite3.connect(config["paths"]["file_auth_database"])

        # Save the administrator in the database.
        with con:
            cur = con.cursor()
            cur.execute("CREATE TABLE secure_login(ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, Username TEXT NOT NULL UNIQUE, Password BLOB NOT NULL, SessionID BLOB UNIQUE, SessionStartTime BLOB)")
            cur.execute("INSERT INTO secure_login(ID,Username,Password) VALUES (?,?,?)", (1,username,hash))

        # Now redirect the user back to the correct page.
        response.status = 303
        response.set_header('Location', '/')
Example #2
0
def get_build_file(project=None, branch=None, system=None, fsdate=None, bfile=None):
    '''get file for build'''
    validate_build(project, branch, system)

    ext = os.path.splitext(bfile)[1]
    path = os.path.join(SETTINGS['builds_directory'], project)
    path = os.path.join(path, branch)
    path = os.path.join(path, system)
    path = os.path.join(path, fsdate)

    if not os.path.exists(path):
        abort(404, "Build does not exist.")

    if bfile == 'build-status.png':
        response.set_header('Cache-control', 'no-cache')
        response.set_header('Pragma', 'no-cache')
        if not failure_for_build(project, branch, system, fsdate):
            return static_file('ok.png', root='media/status/')
        return static_file('fail.png', root='media/status/')
    elif ext == '.zip':
        return static_file(bfile, root=path)
    elif ext == '.bz2':
        return static_file(bfile, root=path)
    elif ext == '.txt':
        response.content_type = 'text/plain'
        path = os.path.join(path, bfile.replace('.txt', '.bz2'))
        if os.path.exists(path):
            return bz2.BZ2File(path).read()

    abort(404, 'No such file.')
Example #3
0
def show__page_about():

    # Connect to the database.
    conn = sqlite3.connect(config["paths"]["file_auth_database"])
    c = conn.cursor()
    c.execute("SELECT SessionID FROM secure_login")
    rows = c.fetchall()

    for row in rows:
        for col in row:
            username = request.get_cookie("username", secret=col)
            if username != None:
                # Delete cookie
                response.delete_cookie("username", secret=col)
                c.execute("UPDATE secure_login SET SessionID = (?) WHERE Username = (?)", (None, str(username),))
                c.close()
                response.status = 303
                response.set_header('Location', '/')
                break
            else:
                pass
    c.close()

    # Now redirect the user back to the correct page.
    response.status = 303
    response.set_header('Location', '/')
Example #4
0
def show__page_install():

    # This page should only be viewed if there is no user database.
    if os.path.isfile(config["paths"]["file_auth_database"]):
        # Userdatabase is found!
        # Kick user away from page.
        response.status = 303
        response.set_header('Location', '/logout')
    else:
        return template('install')
Example #5
0
def list_item_check(name, index):
    validate_list(name)

    list_contents = get_list(name)

    list_contents[index]['is_checked'] = not list_contents[index]['is_checked']

    update_list(name, list_contents)

    response.status = 303
    response.set_header('Location', "/l/" + name)
Example #6
0
def list_item_check(name, index):
    validate_list(name)

    list_contents = get_list(name)

    list_contents[index]['is_checked'] = not list_contents[index]['is_checked']

    update_list(name, list_contents)

    response.status = 303
    response.set_header('Location', "/l/" + name)
Example #7
0
def show_page_index():

    # Check for user database file.
    if os.path.isfile(config["paths"]["file_auth_database"]):
        # Userdatabase is found, show log-in page.
        pass
    else:
        # User database not found.
        # Start registration script.
        response.status = 303
        response.set_header('Location', '/install')
Example #8
0
def post_page_logs():

    # This post function will check the selected options on the logs page.

    # Check which boxes are selected in the datatable
    form_data = request.forms.getall('chkBox')

    # Check if the list is empty (nothing is selected). If so, redirect the user to the user came from.
    if len(form_data) == 0:
        response.status = 303
        response.set_header('Location', '/logs')

    # Pass results back to the view
    return template('view_log', url=url, form_data=form_data, config=config)
Example #9
0
def do_login():

    # This post function will check if the user log-in credentials are correct.

    # Get the user details from the login form.
    username = request.forms.get('username')
    password = request.forms.get('password')

    try:
        # Connect to the database.
        conn = sqlite3.connect(config["paths"]["file_auth_database"])
        c = conn.cursor()
        c.execute("SELECT Password FROM secure_login WHERE Username = ?", (str(username),))
        rows = c.fetchall()
        c.close()
    except OperationalError:
        # If the user is not found in the database and we don't know the password, exit authentication.
        abort(403, "Authentication failed.")

    if len(rows) == 0:
        abort(403, "Authentication failed.")

    # Check if the password from the user matches the passwored stored in the database.
    for row in rows:
        for col in row:
            check = sha512_crypt.verify(password, col)
            if check == True:
                # Password and username checks passed. Now proceeding for setting authenticated session cookie.

                # Generate unique session ID.
                session_start_time = str(datetime.datetime.now())
                secret = sha512_crypt.encrypt(session_start_time)

                # Save cookie secret and session start time to the db.
                conn = sqlite3.connect(config["paths"]["file_auth_database"])
                c = conn.cursor()
                c.execute("UPDATE secure_login SET SessionID = (?) WHERE Username = (?)", (secret, username))
                c.execute("UPDATE secure_login SET SessionStartTime = (?) WHERE Username = (?)", (session_start_time, username))
                conn.commit()
                c.close()

                response.set_cookie("username", username, secret=secret)
                response.status = 303
                response.set_header('Location', '/dashboard')
            else:
                abort(403, "Authentication failed.")
Example #10
0
def post_create_user():

    # This post script will create a new user in the database or modify an existing one.

    # Request the selections the user has made in the HTML form.
    submit_action = request.forms.getall('submit_btn')

    if 'create' in submit_action:
        # Get the user details from the registration form.
        new_username = request.forms.get('new_uname')
        new_password = request.forms.get('new_passwd')
        new_password_check = request.forms.get('new_passwd_check')

        # Some serverside checks on the user input for the required fields to protect the server from invalid input.
        if len(new_username) == 0:
            return template('create_user', url=url, config=config, notification='The username field is required.')
        if len(new_password) == 0:
            return template('create_user', url=url, config=config, notification='The password field is required.')
        if new_password != new_password_check:
            return template('create_user', url=url, config=config, notification='Password mismatch.')

        # Hash the password.
        hash = sha512_crypt.encrypt(new_password)

        # Generate unique session ID.
        session_start_time = str(datetime.datetime.now())
        secret = sha512_crypt.encrypt(session_start_time)

        # Connect to the database.
        conn = sqlite3.connect(config["paths"]["file_auth_database"])
        c = conn.cursor()

        # Save new user in the database.
        c.execute("INSERT INTO `secure_login`(`ID`,`Username`,`Password`) VALUES (?,?,?)", (None, new_username, hash))
        conn.commit()
        c.close()

        # Redirect.
        response.status = 303
        response.set_header('Location', '/users')

    else:
        # Redirect.
        response.status = 303
        response.set_header('Location', '/users')
Example #11
0
def post_page_users():

    # This post script will delete the selected users from the database on the users page.

    # Request the selections the user has made in the HTML form.
    form_data = request.forms.getall('chkBox')
    submit_action = request.forms.getall('submit_btn')

    # Check if the user has clicked the 'create' button. If so, show create_user template where the user can create new users.
    if 'create' in submit_action:
        response.status = 303
        response.set_header('Location', '/create_user')

    # If none of the above, the user wants to delete the selected rules.
    elif 'remove' in submit_action:
        # If the checkboxes are empty (no user input), do nothing.
        if len(form_data) == 0:
            response.status = 303
            response.set_header('Location', '/users')

        for item in form_data:
            conn = sqlite3.connect(config["paths"]["file_auth_database"])
            c = conn.cursor()
            c.execute("DELETE FROM secure_login WHERE ID = ?", (item,))
            conn.commit()
            c.close()

        # Redirect back to the same page.
        return template('users', url=url, config=config, notification='User deleted successfully.')

    else:
        response.status = 303
        response.set_header('Location', '/users')
Example #12
0
def post_page_rules():

    # This post function will create a new rule, modify a rule or remove a rule based on the user selection.

    # First request the selected checkboxes on the /rules page and the button that the user clicked.
    form_data = request.forms.getall('chkBox')
    submit_action = request.forms.getall('submit_btn')

    # Check if the user has clicked the 'create' button. If so, show create_rule template where the user can create new rules.
    if 'create' in submit_action:
        response.status = 303
        response.set_header('Location', '/create_rule')

    # Check if the user has clicked the 'modify' button. If so, show view_rule template where the user can modify rules.
    elif 'modify' in submit_action:
        # If the checkboxes are empty (no user input), do nothing.
        if len(form_data) == 0:
            response.status = 303
            response.set_header('Location', '/rules')
        else:
            return template('view_rule', url=url, config=config, form_data=form_data)

    # If none of the above, the user wants to delete the selected rules.
    elif 'remove' in submit_action:
        # If the checkboxes are empty (no user input), do nothing.
        if len(form_data) == 0:
            response.status = 303
            response.set_header('Location', '/rules')
        else:
            for item in form_data:
                os.remove(config["paths"]["dir_secmon_rules"] + item)
            return template('rules', url=url, config=config, notification='Remove succesfull.')

    # If none of the above, do nothing.
    else:
        response.status = 303
        response.set_header('Location', '/rules')
Example #13
0
def post_truncate_log():

    value = request.forms.get('log')

    # This post function will truncate the selected log file.
    if len(value) == 0:
        response.status = 303
        response.set_header('Location', '/logs')
    elif value == "bottle.log":
        full_path = config["paths"]["dir_webserver_log"] + value
        open(full_path,"w").close()
        response.status = 303
        response.set_header('Location', '/logs')
    else:
        full_path = config["paths"]["dir_secmon_core"] + value
        open(full_path,"w").close()
        response.status = 303
        response.set_header('Location', 'logs')
Example #14
0
def post_page_create_rule():

    # This post function will save the form data into a new rule .txt file, restart the secmon daemon and redirect the user.

    # Serverside checks for the required fields to protect the security monitor daemon from incorrect input from the user.
    if len(request.forms.get('rule_name')) == 0:
        return template('create_rule', url=url, config=config, notification='The rule name field is empty, this field is required.')
    if len(request.forms.get('rule_description')) == 0:
        return template('create_rule', url=url, config=config, notification='The rule description field is empty, this field is required.')
    if len(request.forms.get('count')) == 0:
        return template('create_rule', url=url, config=config, notification='The count field is empty, this field is required.')
    if len(request.forms.get('count_operator')) == 0:
        return template('create_rule', url=url, config=config, notification='The count operator field is empty, this field is required.')
    if len(request.forms.get('action')) == 0:
        return template('create_rule', url=url, config=config, notification='The action field is empty, this field is required.')
    if len(request.forms.get('log')) == 0:
        return template('create_rule', url=url, config=config, notification='The log field is empty, this field is required.')
    if len(request.forms.get('match')) == 0:
        return template('create_rule', url=url, config=config, notification='The match field is empty, this field is required.') 

    # If the user is performing an rule modification, there should be an existing rule that may or may not have changed by name.
    # If the rule name has changed, the rule will be recreated with the new name. This code will delete the old one.
    if request.forms.get('current_rulename') == None:
        pass
    elif request.forms.get('current_rulename') != request.forms.get('rule_name'): 
        os.remove(config["paths"]["dir_secmon_rules"] + request.forms.get('current_rulename') + '.txt')

    # Create new .txt rule file based on user input in the rule directory.
    new_rule_name = request.forms.get('rule_name')
    new_rule_name = config["paths"]["dir_secmon_rules"] + new_rule_name + '.txt'
    f = open(new_rule_name, "w")

    # These are the values that are submitted by the form.
    # rule_name
    # rule_description
    # source-ip-address
    # source-ip-port
    # target-ip-address
    # target-ip-port
    # protocol
    # count
    # count_operator
    # interval
    # action
    # log
    # message
    # match

    # Write the values line by line in secmon readable format.
    f.write("NAME = '" + request.forms.get('rule_name') + "'\n")
    f.write("DESCRIPTION = '" + request.forms.get('rule_description') + "'\n")
    if len(request.forms.get('source-ip-address')) != 0:
        f.write("SOURCEIP = " + request.forms.get('source-ip-address') + "\n")
    if len(request.forms.get('source-ip-port')) != 0:
        f.write("SOURCEPT = " + request.forms.get('source-ip-port') + "\n")
    if len(request.forms.get('target-ip-address')) != 0:
        f.write("TARGETIP = " + request.forms.get('target-ip-address') + "\n")
    if len(request.forms.get('target-ip-port')) != 0:
        f.write("TARGETPT = " + request.forms.get('target-ip-port') + "\n")
    if len(request.forms.get('protocol')) != 0:
        f.write("PROTOCOL = " + request.forms.get('protocol') + "\n")
    f.write("COUNT " + request.forms.get('count_operator') + " " + request.forms.get('count') + "\n")
    if len(request.forms.get('interval')) != 0:
        f.write("INTERVAL = " + request.forms.get('interval') + "\n")
    f.write("ACTION = '" + request.forms.get('action') + "'\n")
    f.write("LOG = " + request.forms.get('log') + "\n")
    if len(request.forms.get('message')) != 0:
        f.write("MESSAGE = " + request.forms.get('message') + "\n")
    f.write("MATCH = " + request.forms.get('match') + "\n")
    f.close()

    # Restart the security monitor daemon so it will use the new rule.
    daemon_running = os.path.isfile('/tmp/secmon.pid')
    if daemon_running:
        os.system('python2.7 ' + config["paths"]["dir_secmon_core"] + 'securitymonitor.py restart')

    # Redirect the user back to the rules page.
    response.status = 303
    response.set_header('Location', '/rules')