Skip to content

Commit

Permalink
Created initial script to generate phish report.
Browse files Browse the repository at this point in the history
Added main(), get_json_file(), and parse_json().
  • Loading branch information
JCantu248 committed Jun 21, 2023
1 parent 7e198b9 commit 857603d
Show file tree
Hide file tree
Showing 6 changed files with 152 additions and 1 deletion.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,6 @@ __pycache__
.python-version
*.egg-info
dist
*.log
*.pdf
*.json
2 changes: 1 addition & 1 deletion bump_version.sh
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ set -o nounset
set -o errexit
set -o pipefail

VERSION_FILE=src/example/_version.py
VERSION_FILE=src/_version.py

HELP_INFORMATION="bump_version.sh (show|major|minor|patch|prerelease|build|finalize)"

Expand Down
3 changes: 3 additions & 0 deletions src/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
"""The rpt_phish_report library."""

LOGGING_FILE = "rpt_phish_report_logging.log"
5 changes: 5 additions & 0 deletions src/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
"""Code to run if this package is used as a Python module."""

from .phish_report_generator import main

main()
2 changes: 2 additions & 0 deletions src/_version.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
"""This file defines the version of this module."""
__version__ = "0.0.1"
138 changes: 138 additions & 0 deletions src/phish_report_generator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
"""cisagov/rpt-phish-report: A tool for creating phishing reports to support RPT.
Usage:
rpt-phish-report REPORT_DATE OUTPUT_DIRECTORY [--log-level=LEVEL]
Options:
-h --help Show this message.
JSON_FILE_PATH Path to the JSON file to act as a data source.
REPORT_DATE Date of the report, format YYYY-MM-DD
OUTPUT_DIRECTORY The directory where the final PDF
reports should be saved.
-l --log-level=LEVEL If specified, then the log level will be set to
the specified value. Valid values are "debug", "info",
"warning", "error", and "critical". [default: info]
"""

# Standard Python Libraries
import logging
import os
import sys
from typing import Any, Dict

# Third-Party Libraries
import docopt
import json
#import pandas as pd
from schema import And, Schema, SchemaError, Use
#from xhtml2pdf import pisa

# cisagov Libraries

from ._version import __version__

LOGGER = logging.getLogger(__name__)
LOGGING_FILE = "phish_report_generator.log"

def get_json_file(phish_result_json):
"""Open JSON file and load data."""
try:
f = open(phish_result_json)
LOGGER.info("Loading JSON data from %s", phish_result_json)
data = json.load(f)
f.close()
return data
except Exception as e:
LOGGER.error("Failure to open JSON file: %s", str(e))

def parse_json(data):
"""Parse JSON object for values to report."""
report_data = {}
try:
if data:
for payload in data['payloads']:
if payload["border_protection"] is 'N':
border_protection = "Not blocked"
elif payload["border_protection"] is 'B':
border_protection = "Blocked"
else:
raise ValueError("border_protection value must be either B or N")

if payload["host_protection"] is 'N':
host_protection = "Not blocked"
elif payload["host_protection"] is 'B':
host_protection = "Blocked"
else:
raise ValueError("host_protection value must be either B or N")

report_data.append({
"payload_description": payload["payload_description"],
"c2_protocol": payload["c2_protocol"],
"border_protection": border_protection,
"host_protection": host_protection
})
return report_data
except Exception as e:
LOGGER.error("Error parsing JSON: %s", str(e))


def generate_reports(datestring, output_directory, json_file_path):
"""Process steps for generating report data."""
data = get_json_file(json_file_path)
report_data = parse_json(data)



def main():
"""Generate PDF reports."""
args: Dict[str, str] = docopt.docopt(__doc__, version=__version__)

# Validate and convert arguments as needed
schema: Schema = Schema(
{
"--log-level": And(
str,
Use(str.lower),
lambda n: n in ("debug", "info", "warning", "error", "critical"),
error="Possible values for --log-level are "
+ "debug, info, warning, error, and critical.",
),
str: object, # Don't care about other keys, if any
}
)

try:
validated_args: Dict[str, Any] = schema.validate(args)
except SchemaError as err:
# Exit because one or more of the arguments were invalid
print(err, file=sys.stderr)
sys.exit(1)

# Assign validated arguments to variables
log_level: str = validated_args["--log-level"]

# Setup logging to central file
logging.basicConfig(
filename=LOGGING_FILE,
filemode="a",
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
datefmt="%m/%d/%Y %I:%M:%S",
level=log_level.upper(),
)

LOGGER.info("Loading RPT Phish Report, Version : %s", __version__)

# Create output directory
if not os.path.exists(validated_args["OUTPUT_DIRECTORY"]):
os.mkdir(validated_args["OUTPUT_DIRECTORY"])

# Generate reports
generated_reports = generate_reports(
validated_args["REPORT_DATE"],
validated_args["OUTPUT_DIRECTORY"],
validated_args["JSON_FILE_PATH"],

)

LOGGER.info("%s reports generated", generated_reports)

# Stop logging and clean up
logging.shutdown()

0 comments on commit 857603d

Please sign in to comment.