def ctr_auth(
    host=env.THREATRESPONSE.get("host"),
    client_id=env.CTR_CLIENT_ID,
    api_key=env.CTR_API_KEY,
):
    print(white("\n==> Authenticating to Cisco Threat Response..."))
    url = f"https://{host}/iroh/oauth2/token"

    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'application/json'
    }
    # MISSION12: Construct payload to pass in authentication request to Threat Response
    env.print_missing_mission_warn(
        env.get_line())  # Delete this line when mission is complete.
    payload = {'MISSION12': 'MISSION12'}

    response = requests.post(url,
                             headers=headers,
                             auth=(client_id, api_key),
                             data=payload)
    response.raise_for_status()

    access_token = response.json()["access_token"]

    return access_token
def get_amp_computers(
    host=env.AMP.get("host"),
    client_id=env.AMP_CLIENT_ID,
    api_key=env.AMP_API_KEY,
):
    """Get a list of computers from Cisco AMP."""
    print("\n==> Getting computers from AMP")
    # MISSION02: Construct the URL
    env.print_missing_mission_warn(
        env.get_line())  # Delete this line when mission is complete.
    url = f"https://MISSION02"

    response = requests.get(url, verify=False)
    # Consider any status other than 2xx an error
    response.raise_for_status()

    computer_list = response.json()["data"]

    return computer_list
def post_umbrella_events(
        blocklist_domains,
        host=env.UMBRELLA.get("en_url"),
        api_key=env.UMBRELLA_ENFORCEMENT_KEY,
):
    print(
        white(
            f"\n==> Post malware events to the Umbrella Enforcement API for processing and optionally adding to a customer's domain lists."
        ))
    # MISSION11: Construct the API endpoint to post malware events to the Umbrella Enforcement API
    env.print_missing_mission_warn(
        env.get_line())  # Delete this line when mission is complete.
    url = f"MISSION11"

    headers = {
        'Content-type': 'application/json',
        'Accept': 'application/json'
    }

    # Time for AlertTime and EventTime when domains are added to Umbrella
    time = datetime.now().isoformat()
    data = []

    for domain in blocklist_domains:
        obj = {
            "alertTime": time + "Z",
            "deviceId": "ba6a59f4-e692-4724-ba36-c28132c761de",
            "deviceVersion": "13.7a",
            "dstDomain": domain,
            "dstUrl": "http://" + domain + "/",
            "eventTime": time + "Z",
            "protocolVersion": "1.0a",
            "providerName": "Security Platform"
        }
        data.append(obj)

    response = requests.post(url, data=json.dumps(data), headers=headers)
    response.raise_for_status()

    id = response.json()["id"]

    return id, data
def threatgrid_search_submissions(
        sha256,
        host=env.THREATGRID.get("host"),
        api_key=env.THREATGRID_API_KEY,
):
    """Search TreatGrid Submissions, by sha256.
    Args:
        sha256(str): Lookup this hash in ThreatGrid Submissions.
        host(str): The ThreatGrid host.
        api_key(str): Your ThreatGrid API key.
    """
    print(
        white(
            f"\n==> Searching the ThreatGrid Submissions for sha256: {sha256}")
    )

    query_parameters = {
        "q": sha256,
        "api_key": api_key,
        "after": "2019-12-01T05:00:00.000Z"
    }

    response = requests.get(
        f"https://{host}/api/v2/search/submissions",
        params=query_parameters,
    )
    # MISSION06: Put proper function to consider any status other than 2xx an error
    env.print_missing_mission_warn(
        env.get_line())  # Delete this line when mission is complete.
    # Put your code here: MISSION06

    submission_info = response.json()["data"]["items"]

    if submission_info:
        print(green("Successfully retrieved data on the sha256 submission"))
    else:
        print(red("Unable to retrieve data on the sha256 submission"))
        sys.exit(1)

    return submission_info
def get_umbrella_domain_status(
        domain,
        host=env.UMBRELLA.get("inv_url"),
        api_key=env.UMBRELLA_INVESTIGATE_KEY,
):
    print(
        white(
            f"\n==> Checking domain against Umbrella Investigate to retrieve its status"
        ))

    url = f"https://{host}/domains/categorization/{domain}?showLabels"

    # MISSION09: Construct authentication headers for Umbrella Investigate
    env.print_missing_mission_warn(
        env.get_line())  # Delete this line when mission is complete.
    headers = {'MISSION09': 'MISSION09'}

    response = requests.get(url, headers=headers)
    response.raise_for_status()

    domain_status = response.json()[domain]["status"]

    return domain_status
    amp_computer_list = get_amp_computers()

    print(green(f"Fetched AMP4E Computer List"))

    for computer in amp_computer_list:
        if computer["hostname"] == amp_computer_name:
            amp_computer_guid = computer["connector_guid"]

    print(
        green(
            f"AMP4E Computer name: {amp_computer_name}, GUID: {amp_computer_guid}"
        ))

    # MISSION03: Complete the AMP query with correct event types to fetch event list
    env.print_missing_mission_warn(
        env.get_line())  # Delete this line when mission is complete.
    amp_query_params = f"connector_guid[]={amp_computer_guid}&MISSIONO3"

    amp_event_list = get_amp_events(query_params=amp_query_params)

    print(green(f"Retrieved {len(amp_event_list)} events from AMP"))

    amp_event = amp_event_list[0]

    print(
        green(f"First Event: {amp_event['event_type']} \
             \nDetection: {amp_event['detection']} \
             \nFile name: {amp_event['file']['file_name']} \
             \nFile sha256: {amp_event['file']['identity']['sha256']}"))

    threatgrid_sha = amp_event["file"]["identity"]["sha256"]