Exemple #1
0
def run(input_file):

    instructions = get_input(input_file)
    part_one(instructions)

    # Need to duplicate the instructions, because we've already chewed through the list evaluating
    # them in part one.
    instructions = get_input(input_file)
    part_two(instructions)
Exemple #2
0
def build_pages(id_):
    """Walk user through building multiple new page documents.

    :return a page object
    """
    pages = list()
    logging.info("Getting Page Metadata")

    # Looks through to get the number of pages as a number with error checking
    num_pages = get_number("    How many pages do you need?")

    for page_num in range(int(num_pages)):
        logging.info(f"Building Page {page_num + 1}")
        temp_page = Page()
        auto_forward = yes_no_prompt("    Will this page auto forward?")
        temp_page.capture_credentials = False
        temp_page.capture_passwords = False

        if auto_forward == "yes":
            setattr(temp_page, "name", f"{id_}-{page_num+1}-AutoForward")
            temp_page.html = AUTO_FORWARD
            temp_page.redirect_url = get_input("    URL to Redirect to:")

        else:
            temp_page.name = f"{id_}-{page_num+1}-Landing"
            forward = yes_no_prompt("    Will this page forward after action? (yes/no)")
            if forward == "yes":
                temp_page.redirect_url = get_input("    URL to Redirect to:")

            # Receives the file name and checks if it exists.
            while True:
                try:
                    landing_file_name = get_input("Landing Page File name:")
                    # Drops .html if included so it can always be added as fail safe.
                    landing_file_name = landing_file_name.split(".", 1)[0]

                    with open(landing_file_name + ".html") as landingFile:
                        temp_page.html = landingFile.read()

                    break
                except EnvironmentError:
                    logging.critical(
                        f"ERROR- Landing Page File not found: {landing_file_name}.html"
                    )
                    print("Please try again...")

        # Debug page information
        logging.debug(f"Page Name: {temp_page.name}")
        logging.debug(f"Redirect ULR: {temp_page.redirect_url}")
        logging.debug(f"Capture Credentials: {temp_page.capture_credentials}")
        logging.debug(f"Capture Passwords: {temp_page.capture_passwords}")

        temp_page = review_page(temp_page)
        pages.append(temp_page)

    return pages
Exemple #3
0
def run(input_file):

    fish = [int(x) for x in get_input(input_file)[0].split(',')]

    # Copy the fish for part one (slow) because the list is modified while simulating
    part_one_slow([f for f in fish])
    part_one_fast(fish)
    part_two(fish)
Exemple #4
0
def target_add_label(labels, email, target):
    """Add a label to a target."""
    if labels == "yes" and not email[3]:
        logging.error("Missing Label for {}".format(target.email))
        target.position = get_input("Please enter a label:")
    else:
        target.position = email[3]
    return target
Exemple #5
0
def build_assessment(assessment_id):
    """Walk user through building a new assessment document.

    :return an assessment object
    """
    logging.info("Building Assessment")
    # Initializes assessment object with ID and timezone
    assessment = Assessment(id=assessment_id, timezone=set_time_zone())

    # Uses prompt to set Assessment and target domains while not allowing blank input
    assessment.domain = get_input(
        "    Assessment Domain (subdomain.domain.tld):")
    assessment.target_domains = (get_input(
        "    Targeted domain(s) separated by spaces:").lower().split(" "))

    # Uses functions to build out aspects of assessment.
    assessment.pages = build_pages(assessment.id)
    assessment.groups = build_groups(assessment.id, assessment.target_domains)

    template_smtp = SMTP()
    template_smtp.name = assessment.id + "-SP"

    # Sets up smtp host info to be pre-populated.
    template_smtp.host = prompt("Enter SMTP Host: ",
                                default=template_smtp.host,
                                validator=BlankInputValidator())

    # Bandit complains about the input() function, but it is safe to
    # use in Python 3, which is required by this project.
    template_smtp.username = input("SMTP User: "******"SMTP Password: "******"Building Campaigns")
    num_campaigns = get_number("    How many Campaigns?")
    for campaign_number in range(0, num_campaigns):
        campaign_data = build_campaigns(assessment, campaign_number + 1,
                                        template_smtp)
        assessment.campaigns.append(campaign_data)

        set_date("start_date", assessment, campaign_data.launch_date)
        set_date("end_date", assessment, campaign_data.complete_date)

    return assessment
Exemple #6
0
def run(input_file):

    lines = [line for line in get_input(input_file)]
    heightmap = list()
    for line in lines:
        line = list(line)
        heightmap.append([int(x) for x in line])

    part_one(heightmap)
    part_two(heightmap)
Exemple #7
0
def run(input_file):

    input_lines = get_input(input_file)
    earliest_time = int(input_lines[0])
    buses = [int(n) for n in input_lines[1].split(',') if n != 'x']

    part_one(earliest_time, buses)

    offset_buses = [(i, int(n))
                    for i, n in enumerate(input_lines[1].split(','))
                    if n != 'x']
    part_two(offset_buses)
Exemple #8
0
def main() -> None:
    """Set up logging, connect to API, call requested function(s)."""
    args: Dict[str, str] = docopt(__doc__, version=__version__)

    # Set up logging
    log_level = args["--log-level"]
    try:
        logging.basicConfig(
            format="\n%(levelname)s: %(message)s", level=log_level.upper()
        )
    except ValueError:
        logging.critical(
            '"%s" is not a valid logging level. Possible values are debug, info, warning, and error.',
            log_level,
        )
        sys.exit(1)

    # Connect to API
    try:
        api = connect_api(args["API_KEY"], args["SERVER"])
        logging.debug('Connected to: "%s"', args["SERVER"])
    except Exception as e:
        logging.critical(e.args[0])
        sys.exit(1)

    try:
        if args["--campaign"]:
            # Use campaign name to find campaign id.
            campaigns = get_campaigns(api)
            campaign_id = get_campaign_id(args["--campaign"], campaigns)
        else:
            # User inputs assessment id and selects campaign from lists.
            assessment_id = get_input("Enter the Assessment ID:")
            campaigns = get_campaigns(api, assessment_id)
            campaign_id = select_campaign(campaigns)

    except LookupError as err:
        logging.error(err)
        sys.exit(1)

    if args["--summary-only"]:
        # Output summary only.
        print_summary(api, campaign_id)
    else:
        # Complete and output summary.
        try:
            complete_campaign(args["API_KEY"], args["SERVER"], campaign_id)

        except UserWarning as err:
            logging.warning(err)
            sys.exit(1)

        print_summary(api, campaign_id)
Exemple #9
0
def run(input_file):

    connectors = [int(n) for n in get_input(input_file)]

    # The power supply is 0 jolts. Your device has a joltage rating 3 higher than the highest-rated
    # connector you have. Add 0 and max+3 to model the supply and device as connectors.
    connectors.append(0)
    connectors.append(max(connectors) + 3)

    connectors.sort()

    part_one(connectors)
    part_two(connectors)
Exemple #10
0
def create_email(assessment, campaign_number=""):
    """Create email."""
    temp_template = Template(name=assessment.id + "-T" + str(campaign_number))
    temp_smtp = SMTP(name=f"{assessment.id}-SP-{campaign_number}")

    # Receives the file name and checks if it exists.
    while True:
        try:
            html_file_name = get_input("HTML Template File name:")
            # Drops .html if included so it can always be added as fail safe.
            html_file_name = html_file_name.split(".", 1)[0]

            with open(html_file_name + ".html") as htmlFile:
                temp_template.html = htmlFile.read()

            break
        except EnvironmentError:
            logging.error(
                f"HTML Template File not found: {html_file_name}.html")
            print("Please try again...")

        # Receives the file name and checks if it exists.
    while True:
        try:
            text_file_name = get_input("    Text Template File name:")
            # Drops .txt if included so it can always be added as fail safe.
            text_file_name = text_file_name.split(".", 1)[0]

            with open(text_file_name + ".txt") as textFile:
                temp_template.text = textFile.read()

            break
        except EnvironmentError:
            logging.critical(
                "Text Template File not found: {}.txt".format(text_file_name))
            print("Please try again...")

    return temp_smtp, temp_template
Exemple #11
0
def run(input_file):

    potential_triangles = list()
    for line in get_input(input_file):
        s1, s2, s3 = int(line[:3]), int(line[3:8]), int(line[8:])
        potential_triangles.append((s1, s2, s3))

    part_one(potential_triangles)

    potential_triangles = list()
    tri1, tri2, tri3 = list(), list(), list()
    for line in get_input(input_file):
        s1, s2, s3 = int(line[:3]), int(line[3:8]), int(line[8:])
        tri1.append(s1)
        tri2.append(s2)
        tri3.append(s3)
        if len(tri1) == 3:
            potential_triangles.append(tri1)
            potential_triangles.append(tri2)
            potential_triangles.append(tri3)
            tri1, tri2, tri3 = list(), list(), list()

    part_two(potential_triangles)
def add_group(api, assessment_id):
    """Create a test group."""
    logging.info("Adding Test Group")

    newGroup = Group()

    newGroup.name = "Test-" + assessment_id

    # Holds list of Users to be added to group.
    targets = list()

    target = User()
    target.first_name = get_input("Enter First Name: ")
    # Receives the file name and checks if it exists.
    while target.first_name != "done" or target.first_name == "":

        target.last_name = get_input("Enter Last Name: ")

        while True:
            target.email = get_input("Enter Email: ")
            if not validate_email(target.email):
                print("In Valid Email")
            else:
                break

        target.position = get_input("Enter Org: ")

        targets.append(target)

        target = User()
        target.first_name = get_input("Enter First Name or 'done': ")

    newGroup.targets = targets

    newGroup = api.groups.post(newGroup)

    return newGroup.name
Exemple #13
0
def import_email(assessment, campaign_number, template_smtp):
    """Import email from file."""
    temp_template = Template(name=f"{assessment.id}-T{str(campaign_number)}")
    temp_smtp = copy.deepcopy(template_smtp)
    temp_smtp.name = f"{assessment.id}-SP-{campaign_number}"

    # Receives the file name and checks if it exists.
    while True:
        try:
            import_file_name = get_input("    Import File name?")
            # Drops .json if included so it can always be added as fail safe.
            import_file_name = import_file_name.split(".", 1)[0]

            with open(import_file_name + ".json") as importFile:
                import_temp = json.load(importFile)

            # Validates that all fields are present or raise MissingKey Error.
            email_import_validation(import_temp)
            break
        except EnvironmentError:
            logging.critical(
                "Import File not found: {}.json".format(import_file_name))
            print("Please try again...")

        except MissingKey as e:
            # Logs and indicates the user should correct before clicking ok which will re-run the import.
            logging.critical("Missing Field from import: {}".format(e.key))
            message_dialog(
                title="Missing Field",
                text=
                f'Email import is missing the "{e.key}" field, please correct before clicking Ok.\n {e.key}: {e.description}',
            )

            continue

    # Finalize SMTP profile, push to GoPhish for check.
    # TODO Need to valid this formatting.
    temp_smtp.from_address = import_temp["from_address"]

    # Load
    temp_template.subject = import_temp["subject"]
    temp_template.html = import_temp["html"]
    temp_template.text = import_temp["text"]
    temp_template.name = f"{assessment.id}-T{str(campaign_number)}-{import_temp['id']}"

    return temp_smtp, temp_template
Exemple #14
0
def run(input_file):

    raw = get_input(input_file)
    line_points = list()

    for line in raw:
        a, b = line.split(' -> ')

        ax, ay = a.split(',')
        point_a = Point(x=int(ax), y=int(ay))

        bx, by = b.split(',')
        point_b = Point(x=int(bx), y=int(by))

        line_points.append((point_a, point_b))

    part_one(line_points)
    part_two(line_points)
Exemple #15
0
def run(input_file):

    lines = get_input(input_file)

    bingo_numbers = [int(x) for x in lines[0].split(',')]

    boards = list()
    boards_workspace = [line for line in lines[1:] if line]

    while True:
        new_board = list()
        for line in boards_workspace[0:5]:
            row = [int(y) for y in line.split(' ') if y]
            new_board.append(row)
        boards.append(new_board)

        boards_workspace = boards_workspace[5:]
        if not boards_workspace:
            break

    part_one(bingo_numbers, boards)
    part_two(bingo_numbers, boards)
Exemple #16
0
def build_emails(domains, labels):
    """Build emails."""
    # Holds list of Users to be added to group.
    targets = list()
    domain_miss_match = list()
    format_error = list()

    # Receives the file name and checks if it exists.
    while True:
        try:
            email_file_name = get_input("    E-mail CSV name:")
            # Drops .csv if included so it can always be added as fail safe.
            email_file_name = email_file_name.split(".", 1)[0]

            with open(email_file_name + ".csv") as csv_file:
                read_csv = csv.reader(csv_file, delimiter=",")
                next(read_csv)

                for row in read_csv:
                    # Checks e-mail format, if false prints message.
                    if not validate_email(row[2]):
                        format_error.append(row)
                    # Checks that the domain matches, if false prints message,
                    elif not validate_domain(row[2], domains):
                        domain_miss_match.append(row)

                    else:
                        target = Target(first_name=row[0],
                                        last_name=row[1],
                                        email=row[2])
                        target = target_add_label(labels, row, target)
                        targets.append(target)

                # Works through emails found to include formatting errors.
                print("\n")
                if len(format_error) < 2:
                    for email in format_error:
                        email[2] = prompt(
                            "Correct Email Formatting: ",
                            default=email[2],
                            validator=EmailValidator(),
                        )
                        if not validate_domain(email[2], domains):
                            domain_miss_match.append(email)
                        else:
                            target = Target(first_name=email[0],
                                            last_name=email[1],
                                            email=email[2])
                            target = target_add_label(labels, email, target)
                            targets.append(target)
                else:
                    logging.error("{} Formatting Errors".format(
                        len(format_error)))
                    if yes_no_prompt(
                            "Would you like to correct each here") == "yes":
                        for email in format_error:
                            email[2] = prompt(
                                "Correct Email Formatting: ",
                                default=email[2],
                                validator=EmailValidator(),
                            )
                            if not validate_domain(email[2], domains):
                                domain_miss_match.append(email)
                            else:
                                target = Target(first_name=row[0],
                                                last_name=row[1],
                                                email=row[2])
                                target = target_add_label(
                                    labels, email, target)
                                targets.append(target)
                    else:
                        logging.warning(
                            "Incorrectly formatted Emails will not be added, continuing..."
                        )

                # Works through emails found to have domain miss match.
                if len(domain_miss_match) < 2:
                    for email in domain_miss_match:
                        email[2] = prompt(
                            "Correct Email Domain: ",
                            default=email[2],
                            validator=EmailValidator(),
                        )
                else:
                    logging.error("{} Domain Miss Match Errors".format(
                        len(format_error)))
                    if yes_no_prompt(
                            "Would you like to correct each here") == "yes":
                        for email in domain_miss_match:
                            while True:
                                email[2] = prompt(
                                    "Correct Email Domain: ",
                                    default=email[2],
                                    validator=EmailValidator(),
                                )
                                if validate_domain(email[2], domains):
                                    target = Target(
                                        first_name=row[0],
                                        last_name=row[1],
                                        email=row[2],
                                    )
                                    target = target_add_label(
                                        labels, email, target)
                                    targets.append(target)
                                    break
                    else:
                        logging.warning(
                            "Incorrectly formatted Emails will not be added, continuing..."
                        )

            if len(targets) == 0:
                raise Exception("No targets loaded")
            break
        except EnvironmentError:
            logging.critical(
                "Email File not found: {}.csv".format(email_file_name))
            print("\t Please try again...")
        except Exception:
            # Logs and indicates the user should correct before clicking ok which will re-run the import.
            logging.critical("No targets loaded")
            message_dialog(
                title="Missing Targets",
                text=
                "No targets loaded from file, please check file before clicking Ok.",
            )
            continue

    return targets
Exemple #17
0
def run(input_file):

    document = loads(get_input(input_file)[0])

    part_one(document)
    part_two(document)
Exemple #18
0
def run(input_file):

    messages = get_input(input_file)

    part_one(messages)
    part_two(messages)
Exemple #19
0
def run(input_file):

    packages = [int(line) for line in get_input(input_file)]

    part_one(packages, 3)
    part_two(packages, 4)
Exemple #20
0
def run(input_file):

    encrypted_rooms = get_input(input_file)

    part_one(encrypted_rooms)
    part_two(encrypted_rooms)
Exemple #21
0
def run(input_file):

    entries = get_input(input_file)

    part_one(entries)
    part_two(entries)
Exemple #22
0
def run(input_file):

    part_one(get_input(input_file))
    part_two(get_input(input_file))
Exemple #23
0
def run(input_file):

    directions = get_input(input_file)[0]

    part_one(directions)
    part_two(directions)
Exemple #24
0
def run(input_file):

    key = get_input(input_file)[0]

    part_one(key)
    part_two(key)
Exemple #25
0
def run(input_file):

    floor_instructions = get_input(input_file)[0]

    part_one(floor_instructions)
    part_two(floor_instructions)
Exemple #26
0
def run(input_file):

    door_id = get_input(input_file)[0]

    part_one(door_id)
    part_two(door_id)
Exemple #27
0
def run(input_file):

    target_present_count = int(get_input(input_file)[0])

    part_one(target_present_count)
    part_two(target_present_count)
Exemple #28
0
def run(input_file):

    reactions, medicine_molecule = __parse(get_input(input_file))

    part_one(reactions, medicine_molecule)
    part_two(reactions, medicine_molecule)
Exemple #29
0
def run(input_file):

    instructions = get_input(input_file)

    part_one(instructions)
    part_two(instructions)
Exemple #30
0
def run(input_file):

    crabs = [int(x) for x in get_input(input_file)[0].split(',')]

    part_one(crabs)
    part_two(crabs)