plumhound 1.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
PlumHound.py ADDED
@@ -0,0 +1,65 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf8 -*-
3
+
4
+ # PlumHound https://github.com/PlumHound/PlumHound | https://plumhound.defensiveorigins.com/
5
+ # BloodHoundAD Wrapper for Purple Teams | https://github.com/BloodHoundAD/BloodHound
6
+ # BloodHound CE (Newest version) can also be used | https://github.com/SpecterOps/BloodHound
7
+
8
+ # GNU GPL 3.0
9
+
10
+ import sys
11
+ import traceback
12
+
13
+ # Import PlumHound libraries
14
+ import lib.phCheckPython
15
+ import lib.phCLImanagement
16
+ import lib.phNotifyArgs
17
+ import lib.phTasks
18
+ import lib.phDatabase
19
+
20
+ ph_version = "1.6"
21
+
22
+
23
+ def main() -> int:
24
+ """
25
+ Main entry point for PlumHound CLI. Returns an exit code (0 success, non-zero error).
26
+ This function is referenced by the pyproject entry point: PlumHound:main
27
+ """
28
+ try:
29
+ # Check if Py2 environment. If not executing in Python3, exit nicely.
30
+ lib.phCheckPython.CheckPython2()
31
+
32
+ # Commandline Arguments (ArgParse) configuration
33
+ phArgs = lib.phCLImanagement.SetupArguments(ph_version)
34
+
35
+ # Check if Py3 environment. If not expected version of 3, notify nicely
36
+ lib.phCheckPython.CheckPython3(phArgs)
37
+
38
+ # Report execution parameters
39
+ lib.phNotifyArgs.NotifyArgs(phArgs, ph_version)
40
+
41
+ # Generate TaskList (jobs)
42
+ phTaskList = lib.phTasks.MakeTaskList(phArgs)
43
+
44
+ # Setup Driver (excluding BlueHound)
45
+ phDriver = lib.phDatabase.setup_database_conn(phArgs)
46
+
47
+ # Execute Jobs in Task List
48
+ lib.phTasks.TaskExecution(phTaskList, phDriver, phArgs)
49
+
50
+ # Close the neoj4 connection.
51
+ lib.phDatabase.close_database_con(phArgs, phDriver)
52
+
53
+ return 0
54
+ except SystemExit:
55
+ # Let argparse or other code call sys.exit() behave normally
56
+ raise
57
+ except Exception:
58
+ # Print traceback for visibility when used as a console command
59
+ traceback.print_exc()
60
+ return 1
61
+
62
+
63
+ if __name__ == "__main__":
64
+ sys.exit(main())
65
+
lib/__init__.py ADDED
File without changes
lib/phCLImanagement.py ADDED
@@ -0,0 +1,47 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf8 -*-
3
+ # PlumHound (phCLIManagement.py) - Management of Command Line Arguments
4
+ # https://github.com/PlumHound/PlumHound
5
+ # License GNU GPL3
6
+
7
+ # Import Python Modules
8
+ import argcomplete
9
+ import argparse
10
+
11
+ def SetupArguments(ph_version):
12
+ parser = argparse.ArgumentParser(description="BloodHound Wrapper for Blue/Purple Teams "+str(ph_version), add_help=True, epilog="For more information see https://github.com/plumhound")
13
+ argcomplete.autocomplete(parser)
14
+
15
+ pgroupc = parser.add_argument_group('DATABASE')
16
+ pgroupc.add_argument("-s", "--server", type=str, help="Neo4J Server", default="bolt://localhost:7687")
17
+ pgroupc.add_argument("-u", "--username", default="neo4j", type=str, help="Neo4J Database Useranme")
18
+ pgroupc.add_argument("-p", "--password", default="neo4jneo4j", type=str, help="Neo4J Database Password")
19
+ pgroupc.add_argument("--UseEnc", default=False, dest="UseEnc", help="Use encryption when connecting.", action='store_true')
20
+ pgroupc.add_argument("--timeout", type=int, default="300", dest="timeout", help="Cypher Query Timeout **NOT FULLY IMPLEMENTED**")
21
+
22
+ pgroupx = parser.add_mutually_exclusive_group(required="True")
23
+ pgroupx.add_argument("--easy", help="Test Database Connection, Returns Domain Users to stdout", action='store_true')
24
+ pgroupx.add_argument("-x", "--TaskFile", dest="TaskFile", type=str, help="Specify a PlumHound TaskList File")
25
+ pgroupx.add_argument("-q", "--QuerySingle", dest="QuerySingle", type=str, help="Specify a Single Cypher Query")
26
+ pgroupx.add_argument("-bp", "--BusiestPath", dest="BusiestPath", nargs='+', default=False, type=str, help="Find the X Shortest Paths that give the most users a path to Domain Admins. Need to specified [short|all] for shortestpath and the number of results. Ex: PlumHound -cu all 3")
27
+ pgroupx.add_argument("-ap", "--AnalyzePath", dest="AnalyzePath", nargs='+', default=False, type=str, help="Analyze 'Attack Paths' between two nodes and find which path needs to be remediated to brake the path.")
28
+ pgroupx.add_argument("-az", "--AzPath", dest="AzPath", nargs='+', default=False, type=str, help="Analyze 'Attack Paths' between two nodes in Azure. Specify starting and ending nodes or use the built-in options to find paths to Global Administrator: [AZUser|AZGroup|AZApp|AZServicePrincipal|AZDevice]. ALL can be used to run all the built-in options at once.")
29
+
30
+ pgroupo = parser.add_argument_group('OUTPUT', "Output Options (For single cypher queries only. --These options are ignored when -x or --easy is specified.")
31
+ pgroupo.add_argument("-t", "--title", dest="title", default="Adhoc Query", type=str, help="Report Title for Single Query [HTML,CSV,Latex]")
32
+ pgroupo.add_argument("--of", "--OutFile", dest="OutFile", default="PlumHoundReport", type=str, help="Specify a Single Cypher Query")
33
+ pgroupo.add_argument("--op", "--OutPath", dest="path", default="reports//", type=str, help="Specify an Output Path for Reports")
34
+ pgroupo.add_argument("--ox", "--OutFormat", dest="OutFormat", default="STDOUT", type=str, help="Specify the type of output.", choices=['stdout', 'HTML', 'CSV', 'HTMLCSV'])
35
+
36
+ pgrouph = parser.add_argument_group('HTML', "Options for HTML Output (For single queries or TaskLists")
37
+ pgrouph.add_argument("--HTMLHeader", dest="HTMLHeader", type=str, default="template//head.html", help="HTML Header (file) of Report")
38
+ pgrouph.add_argument("--HTMLFooter", dest="HTMLFooter", type=str, default="template//tail.html", help="HTML Footer (file) of Report")
39
+ pgrouph.add_argument("--HTMLCSS", dest="HTMLCSS", type=str, default="template//html.css", help="Specify a CSS template for HTML Output")
40
+
41
+ pgroupv = parser.add_argument_group('VERBOSE', "Set verbosity")
42
+ pgroupv.add_argument("-v", "--verbose", type=int, default="100", help="Verbosity 0-1000, 0 = quiet, default=100, info=150, verbose=1000")
43
+
44
+ args = parser.parse_args()
45
+
46
+ return args
47
+
lib/phCheckPython.py ADDED
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf8 -*-
3
+ # PlumHound (phCheckPython.py) - Check for appropriate version of python
4
+ # https://github.com/PlumHound/PlumHound
5
+ # License GNU GPL3
6
+
7
+ import sys
8
+ from lib.phLoggy import Loggy as Loggy
9
+
10
+ def CheckPython2():
11
+ if sys.version_info < (3, 0, 0):
12
+ print(__file__ + ' requires Python 3, while Python ' + str(sys.version[0] + ' was detected. Terminating. '))
13
+ sys.exit(1)
14
+
15
+ def CheckPython3(phArgs):
16
+ if sys.hexversion > 0x3090000:
17
+ Loggy(phArgs.verbose,200, "Python Hex Version Identified:"+str(sys.hexversion))
18
+
lib/phDatabase.py ADDED
@@ -0,0 +1,34 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf8 -*-
3
+ # PlumHound (phDatabase.py) Database Connection Management
4
+ # https://github.com/PlumHound/PlumHound
5
+ # License GNU GPL3
6
+
7
+ from neo4j import GraphDatabase
8
+ from lib.phLoggy import Loggy as Loggy
9
+
10
+ # Setup Database Connection
11
+ def setup_database_conn(phArgs):
12
+ Loggy(phArgs.verbose,900, "------ENTER: SETUP_DATABASE_CONN-----")
13
+ Loggy(phArgs.verbose,200, "[!] Attempting to connect to your Neo4j project using {}:{} @ {} {}.".format(phArgs.username, "****", phArgs.server, "[ENCRYPTED]" if phArgs.UseEnc else "[UNECNCRYPTED]"))
14
+ try:
15
+ if phArgs.UseEnc:
16
+ Loggy(phArgs.verbose,200, " Using Neo4j encryption")
17
+ driver_connection = GraphDatabase.driver(phArgs.server, auth=(phArgs.username, phArgs.password), encrypted=True)
18
+ else:
19
+ Loggy(phArgs.verbose,200, " Not using Neo4j encryption")
20
+ driver_connection = GraphDatabase.driver(phArgs.server, auth=(phArgs.username, phArgs.password), encrypted=False)
21
+ Loggy(phArgs.verbose,200, "[+] Success!")
22
+ return driver_connection
23
+ except Exception:
24
+ Loggy(phArgs.verbose,100, "There was a problem. Check username, password, and server parameters.")
25
+ Loggy(phArgs.verbose,100, "[X] Database connection failed!")
26
+ exit()
27
+ Loggy(phArgs.verbose,900, "------EXIT: SETUP_DATABASE_CONN-----")
28
+
29
+ def close_database_con(phArgs,connectiondriver):
30
+ Loggy(phArgs.verbose,900, "------ENTER: CLOSE_DATABASE_CONN-----")
31
+ connectiondriver.close
32
+ Loggy(phArgs.verbose,200, "[+] Closed Database Connection!")
33
+ Loggy(phArgs.verbose,900, "------EXIT: CLOSE_DATABASE_CONN-----")
34
+ exit()
lib/phDeliver.py ADDED
@@ -0,0 +1,92 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf8 -*-
3
+ # PlumHound - Output Delivery and Parsing Functions(phdeliver.py)
4
+ # https://github.com/PlumHound/PlumHound
5
+ # License GNU GPL3
6
+
7
+ #Python Libraries
8
+ import ast
9
+ import csv
10
+ from tabulate import tabulate
11
+ from datetime import datetime
12
+
13
+ #Plumhound Modules
14
+ from lib.phLoggy import Loggy as Loggy
15
+
16
+ def SenditOut(verbose,list_KeysList, Processed_Results_List, OutFormat, OutFile, OutPath, Title, HTMLHeader, HTMLFooter, HTMLCSS, jobQuery):
17
+ Loggy(verbose,900, "------ENTER: SENDITOUT-----")
18
+ # Quick fix if keys returned no records to properly rebuild the keys list of 0, instead of int(0)
19
+ if isinstance(list_KeysList, int):
20
+ list_KeysList = []
21
+ output = ""
22
+
23
+ if OutFormat == "CSV":
24
+ Loggy(verbose,500, "Beginning Output CSV:" + OutPath + OutFile)
25
+ with open(OutPath + OutFile, "w", newline="", encoding="utf-8") as f:
26
+ Loggy(verbose,500, "KeyType: " + str(type(list_KeysList)))
27
+ Loggy(verbose,500, "KeyList: " + str((list_KeysList)))
28
+ writer = csv.writer(f)
29
+ ModKeyList = ast.literal_eval("[" + str(list_KeysList) + "]")
30
+ Loggy(verbose,500, "KeyTypeMod: " + str(type(ModKeyList)))
31
+ Loggy(verbose,500, "KeyListMod: " + str(ModKeyList))
32
+ writer.writerows(ModKeyList)
33
+ Loggy(verbose,500, "ResultsType: " + str(type(Processed_Results_List)))
34
+ Loggy(verbose,999, "ResultsList: " + str(Processed_Results_List))
35
+ writer.writerows(Processed_Results_List)
36
+ Loggy(verbose,150, "Task " + Title + " Complete: " + OutFile)
37
+ return True
38
+
39
+ if OutFormat == "HTMLCSV":
40
+ Loggy(verbose,500, "Beginning Output HTMLCSV:" + OutPath + OutFile)
41
+ SenditOut(verbose,list_KeysList, Processed_Results_List, "HTML", OutFile + ".html", OutPath, Title, HTMLHeader, HTMLFooter, HTMLCSS, jobQuery)
42
+ SenditOut(verbose,list_KeysList, Processed_Results_List, "CSV", OutFile + ".csv", OutPath, Title, HTMLHeader, HTMLFooter, HTMLCSS, jobQuery)
43
+ Loggy(verbose,500, "Completed Output HTMLCSV:" + OutPath + OutFile)
44
+ return True
45
+
46
+ if OutFormat == "STDOUT":
47
+ Loggy(verbose,500, "Beginning Standard Output:")
48
+ print()
49
+ output = tabulate(Processed_Results_List, list_KeysList, tablefmt="simple")
50
+ print(output)
51
+ print()
52
+ return True
53
+
54
+ if OutFormat == "HTML":
55
+ Loggy(verbose,500, "Beginning Output HTML:" + OutFile)
56
+ output = tabulate(Processed_Results_List, list_KeysList, tablefmt="html")
57
+ outputq = "<br><div style='width:50%; display:inline-block;'><tt><u>Cypher Query</u>:<br>"+jobQuery+"</tt></div>"
58
+ HTMLCSS_str = ""
59
+ HTMLHeader_str = ""
60
+ HTMLFooter_str = ""
61
+ HTMLPre_str = "<HTML><head>"
62
+ HTMLMId_str = "</head><Body>"
63
+ HTMLEnd_str = "</body></html>"
64
+ if HTMLHeader:
65
+ with open(HTMLHeader, 'r') as header:
66
+ HTMLHeader_str = header.read()
67
+ HTMLHeader_str = ReplaceHTMLReportVars(HTMLHeader_str, Title)
68
+
69
+ if HTMLFooter:
70
+ with open(HTMLFooter, 'r') as footer:
71
+ HTMLFooter_str = footer.read()
72
+ HTMLFooter_str = ReplaceHTMLReportVars(HTMLFooter_str, Title)
73
+
74
+ if HTMLCSS:
75
+ with open(HTMLCSS, 'r') as css:
76
+ HTMLCSS_str = "<style>\n" + css.read() + "\n</style>"
77
+
78
+ Loggy(verbose,500, "File Writing " + OutPath + OutFile)
79
+ output = HTMLPre_str + HTMLCSS_str + HTMLMId_str + HTMLHeader_str + output + outputq + HTMLFooter_str + HTMLEnd_str
80
+ fsys = open(OutPath + OutFile, "w")
81
+ fsys.write(output)
82
+ Loggy(verbose,150, "Task " + Title + " Complete: " + OutFile)
83
+ Loggy(verbose,500, "File Closing " + OutPath + OutFile)
84
+ fsys.close
85
+ return True
86
+ Loggy(verbose,900, "------EXIT: SENDITOUT-----")
87
+
88
+ def ReplaceHTMLReportVars(InputStr, Title):
89
+ now=datetime.now()
90
+ sOutPut = InputStr.replace("--------PH_TITLE-------", str(Title))
91
+ sOutPut = sOutPut.replace("--------PH_DATE-------", str(now.strftime("%Y-%m-%d %H:%M:%S")))
92
+ return sOutPut
lib/phLoggy.py ADDED
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf8 -*-
3
+ # PlumHound (phLoggy.py) - Logging Function
4
+ # https://github.com/PlumHound/PlumHound
5
+ # License GNU GPL3
6
+
7
+ # Loggy Function for lazy debugging
8
+
9
+ import datetime
10
+
11
+ def Loggy(hurdle, level, notice):
12
+ logfile="log/PlumHound.log"
13
+ if level <= hurdle:
14
+ if level <100:
15
+ print("" + "\t" + notice)
16
+ elif level == 100:
17
+ print("INFO" + "\t" + notice)
18
+ else:
19
+ print(str(level) + "\t" + notice)
20
+
21
+ fsys = open(logfile, "a", encoding="utf-8")
22
+ fsys.writelines(str(level) + "\t" + datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S") +"\t" + notice +"\n")
23
+ fsys.close
lib/phNotifyArgs.py ADDED
@@ -0,0 +1,53 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf8 -*-
3
+ # PlumHound (phNotifyArgs.py) - Check and Notify of CL arguments
4
+ # https://github.com/PlumHound/PlumHound
5
+ # License GNU GPL3
6
+
7
+ from lib.phLoggy import Loggy as Loggy
8
+
9
+ def NotifyArgs(phArgs, ph_version):
10
+ Loggy(phArgs.verbose,10, "")
11
+ Loggy(phArgs.verbose,10, "PlumHound " +str(ph_version))
12
+ Loggy(phArgs.verbose,10, "For more information: https://github.com/plumhound")
13
+ Loggy(phArgs.verbose,50, "--------------------------------------")
14
+ Loggy(phArgs.verbose,50, "Server: " + str(phArgs.server))
15
+ Loggy(phArgs.verbose,50, "User: " + str(phArgs.username))
16
+ Loggy(phArgs.verbose,50, "Password: *****")
17
+ if phArgs.UseEnc:
18
+ Loggy(phArgs.verbose,50, "Encryption: True")
19
+ else:
20
+ Loggy(phArgs.verbose,50, "Encryption: False")
21
+ Loggy(phArgs.verbose,50, "Timeout: " + str(phArgs.timeout))
22
+
23
+ Loggy(phArgs.verbose,50, "--------------------------------------")
24
+
25
+ if phArgs.TaskFile:
26
+ Loggy(phArgs.verbose,50, "Tasks: Task File")
27
+ Loggy(phArgs.verbose,50, "TaskFile: " + str(phArgs.TaskFile))
28
+
29
+ if phArgs.QuerySingle:
30
+ Loggy(phArgs.verbose,50, "Task: Single Query")
31
+ Loggy(phArgs.verbose,50, "Query Title: " + str(phArgs.title))
32
+ Loggy(phArgs.verbose,50, "Query Format: " + str(phArgs.OutFormat))
33
+ Loggy(phArgs.verbose,50, "Query Path: " + str(phArgs.path))
34
+ Loggy(phArgs.verbose,50, "Query Cypher: " + str(phArgs.QuerySingle))
35
+
36
+ if phArgs.BusiestPath:
37
+ Loggy(phArgs.verbose,50, "Task: Busiest Path")
38
+ Loggy(phArgs.verbose,50, "Argument 1: " + str(phArgs.BusiestPath[0]))
39
+ Loggy(phArgs.verbose,50, "Argument 2: " + str(phArgs.BusiestPath[1]))
40
+
41
+ if phArgs.AnalyzePath:
42
+ Loggy(phArgs.verbose,50, "Task: Analyzer Path")
43
+ Loggy(phArgs.verbose,50, "Start Node: " + str(phArgs.AnalyzePath[0].upper()))
44
+
45
+ if phArgs.easy:
46
+ Loggy(phArgs.verbose,50, "Task: Easy")
47
+ Loggy(phArgs.verbose,50, "Query Title: Domain Users")
48
+ Loggy(phArgs.verbose,50, "Query Format: STDOUT")
49
+ Loggy(phArgs.verbose,50, "Query Cypher: MATCH (n:User) RETURN n.name, n.displayname")
50
+
51
+ Loggy(phArgs.verbose,50, "--------------------------------------")
52
+
53
+ return True
lib/phTasks.py ADDED
@@ -0,0 +1,299 @@
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf8 -*-
3
+ # PlumHound (phtasks.py) - Task Management and Execution
4
+ # https://github.com/PlumHound/PlumHound
5
+ # License GNU GPL3
6
+
7
+ #Python Libraries
8
+ import ast
9
+ import copy
10
+ from alive_progress import alive_bar
11
+ from neo4j import GraphDatabase
12
+ from neo4j import unit_of_work
13
+
14
+ #Plumhound modules
15
+ from lib.phLoggy import Loggy as Loggy
16
+ import lib.phDeliver
17
+
18
+ #Plumhound Extensions
19
+ import modules.BlueHound
20
+ import modules.AzHound
21
+ import modules.ph_ReportIndexer
22
+ import modules.ph_TaskZipper
23
+
24
+ def MakeTaskList(phArgs):
25
+ Loggy(phArgs.verbose,900, "------ENTER: MAKETASKLIST-----")
26
+ Loggy(phArgs.verbose,200, "Building Task List")
27
+
28
+ tasks = []
29
+
30
+ if phArgs.TaskFile:
31
+ Loggy(phArgs.verbose,500, "Tasks file specified. Reading")
32
+ with open(phArgs.TaskFile, encoding="utf-8") as f:
33
+ tasks = f.read().splitlines()
34
+ Loggy(phArgs.verbose,500, "TASKS: " + str(tasks))
35
+ Loggy(phArgs.verbose,90, "Found " +str(len(tasks))+" task(s)")
36
+ Loggy(phArgs.verbose,90, "--------------------------------------")
37
+ Loggy(phArgs.verbose,90, "")
38
+ Loggy(phArgs.verbose,90, "")
39
+ return tasks
40
+
41
+ if phArgs.QuerySingle:
42
+ Loggy(phArgs.verbose,500, "Tasks Single Query Specified. Reading")
43
+ Loggy(phArgs.verbose,500, "Tasks-Title:" + phArgs.title)
44
+ Loggy(phArgs.verbose,500, "Tasks-OutFormat:" + phArgs.OutFormat)
45
+ Loggy(phArgs.verbose,500, "Tasks-OutPath:" + phArgs.path)
46
+ Loggy(phArgs.verbose,500, "Tasks-QuerySingle:" + phArgs.QuerySingle)
47
+
48
+ task_str = "[\"" + phArgs.title + "\",\"" + phArgs.OutFormat + "\",\"" + phArgs.OutFile + "\",\"" + phArgs.QuerySingle + "\"]"
49
+ Loggy(phArgs.verbose,500, "Task_str: " + task_str)
50
+ tasks = [task_str]
51
+
52
+ return tasks
53
+
54
+ if phArgs.BusiestPath:
55
+ # Find and print on screen the X Attack Paths that give the most users a path to DA
56
+ bp=modules.BlueHound.find_busiest_path(phArgs.server, phArgs.username, phArgs.password, phArgs.BusiestPath[0], phArgs.BusiestPath[1])
57
+
58
+ if phArgs.AnalyzePath:
59
+ if phArgs.AnalyzePath[0].upper() == "USER":
60
+ snode="User"
61
+ enode=""
62
+ elif phArgs.AnalyzePath[0].upper() == "GROUP":
63
+ snode="Group"
64
+ enode=""
65
+ elif phArgs.AnalyzePath[0].upper() == "COMPUTER":
66
+ snode="Computer"
67
+ enode=""
68
+ else:
69
+ snode=(phArgs.AnalyzePath[0]).upper()
70
+ enode=(phArgs.AnalyzePath[1]).upper()
71
+ modules.BlueHound.getpaths(phArgs.server, phArgs.username, phArgs.password,snode,enode)
72
+
73
+ if phArgs.AzPath:
74
+ if phArgs.AzPath[0].upper() == "ALL":
75
+ snode="AZUser"
76
+ enode="GLOBAL ADMINISTRATOR"
77
+ modules.AzHound.getpaths(phArgs.server, phArgs.username, phArgs.password,snode,enode)
78
+ snode="AZGroup"
79
+ modules.AzHound.getpaths(phArgs.server, phArgs.username, phArgs.password,snode,enode)
80
+ snode="AZApp"
81
+ modules.AzHound.getpaths(phArgs.server, phArgs.username, phArgs.password,snode,enode)
82
+ snode="AZServicePrincipal"
83
+ modules.AzHound.getpaths(phArgs.server, phArgs.username, phArgs.password,snode,enode)
84
+ snode="AZDevice"
85
+ modules.AzHound.getpaths(phArgs.server, phArgs.username, phArgs.password,snode,enode)
86
+ elif phArgs.AzPath[0].upper() == "AZUSER":
87
+ snode="AZUser"
88
+ enode="GLOBAL ADMINISTRATOR"
89
+ elif phArgs.AzPath[0].upper() == "AZGROUP":
90
+ snode="AZGroup"
91
+ enode="GLOBAL ADMINISTRATOR"
92
+ elif phArgs.AzPath[0].upper() == "AZAPP":
93
+ snode="AZApp"
94
+ enode="GLOBAL ADMINISTRATOR"
95
+ elif phArgs.AzPath[0].upper() == "AZSERVICEPRINCIPAL":
96
+ snode="AZServicePrincipal"
97
+ enode="GLOBAL ADMINISTRATOR"
98
+ elif phArgs.AzPath[0].upper() == "AZDEVICE":
99
+ snode="AZDevice"
100
+ enode="GLOBAL ADMINISTRATOR"
101
+ else:
102
+ snode=(phArgs.AzPath[0]).upper()
103
+ enode=(phArgs.AzPath[1]).upper()
104
+ if phArgs.AzPath[0].upper() != "ALL":
105
+ modules.AzHound.getpaths(phArgs.server, phArgs.username, phArgs.password,snode,enode)
106
+
107
+ if phArgs.easy:
108
+ Loggy(phArgs.verbose,500, "Tasks Easy Query Specified.")
109
+ tasks = ['["Domain Users (Limit 10)","STDOUT","","MATCH (n:User) RETURN n.name, n.displayname LIMIT 10"]']
110
+ Loggy(phArgs.verbose,100, "Found " +str(len(tasks))+" task(s)")
111
+ Loggy(phArgs.verbose,100, "--------------------------------------")
112
+ return tasks
113
+
114
+ Loggy(phArgs.verbose,100, "Tasks Generation Completed\nTasks: " + str(tasks))
115
+ Loggy(phArgs.verbose,900, "------EXIT: MAKETASKLIST-----")
116
+ return tasks
117
+
118
+
119
+ # Execute Tasks
120
+ def TaskExecution(tasks, phDriver, phArgs):
121
+
122
+ Loggy(phArgs.verbose,900, "------ENTER: TASKEXECUTION-----")
123
+ Loggy(phArgs.verbose,500, "Begin Task Executions")
124
+ Loggy(phArgs.verbose,500, "TASKS:" + str(tasks))
125
+
126
+ Outpath=phArgs.path
127
+
128
+ # Correct Path if sent as command line/not default.
129
+ if "//" not in Outpath:
130
+ Outpath=phArgs.path + "//"
131
+
132
+ jobHTMLHeader = phArgs.HTMLHeader
133
+ jobHTMLFooter = phArgs.HTMLFooter
134
+ jobHTMLCSS = phArgs.HTMLCSS
135
+
136
+ task_output_list = []
137
+
138
+ tasksuccess=0
139
+
140
+ with alive_bar(len(tasks),title='\t Executing Tasks',length=50,theme='smooth',spinner=None,dual_line=True,monitor="Tasks {count} / {total} ") as tpbar:
141
+ for job in tasks:
142
+ tpbar()
143
+ try:
144
+ Loggy(phArgs.verbose,500, "Job: " + str(job))
145
+
146
+ job_List = ast.literal_eval(job)
147
+ jobTitle = job_List[0]
148
+ jobOutFormat = job_List[1]
149
+ jobOutPathFile = Outpath + job_List[2]
150
+ jobQuery = job_List[3]
151
+
152
+ tpbar.text("\t -> Task: " + jobTitle)
153
+
154
+ Loggy(phArgs.verbose,200, "Starting job: " + jobTitle)
155
+
156
+ Loggy(phArgs.verbose,500, "Job Title: " + jobTitle)
157
+ Loggy(phArgs.verbose,500, "Job Format: " + jobOutFormat)
158
+ Loggy(phArgs.verbose,500, "Job File: " + jobOutPathFile)
159
+ Loggy(phArgs.verbose,500, "Job Query: " + jobQuery)
160
+
161
+ if jobQuery == "REPORT-INDEX":
162
+ task_output_list_clean = copy.deepcopy(task_output_list) #copy the list and revert it after ReportIndexer
163
+ modules.ph_ReportIndexer.ReportIndexer(phArgs.verbose,task_output_list, jobOutPathFile, jobHTMLHeader, jobHTMLFooter, jobHTMLCSS)
164
+ task_output_list = task_output_list_clean
165
+ task_output_list.append([jobTitle, len(jobresults_processed_list), job_List[2],jobOutFormat])
166
+ tasksuccess += 1
167
+ continue
168
+
169
+ if jobQuery == "ZIP-TASKS":
170
+ Loggy(phArgs.verbose,200, "task_output_list: " + str(task_output_list))
171
+ modules.ph_TaskZipper.ZipTasks(phArgs.verbose,task_output_list, jobOutPathFile, Outpath)
172
+ tasksuccess += 1
173
+ continue
174
+
175
+ #now returns native dict containing keys
176
+ jobkeys = get_keys(phArgs.verbose,phDriver, jobQuery)
177
+ jobkeys_List = ast.literal_eval(str(jobkeys))
178
+
179
+ # If keys returned 0, make an empty list
180
+ if isinstance(jobkeys_List, int):
181
+ jobkeys_List = []
182
+
183
+ #
184
+ jobresults = execute_query(phArgs.verbose,phDriver, jobQuery)
185
+ jobresults_processed = "[" + process_results(phArgs.verbose,jobresults) + "]"
186
+ try:
187
+ jobresults_processed_list = ast.literal_eval(jobresults_processed)
188
+ except Exception as er1:
189
+ Loggy(phArgs.verbose,100, "ERROR While parsing results (non-fatal but errors may exist in output.")
190
+ print(er1)
191
+ Loggy(phArgs.verbose,500, jobresults_processed)
192
+ jobresults_processed_list = jobresults_processed
193
+
194
+ if jobOutFormat == "HTML" or jobOutFormat == "HTMLCSV" or jobOutFormat == "CSV":
195
+ task_output_list.append([jobTitle, len(jobresults_processed_list), job_List[2],jobOutFormat])
196
+
197
+ Loggy(phArgs.verbose,500, "Exporting Job Results")
198
+ lib.phDeliver.SenditOut(phArgs.verbose,jobkeys_List, jobresults_processed_list, jobOutFormat, jobOutPathFile, "", jobTitle, jobHTMLHeader, jobHTMLFooter, jobHTMLCSS, jobQuery)
199
+ tasksuccess += 1
200
+
201
+ except Exception as er2:
202
+ Loggy(phArgs.verbose,100, "ERROR While running job (trying next job in list).")
203
+ print(er2)
204
+
205
+ Loggy(phArgs.verbose,90, "")
206
+ Loggy(phArgs.verbose,90, "Completed " + str(tasksuccess) + " of " + str(len(tasks)) + " tasks.")
207
+ Loggy(phArgs.verbose,90, "")
208
+
209
+
210
+ Loggy(phArgs.verbose,900, "------EXIT: TASKEXECUTION-----")
211
+
212
+ if tasksuccess != (len(tasks)):
213
+ Loggy(phArgs.verbose,100, "Completed " + str(tasksuccess) + " of " + str(len(tasks)) + " tasks (Non-Lethal errors occurred).")
214
+
215
+ Loggy(phArgs.verbose,90, "")
216
+
217
+ # Setup Query
218
+ @unit_of_work(timeout=300)
219
+ def execute_query(verbose, phDriver, query, enabled=True):
220
+ Loggy(verbose,900, "------ENTER: EXECUTE_QUERY-----")
221
+ try:
222
+ with phDriver.session() as session:
223
+ Loggy(verbose,500, "Running Query")
224
+ results = session.run(query)
225
+ #results return a <class 'neo4j._sync.work.result.Result'>
226
+ #https://neo4j.com/docs/api/python-driver/current/api.html#result
227
+ #I have tried getting the number of records in the object, but its a bit tricky, all functions doing it in one step ive tired have been deprecated and removed in the new driver
228
+ #even tried making a summary object before getting the real data:
229
+ #https://neo4j.com/docs/api/python-driver/current/api.html#neo4j.ResultSummary
230
+ #results = session.run(query)
231
+ #summary = results.consume()
232
+ #results = session.run(query)
233
+ #count = summary.counters.nodes_created()
234
+ #data = results.fetch(count)
235
+ #Bloodhounds javascript is using recursion, id say its the way to go
236
+ data = results.fetch(999999999999)
237
+ if check_records(verbose, phDriver, query):
238
+ Loggy(verbose,500, "Identified " + str(len(data)) + " Results")
239
+ else:
240
+ Loggy(verbose,200, "Job result: No records found")
241
+ Loggy(verbose,900, "------EXIT: EXECUTE_QUERY-----")
242
+ except Exception as er3:
243
+ Loggy(verbose,200,"Error occured in execute_query: ")
244
+ print(er3)
245
+ return data
246
+
247
+
248
+ # Grab Keys for Cypher Query
249
+ @unit_of_work(timeout=300)
250
+ def get_keys(verbose,phDriver, query, enabled=True):
251
+ Loggy(verbose,900, "------ENTER: get_keys-----")
252
+ try:
253
+ Loggy(verbose,500, "get_keys Query: " + str(query))
254
+ with phDriver.session() as session:
255
+ results = session.run(query)
256
+ keys = results.keys()
257
+ if check_records(verbose, phDriver, query):
258
+ keys = results.keys()
259
+ Loggy(verbose,500, "Identified " + str(len(keys)) + " Results")
260
+ Loggy(verbose,500, "Keys Found")
261
+ else:
262
+ Loggy(verbose,200, "No Keys found")
263
+ keys = 0
264
+ Loggy(verbose,500, "Key enumeration complete")
265
+ Loggy(verbose,900, "------EXIT: get_keys-----")
266
+ except Exception as er4:
267
+ Loggy(verbose,200,"Error occured in get_keys: ")
268
+ print(er4)
269
+ return keys
270
+
271
+
272
+ def check_records(verbose, phDriver, query):
273
+ Loggy(verbose,900, "------ENTER: check_records-----")
274
+ try:
275
+ with phDriver.session() as session:
276
+ results = session.run(query)
277
+ first = results.peek()
278
+ if first:
279
+ Loggy(verbose,500, "Found Records")
280
+ else:
281
+ Loggy(verbose,200, "No Records Found")
282
+ Loggy(verbose,900, "------EXIT: check_records-----")
283
+ except Exception as er5:
284
+ Loggy(verbose,200,"Error occured in check_records: ")
285
+ print(er5)
286
+ return first
287
+
288
+
289
+ def process_results(verbose,results):
290
+ Loggy(verbose,900, "------ENTER: process_results-----")
291
+ BigTable = ""
292
+ for record in results:
293
+ try:
294
+ BigTable = BigTable + str(record.values()) + ","
295
+ except Exception as er6:
296
+ Loggy(verbose,200, "Washing records failed. Error on record")
297
+ print(er6)
298
+ Loggy(verbose,900, "------EXIT: process_results-----")
299
+ return BigTable