Beispiel #1
0
def main(update, user, tele_config, tele_config_uniformly, settings):
    chat_id_list = [user["chat_id"]]

    if user["delete_mode"] == True:
        if update["message"]["text"] == "Ja":
            print("User wants to delete his classes.")
            classes_before = user["classes"]  # The classes before the deletion

            user["delete_mode"] = False
            print(f"Delete mode was disabled for {user['user_id']}")
            user["classes"] = []
            print(f"The classes {', '.join(classes_before)} for {user['user_id']} were successfully deleted.")

            successfully_deleted = open(settings["messages"]["delete_mode_successful"]).readlines()[0]

            keyboardmarkup = json.load(open(settings["messages"]["main_keyboardmarkup"]))
            telegram.send_msg_keyboard_markup(
                tele_config, tele_config_uniformly, chat_id_list, successfully_deleted, keyboardmarkup
            )
            print("Sent deletion successful message and reactivated the main keyboard markup.")
            return
        else:
            print("User wants to keep his classes")
            user["delete_mode"] = False
            print(f"Delete mode was disabled for {user['user_id']}")

            not_deleted = open(settings["messages"]["delete_mode_unsuccessful"]).readlines()[0]

            keyboardmarkup = json.load(open(settings["messages"]["main_keyboardmarkup"]))
            telegram.send_msg_keyboard_markup(
                tele_config, tele_config_uniformly, chat_id_list, not_deleted, keyboardmarkup
            )
            print("Sent deletion unsuccessful message and reactivated the main keyboard markup.")
            return

    else:
        if user["classes"]:
            user["delete_mode"] = True
            print(f"Enabled delete_mode for user {user['user_id']}")

            delete_text = open(settings["messages"]["delete"]).read()
            delete_text = delete_text.format(", ".join(user["classes"]))

            keyboardmarkup = json.load(open(settings["messages"]["delete_keyboard_markup"]))

            telegram.send_msg_keyboard_markup(
                tele_config, tele_config_uniformly, chat_id_list, delete_text, keyboardmarkup
            )
            print("Sent delete validation message.")
            return

        elif not user["classes"]:
            no_classes_to_delete = open(settings["messages"]["no_classes_to_delete"]).read()
            telegram.send_message(tele_config, tele_config_uniformly, chat_id_list, no_classes_to_delete)
            print(f"Sent no-classes-to-delete message to user {user['user_id']}")
            return
Beispiel #2
0
def main(update, user, tele_config, tele_config_uniformly, settings):
    if not user["classes"]:
        classes_vertretung = "Keine"
    else:
        classes_vertretung = ", ".join(user["classes"])

    myinfo_text = open(settings["messages"]["myinfo"]).read().format(
        classes_vertretung, user["user_id"])
    chat_id_list = [user["chat_id"]]

    telegram.send_message(tele_config, tele_config_uniformly, chat_id_list,
                          myinfo_text)
    print("Send a user his information.")
Beispiel #3
0
def main(user, tele_config, tele_config_uniformly, settings):
    help_text = open(settings["messages"]["help"]).read()
    chat_id_list = [user["chat_id"]]

    telegram.send_message(tele_config, tele_config_uniformly, chat_id_list, help_text)
    print(f"Send help message to user {user['user_id']}.")
Beispiel #4
0
def main():
    vp_config, telegram_config, telegram_api, user_data = get_prerequisites(
        settings)

    # Get all recipients (single users and telegram groups)
    # For single users add them to own_selection and assign the chat id as key to the classes the user will get vertretung
    # Add all groups to the recipients["all"] list because they get vertretung for all classes
    recipients = {"all": [], "own_selection": []}

    for user in user_data["users"]:
        recipients["own_selection"].append({
            user_data["users"][user]["chat_id"]:
            user_data["users"][user]["classes"]
        })

    for group in telegram_config["group_chat_ids"].split(","):
        recipients["all"].append(group)

    stored_vp = utils.get_stored(
        settings=settings)  # Last local stored vertretungplan

    current_vp = poll_plan.get_recent(
        config=vp_config
    )  # Current vertretungsplan from the website of the FSG

    updated = check_updated.compare(stored_vp=stored_vp, current_vp=current_vp)

    if updated:
        print("Updated")

        utils.backup_vertretungsplan(
            settings=settings,
            to_save=current_vp)  # Save the vertretungsplan to backups
        # Find table and rows in that table

        print("Converting...")
        rows = convert_rows.get_rows(file=current_vp)

        # Remove line: Klasse | Fach...
        # Is added hard-coded later
        rows.pop(1)

        if recipients["all"]:
            # Just needs to be converted once because all recipients which will get all classes get all the same message
            # wclasses: wanted classes
            header, date = convert_header.parse_header(
                rows=rows,
                wclasses=["all"
                          ])  # Get back the header and the date from the page
            temp_rows = rows[
                1:]  # Remove the header row and only use this list temporary because can't pop first item because would
            # result into errors when using pop again for converting lines in own_selection
            body = convert_rows.convert_body(
                rows=temp_rows,
                wclasses=["all"])  # Convert the body and the footer

            # Merge the header and the body
            # If the body is empty a message will be inserted for the body which tells the user that there is not vertretung
            output = merge_lines.to_text(header, body, date, ["all"], settings)

            print(f"Sending message to {recipients['all']}.")
            telegram.send_message(config=telegram_config,
                                  telegram_api=telegram_api,
                                  chat_id_list=recipients["all"],
                                  message=output)

        for rcpt in recipients["own_selection"]:
            chat_id = list(rcpt.keys())[0]
            wclasses = rcpt[chat_id]

            header, date = convert_header.parse_header(
                rows=rows, wclasses=wclasses
            )  # Get back the header and the date from the page
            temp_rows = rows[1:]
            body = convert_rows.convert_body(
                rows=temp_rows,
                wclasses=wclasses)  # Convert the body and the footer

            # Merge the header and the body
            # If the body is empty a message will be inserted for the body which tells the user that there is not vertretung
            output = merge_lines.to_text(header, body, date, wclasses,
                                         settings)

            print(f"Sending message to {rcpt}.")
            telegram.send_message(config=telegram_config,
                                  telegram_api=telegram_api,
                                  chat_id_list=[chat_id],
                                  message=output)
    else:
        print("Not updated")
Beispiel #5
0
def main(update, user, tele_config, tele_config_uniformly, settings):
    chat_id_list = [user["chat_id"]]

    if user["setup_mode"] == True:
        validation_classes = utils.get_validate_classes(
            update["message"]["text"])
        successful_string = ", ".join(validation_classes["successful"])
        unsuccessful_string = ", ".join(validation_classes["unsuccessful"])

        if len(validation_classes["successful"]) > 0:
            if len(validation_classes["successful"]
                   ) == 1:  # Check for singular or plural
                correct_msg = open(settings["messages"]
                                   ["validation_successful"]).readlines()[0]
            elif len(validation_classes["successful"]) > 1:
                correct_msg = open(settings["messages"]
                                   ["validation_successful"]).readlines()[1]

            correct_msg = correct_msg.format(successful_string)

            for c in validation_classes[
                    "successful"]:  # Add successfully detected classes to user
                if not c in user["classes"]:
                    user["classes"].append(c)

            print(f"Added {successful_string} to user {user['user_id']}.")

            telegram.send_message(tele_config, tele_config_uniformly,
                                  chat_id_list, correct_msg)
            print("Send validation-successful message.")

            stpmde_deactivated_msg = open(
                settings["messages"]["setup_mode_finished"]).readlines()[
                    0]  # Setup mode deactivated message
            keyboardmarkup = json.load(
                open(settings["messages"]["main_keyboardmarkup"]))
            telegram.send_msg_keyboard_markup(tele_config,
                                              tele_config_uniformly,
                                              chat_id_list,
                                              stpmde_deactivated_msg,
                                              keyboardmarkup)
            print(
                "Send setup-mode-deactivated message and reactivated the main keyboard markup."
            )

        if len(validation_classes["unsuccessful"]) > 0:
            if len(validation_classes["unsuccessful"]
                   ) == 1:  # Check for singular or plural
                not_correct_msg = open(
                    settings["messages"]
                    ["validation_unsuccessful"]).readlines()[0]
            elif len(validation_classes["unsuccessful"]) > 1:
                not_correct_msg = open(
                    settings["messages"]
                    ["validation_unsuccessful"]).readlines()[1]

            print(
                f"Could not add {unsuccessful_string} for user {user['user_id']}."
            )
            not_correct_msg = not_correct_msg.format(unsuccessful_string)
            keyboardmarkup = json.load(
                open(settings["messages"]["main_keyboardmarkup"]))
            telegram.send_msg_keyboard_markup(tele_config,
                                              tele_config_uniformly,
                                              chat_id_list, not_correct_msg,
                                              keyboardmarkup)
            print("Send validation unsuccessful message.")

        user["setup_mode"] = False
        print(f"setup_mode deactivated for user {user['user_id']}")

    else:
        user["setup_mode"] = True
        print(f"setup_mode enabled for user {user['user_id']}")

        setup_text = open(settings["messages"]["setup"]).read()
        keyboardmarkup = False

        telegram.send_msg_keyboard_markup(tele_config, tele_config_uniformly,
                                          chat_id_list, setup_text,
                                          keyboardmarkup)
        print("Send setup info message.")
Beispiel #6
0
def main():
    # reset timer
    new_offset = datetime.datetime.now()
    current_offset = new_offset

    # *****************************************************
    # directory containing the script
    path = os.path.dirname(os.path.abspath(__file__))
    # parent folder
    parent = os.path.dirname(os.path.abspath(path))

    # Configuration file parameters
    file = parent + '/config/params.cfg'
    config = ConfigParser()
    config.read(file)

    # create firewall object
    global firewall
    firewall = modules.paloalto.PanOS(config.get('Firewall', 'fw_fqdn'),
                                      config.get('Firewall', 'username'),
                                      config.get('Firewall', 'password'))

    # get firewall key
    ret = firewall.keygen()
    if (ret['status'] != 0):
        print(ret['result'])
        msg = "Error in retrieving Firewall key: {}".format(ret['result'])
        #logger.error(msg)
        print(msg)
        exit(1)

    # create ClearPass object
    global cppm
    cppm = modules.aruba_clearpass.ClearPass(
        config.get('ClearPass', 'clearpass_fqdn'),
        config.get('OAuth2', 'grant_type'), config.get('OAuth2', 'client_id'),
        config.get('OAuth2', 'client_secret'),
        config.get('OAuth2', 'username'), config.get('OAuth2', 'password'))

    # get ClearPass token
    ret = cppm.get_access_token()
    if (ret['status'] != 0):
        msg = "Error in creating ClearPass access \
              token: {}".format(ret['result'])
        #logger.error(msg)
        print(msg)
        exit(1)

    # create Telegram bot object
    global telegram
    telegram = modules.telegram.Telegram(
        config.get("Telegram", "token"),
        json.loads(config.get("Telegram", "whitelist")))
    # *****************************************************

    try:
        while True:
            ret = firewall.get_threat_log()
            if (ret['status'] != 0):
                sleep(10)
                continue

            #print(ret['result'])
            root = ET.fromstring(ret['result'])
            #print(root.find('./result/log/logs/entry/src').text)
            print('[Threat Log]')
            compromized_addr = []
            for entry in root.findall('./result/log/logs/entry'):

                # check for new high severity threat log
                if (entry.find('severity').text == 'high'):

                    log_time = datetime.datetime.strptime(
                        entry.find('receive_time').text, '%Y/%m/%d %H:%M:%S')

                    print(entry.text)

                    # check if the newer log is newer than the offset
                    if (log_time > new_offset):
                        new_offset = log_time

                    #print('new offset:', new_offset)
                    #print('current offset:', current_offset)

                    # if the received log are older than the offset
                    # exit internal loop
                    if (log_time <= current_offset):
                        break
                    '''
                    print('|--------------------------------------|')
                    print('Severity:', entry.find('severity').text)
                    print('Receive Time:', entry.find('receive_time').text)
                    print('Source Address:', entry.find('src').text)
                    print('Destination Address:', entry.find('dst').text)
                    '''

                    msg = '|--------------------------------------|\n'
                    msg += 'Severity: {}\n'.format(entry.find('severity').text)
                    msg += 'Receive Time: {}\n'.format(
                        entry.find('receive_time').text)
                    msg += 'Source Address: {}\n'.format(
                        entry.find('src').text)
                    msg += 'Destination Address: {}\n'.format(
                        entry.find('dst').text)

                    print(msg)
                    src_addr = entry.find('src').text
                    if src_addr not in compromized_addr:
                        compromized_addr.append(src_addr)
                    print("Lista ip compromessi:")
                    pprint(compromized_addr)
                    telegram.send_message('596368574',
                                          msg)  # ID Telegram Marco

            for addr in compromized_addr:
                session_id, mac_addr = get_session_and_mac_from_ip(addr)
                if (session_id == None):
                    print('Unable to find session')
                    continue
                print('Session id: {}\nMac Address: {}'.format(
                    session_id, mac_addr))
                ret = mark_compromised(mac_addr)
                if (ret != 0):
                    print('Unable to mark the endpoint')
                    continue
                ret = disconnect_session(session_id)

            current_offset = new_offset
            sleep(10)

    except KeyboardInterrupt:
        print('Application closed by user')
    print('\nBye!')