"""
55 |
56 | bot = """
72 |
73 |
74 | """
75 |
76 | def parse_results(user_results, computer_results):
77 | html = '\n'
78 | if all(len(result['result']) == 0 for result in user_results) == False:
79 | html = html + "
User results
" + '\n'
80 | for result in user_results:
81 | if len(result['result']) != 0:
82 | html = html + button.format(query_name=(result['report'].format(number=len(result['result'])))) + '\n'
83 | for object in result['result']:
84 | html = html + '
' + object + '
' + '\n'
85 | html = html + '
' + '\n' + '
' + '\n'
86 |
87 | if all(len(result['result']) == 0 for result in computer_results) == False:
88 | html = html + "
Computer results
" + '\n'
89 | for result in computer_results:
90 | if len(result['result']) != 0:
91 | html = html + button.format(query_name=(result['report'].format(number=len(result['result'])))) + '\n'
92 | for object in result['result']:
93 | html = html + '
' + object + '
' + '\n'
94 | html = html + '' + '\n' + '' + '\n'
95 | return html
96 |
97 | def generate_html_report(user_results, computer_results):
98 | if all(len(result['result']) == 0 for result in user_results) == False or all(len(result['result']) == 0 for result in computer_results) == False:
99 | inner_html = parse_results(user_results, computer_results)
100 | report = top + title + time.strftime("%Y-%m-%d %H:%M:%S") + '' + inner_html + bot
101 | return report
102 |
103 | def generate_report(user_results, computer_results):
104 | reportdir = os.path.realpath(os.path.dirname(__file__)) + '/reports'
105 | if os.path.isdir(reportdir) == False:
106 | os.makedirs(reportdir)
107 |
108 | reportdest = reportdir + "/pycobalthound-report-" + time.strftime("%Y%m%d-%H%M%S") + ".html"
109 | report = generate_html_report(user_results, computer_results)
110 | f = open(reportdest, "w")
111 | f.write(report)
112 | f.close()
113 | return reportdest
114 |
115 |
116 |
117 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## Quick summary
4 |
5 | `pyCobaltHound` is an Aggressor script extension for Cobalt Strike which aims to provide a deep integration between `Cobalt Strike` and `Bloodhound`.
6 |
7 | `pyCobaltHound` strives to assists red team operators by:
8 |
9 | - Automatically querying the `BloodHound` database to discover escalation paths opened up by newly collected credentials.
10 | - Automatically marking compromised users and computers as owned.
11 | - Allowing operators to quickly and easily investigate the escalation potential of beacon sessions and users.
12 |
13 | To accomplish this, `pyCobaltHound` uses a set of built-in queries. Operators are also able to add/remove their own queries to fine tune `pyCobaltHound's` monitoring capabilities. This grants them the flexibility to adapt `pyCobaltHound` on the fly during engagements to account for engagement-specific targets (users, hosts etc..).
14 |
15 | ## Installation & usage
16 |
17 | To install `pyCobaltHound` clone this repository. Do not forget to also clone the included submodule!
18 |
19 | You can use the following command:
20 |
21 | - `git clone https://github.com/NVISOsecurity/pyCobaltHound.git --recurse-submodules`
22 |
23 | ### Dependencies
24 |
25 | Ensure that the following dependencies are correctly installed:
26 |
27 | #### PyCobalt
28 |
29 | `PyCobalt` is a Python API for `Cobalt Strike`. It exposes many Aggressor functions to be used directly from Python.
30 |
31 | ##### Setup
32 |
33 | Ensure that you have `Python3+` installed. While `PyCobalt` may work on macOS and Windows as well, we have only really tested it on Linux.
34 |
35 | There are two ways to use the `PyCobalt` Python library:
36 |
37 | 1. Run it straight out of the repository using [PYTHONPATH](https://docs.python.org/3/using/cmdline.html#envvar-PYTHONPATH). `pyCobaltHound` takes this approach, setting the search path from within the Python program using the variable [`sys.path`](https://docs.python.org/3/library/sys.html#sys.path) variable.
38 | 2. Install the `PyCobalt` Python library. To do so, run `python3 setup.py install`. You will have to modify `pycobalthound.py` to ensure that it used the installed library instead of the one in the included repository.
39 |
40 | ##### Remarks
41 |
42 | - Note that there is no guarantee that the `PyCobalt` project will be maintained in the future. In fact, the latest update to the project was to incorporate the changes made in `Cobalt Strike 4.2`. Since `pyCobaltHound` only really uses basic Aggressor functions to interface with `Cobalt Strike` and its operator however this is not a big problem for `pyCobaltHound`.
43 | - The `PyCobalt` submodule used in this project is a fork done by us. We do not control the `PyCobalt` repository however.
44 |
45 | ##### Tips & tricks
46 |
47 | - `PyCobalt` comes with some Script Console commands to manage the running Python scripts. When you reload your Aggressor script you should explicitly stop the Python scripts first. Otherwise they'll run forever doing nothing. During `pyCobaltHound's` development we noticed that this can also lead to undefined behavior.
48 |
49 | Reloading `pyCobaltHound` can be done as follows:
50 |
51 | ```
52 | aggressor> python-stop-all`
53 | [pycobalt] Asking script to stop: /root/pycobalthound/pycobalthound.py
54 | [pycobalt] Script process exited: /root/pycobalthound/pycobalthound.py
55 |
56 | aggressor> reload example.cna`
57 | [pycobalt] Executing script /root/pycobalthound/pycobalthound.py
58 | ```
59 |
60 | - For `PyCobalt` to work properly you can only call `PyCobalt` in one Aggressor script. Keep this in mind if you want to use `pyCobaltHound` together with other Aggressor scripts that use `PyCobalt`. Our approach is to have an Aggressor script with a calls to python() and include() for every `PyCobalt` based tool.
61 |
62 | #### notify2 (Optional)
63 |
64 | [`notify2`](https://notify2.readthedocs.io/en/latest/) is - or was - a package to display desktop notifications on Linux. As we will see later `pyCobaltHound` supports a few ways of notifying the operator. `notify2` is used on Linux to send notifications to the notification daemon over D-Bus.
65 |
66 | To enable this, `notify2` needs to be installed using:
67 |
68 | `pip install notify2`
69 |
70 | ### Usage in Cobalt Strike
71 |
72 | Using `pyCobaltHound` in `Cobalt Strike` is as simple as importing the `pycobalthound.cna` Aggressor script into your client. Once this is done you should see a`pyCobaltHound` menu appear in your `Cobalt Strike` menubar.
73 |
74 | 
75 |
76 | ## Usage
77 |
78 | ### Credential store monitoring
79 |
80 | `pyCobaltHound's` initial goal was to monitor `Cobalt Strike's` credential cache (`View` > `Credentials`) for new entries. It does this by reacting to the *on_credentials* event that `Cobalt Strike` fires when changed to the credential store are made.
81 |
82 | When this event is fired, `pyCobaltHound` will:
83 |
84 | 1. Parse and validate the data recieved from `Cobalt Strike`
85 | 2. Check if it has already investigated these entities by reviewing it's cache
86 | 3. Add the entities to a cache for future runs
87 | 4. Check if the entities exist in the `BloodHound` database
88 | 5. Mark the entities as owned
89 | 6. Query the `BloodHound` database for each new entity using both built-in and custom queries.
90 | 7. Parse the returned results, notify the operator of any interesting findings and write them to a basic HTML report.
91 |
92 | Since all of this takes place asynchronously from the main `Cobalt Strike` client this process should not block your UI so you can keep working while `pyCobaltHound` investigates away in the background.
93 |
94 | `pyCobaltHound` uses seperate caches per teamserver to prevent issues when using multiple teamservers.
95 |
96 | #### Removing entities from the cache
97 |
98 | Sometimes there are situations where you would want to investigate specific users (or the entire credential store) again. This might be the case when you've uploaded new data into the `BloodHound` database.
99 |
100 | Since `pyCobaltHound` should have investigated (and therefore cached) all entities in your credential store already it will not evaluate them against this new data without some operator intervention.
101 |
102 | Two methods are available to operators to control which entities are cached.
103 |
104 | ##### Removing specific entities
105 |
106 | In cases where you wish to remove a specific entity (or multiple) from the cache you can do so in the credential viewer (`View` > `Credentials`). Simply select your target(s) and click the *remove from cache* option under the `pyCobaltHound` menu entry.
107 |
108 | ##### Removing the entire cache
109 |
110 | In cases where you wish to remove all entities from the cache you can do so in `pyCobaltHound's` main menu (`Cobalt Strike` > `pyCobaltHound` > `Wipe cache`). This is most helpful when you want to reevaluate your entire credential store.
111 |
112 | 
113 |
114 | ##### Manually triggering an investigation
115 |
116 | After removing your targets from the cache you can manually prompt `pyCobaltHound` to re-investigate the contents of the credential store. This follows exactly the same process as above.
117 |
118 | ### Beacon management
119 |
120 | `pyCobaltHound` contains functionality to interact with existing beacon sessions. This can be found in the beacon context menu. Note that these commands can be executed on a single beacon or a selections of beacons.
121 |
122 | 
123 |
124 | This functionality is especially useful when dealing with users and computers whose credentials have not been compromised (yet), but that are effectively under our control (e.g because we have a beacon running under their session token).
125 |
126 | #### Mark as owned
127 |
128 | The *Mark as owned* functionality (`pyCobaltHound` > `Mark as owned`) can be used to mark a beacon (or collection of beacons) as owned in the `BloodHound` database.
129 |
130 | 
131 |
132 | This dialog will ask the operator for the following information:
133 |
134 | - **Nodetype**
135 | - **Both:** If this is selected, both the user and computer associated with the beacon context will be marked as owned. `pyCobaltHound` will only mark computers as owned if the beacon session is running as local admin, SYSTEM or a high integrity session as another user.
136 | - **User:** If this is selected the user associated to the beacon context will be marked as owned.
137 | - **Computer:** If this is selected the computer associated to the beacon context will be marked as owned, regardless of the integrity level of the associated session.
138 | - **Domain**
139 | - Since a beacon's context does not contain any reference to the domain, operators need to specify this themselves
140 |
141 | #### Investigation
142 |
143 | The *Investigate* functionality (`pyCobaltHound` > `Mark as owned`) can be used to investigate the users and hosts associated with a beacon (or collection of beacons).
144 |
145 | 
146 |
147 | This dialog will ask the operator for the following information:
148 |
149 | - **Nodetype**
150 | - **Both:** If this is selected, both the user and computer associated with the beacon context will be investigated. `pyCobaltHound` will only investigate computers if the beacon session is running as local admin, SYSTEM or a high integrity session as another user.
151 | - **Both without logic:** If this is selected, both the user and computer associated with the beacon context will be investigated. `pyCobaltHound` will investigate all entities without checking for integrity levels.
152 | - **User:** If this is selected the user associated to the beacon context will be marked as owned.
153 | - **Computer:** If this is selected the computer associated to the beacon context will be marked as owned, regardless of the integrity level of the associated session.
154 | - **Domain**
155 | - Since a beacons context does not contain any reference to the domain, operators need to specify this themselves
156 | - **Generate a report**
157 | - If this option is selected a basic HTML report will be generated
158 |
159 | ### Entity investigation
160 |
161 | `pyCobaltHound` contains functionality to freely investigate entities. This can be found in the main menu (`Cobalt Strike` > `pyCobaltHound` > `Investigate` ).
162 |
163 | This functionality is especially useful when dealing with users and computers whose credentials have not been compromised and are not under our control.
164 |
165 | 
166 |
167 | This dialog will ask the operator for the following information:
168 |
169 | - **Targets**
170 | - A CSV-style string of entities the operator wishes to investigate. This can be just user/computer names (e.g user1) **or** FQDNs (user1@domain.local).
171 | - **Note:** Do not mix & match notations. You can do either user/computer names or FQDN's!
172 | - **Domain included**
173 | - This parameter specifies if the provided target string contains just user/computer names or FQDNs.
174 | - **Domain**
175 | - If the targetstring does not contain FQDNs the operator will need to indicate the domain the entities to investigate belong to.
176 | - **Generate a report**
177 | - If this option is selected a basic HTML report will be generated
178 |
179 | ## Settings
180 |
181 | `pyCobaltHound's` settings menu can be found under `Cobalt Strike` > `pyCobaltHound` > `Settings`.
182 |
183 | 
184 |
185 | `pyCobaltHound` will save your settings to disk. Every time `pyCobaltHound` is reloaded, it will check for the existence of a settings file and load the saved settings if it finds one.
186 |
187 | `pyCobaltHound` saves a settings file per teamserver, so it is possible to have different settings on different teamservers.
188 |
189 | #### Neo4j
190 |
191 | To authenticate to the `BloodHound` database, `pyCobaltHound` will need the following information:
192 |
193 | - **Neo4j username**
194 | - **Neo4j password**
195 | - **Neo4j URL**
196 |
197 | **Note:** if you choose to persistently save your settings (to preserve them across client/host reboots) `pyCobaltHound` will deserialize and store these credentials on disk.
198 |
199 | #### Caching
200 |
201 | As discussed before, `pyCobaltHound` uses caching to make sure it does not perform unnecessary work. This caching can be disabled in the settings. This is mostly useful when developing new queries so you don't constantly have to manage/wipe the cache.
202 |
203 | #### Notifications
204 |
205 | `pyCobaltHound` supports a few different methods of notifying the operator once it has identified an entity of interest. It is possible to disable these notifications.
206 |
207 | ##### Native notifications
208 |
209 | By default, `pyCobaltHound` will notify the operator using the default Aggressor messagebox. This option can the operators workflow. It is however the default method since it it supported on each platform you can run a `Cobalt Strike` client.
210 |
211 | 
212 |
213 | ##### Notify2 notifications
214 |
215 | `pyCobaltHound` also supports displaying desktop notifications on Linux. This is our preferred option since it does not interrupt the operators workflow.
216 |
217 | 
218 |
219 | #### Reporting
220 |
221 | During some of its workflows, `pyCobaltHound` will generate an HTML report. This design choice was made to avoid spamming the operator with giant notifications in case a lot of entities were investigated. These reports will be generated in the *reports* folder. It is possible to disable the report generation.
222 |
223 | 
224 |
225 | #### Query synchronization
226 |
227 | By default, `pyCobaltHound` will synchronize queries across teamservers by using a central file for all query related settings. This means that queries that are enabled, added or deleted on one teamserver will also be enabled, added, delete to the queries made by other teamservers. This is mostly a convenience option and can be disabled, which is useful in cases where you are running engagement specific queries that do not apply to all the teamservers you are connected to.
228 |
229 | ##### Disabling
230 |
231 | When query synchronization is disabled, `pyCobaltHound` will check for the existence of unique query files. If these exists, it will load these and use these queries during its workflows. If the files do not exists, it will create and load them . This setting will persist through reloads
232 |
233 | ##### Enabling
234 |
235 | When query synchronization is enabled, `pyCobaltHound` will check for the existence of unique query files. If these exists, the operator will be prompted for a choice.
236 |
237 | 
238 |
239 | The operator has the following choices:
240 |
241 | - **Delete**
242 | - If chosen, `pyCobaltHound` will simply remove the unique query files. All custom queries will be lost.
243 | - **Merge**
244 | - If chosen, `pyCobaltHound` will attempt to merge the unique query files into the general query files. Before merging a query, it will check if there is no query in the general file that has the same name or the same Cypher statement. If any merge conflicts occur, the operator will be asked if they want to keep the non-merged queries. They will be saved in a separate file. The unique query files will then be removed.
245 | - **Keep**
246 | - If chosen, `pyCobaltHound` will just leave the unique query files. All custom queries will be preserved and the files will be loaded again if query synchronization is disabled again.
247 |
248 | ## Queries
249 |
250 | ### Built-in queries
251 |
252 | `pyCobaltHound` currently supports the following built-in queries:
253 |
254 | - **User** **(user-queries.json)**
255 | - Path to Domain Admins
256 | - Path to High Value Targets
257 | - **Computer** **(computer-queries.json)**
258 | - Path to High Value Targets
259 |
260 | ### Managing queries
261 |
262 | Managing the various queries that `pyCobaltHound` uses can be done through the main menu (`Cobalt Strike` > `pyCobaltHound` > `Queries`).
263 |
264 | 
265 |
266 | #### Enabling/Disabling queries
267 |
268 | The *Update queries* dialog allows operators to enable/disable specific queries. When using the this dialog, the operator will first be asked what type of queries they want to update. This is done to dynamically render/load the correct queries during this workflow.
269 |
270 | 
271 |
272 | After answering the first dialog, the operator will then be presented with a list of all available queries of that type. Here they can choose which queries they wish to enable/disable.
273 |
274 | 
275 |
276 | The query type option is an ugly workaround to pass the query type to the next function in the workflow and is of no concern to the operator.
277 |
278 | #### Adding custom queries
279 |
280 | The *Add query* functionality allows operators to add/remove their own queries to fine tune `pyCobaltHound's` investigation capabilities. This grants them the flexibility to adapt `pyCobaltHound` on the fly during engagements to account for engagement-specific targets (users, hosts etc..).
281 |
282 | 
283 |
284 | This dialog will ask the operator for the following information:
285 |
286 | - **Name**
287 | - The name of the custom query. This will be used in various menus & reports during `pyCobaltHounds` workflows.
288 | - **Cypher query**
289 | - The Cypher query `pyCobaltHound` needs to execute. Operators are quite free to define their queries. The only requirements are the following:
290 | - `pyCobaltHound` dynamically generates the following Cypher string based on the entity names it is investigating:
291 | - `WITH [account names here] AS samAccountNames UNWIND samAccountNames AS names`.
292 | - The **{statement}** placeholder will be replaced with this string.
293 | - This Cypher string takes the samAccountNames of the targets and assigns them to the "names" variable.
294 | - To make your query work with this you must ensure that it starts with the following statement:
295 | - `MATCH (x) WHERE x.name STARTS WITH names`
296 | - I recommend filtering (e.g `(x:User)`) depending on which query type you are adding.
297 | - `pyCobaltHound` expects the query to return a distinct set of usernames.
298 | - To do so, end your query with `RETURN DISTINCT (x.name)`
299 | - For some examples, refer to the built-in queries.
300 | - **Report headline**
301 | - The headline that `pyCobaltHound` uses for the custom query. This will be used in notifications & reports during `pyCobaltHounds` workflows.
302 | - The only requirement is the the sentence contains a **{number}** placeholder which `pyCobaltHound` will replace with the amount of results for this query.
303 | - **Status**
304 | - This parameter determines if the query is created in an enabled or disabled state.
305 | - **Query type**
306 | - The type of query you are adding. This will determine which set of queries is edited.
307 |
308 | #### Deleting custom queries
309 |
310 | The *Delete query* dialog allows operators to remove specific custom queries from `pyCobaltHound`. When using the this dialog, the operator will first be asked what type of query they want to remove. This is done to dynamically render/load the correct queries during this workflow.
311 |
312 | 
313 |
314 | After answering the first dialog, the operator will then be presented with a list of all available queries of that type. Here they can choose which queries they wish to remove.
315 |
316 | 
317 |
318 | The query type option is an ugly workaround to pass the query type to the next function in the workflow and is of no concern to the operator.
319 |
320 | ## References
321 |
322 | `pyCobaltHound` uses/takes inspiration from the following:
323 |
324 | - [pycobalt](https://github.com/dcsync/pycobalt.git) by dcsync
325 | - [Vampire](https://github.com/Coalfire-Research/Vampire.git) by Coalfire-Research
326 | - [ANGRYPUPPY](https://github.com/vysecurity/ANGRYPUPPY.git) by vysecurity
327 | - [Max](https://github.com/knavesec/Max.git) by knavesec
328 | - [BloodHound](https://github.com/BloodHoundAD/BloodHound.git) by SpecterOps
329 |
330 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/pycobalthound.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | # So we can use the repo copy of pycobalt
4 | import sys
5 | import os
6 | from netaddr.ip import cidr_merge
7 | sys.path.insert(0, os.path.realpath(os.path.dirname(__file__)) + "/pycobalt")
8 |
9 | # Importing the required regular libraries
10 | import requests
11 | import json
12 | import pickle
13 | import asyncio
14 | import base64
15 | import netaddr
16 |
17 | from aiohttp import ClientSession
18 | from requests.models import HTTPError
19 | from requests.exceptions import ConnectionError
20 |
21 | # Importing the required pycobalt libraries
22 | import pycobalt.engine as engine
23 | import pycobalt.events as events
24 | import pycobalt.aggressor as aggressor
25 | import pycobalt.gui as gui
26 |
27 | # Importing the reporting functionality
28 | from report import generate_report
29 |
30 | # Functions
31 | # JSON handling
32 | def read_json(location):
33 | with open(location, "r") as json_file:
34 | data = json.load(json_file)
35 | return data
36 |
37 | def write_json(data, location):
38 | with open(location, "w") as json_file:
39 | json.dump(data, json_file, indent=4)
40 |
41 | # Settings initialization & handling
42 | def load_queries():
43 | global user_queries
44 | global computer_queries
45 | # Load user cypher queries
46 | user_queries = read_json(user_queries_location)
47 |
48 | # Load computer cypher queries
49 | computer_queries = read_json(computer_queries_location)
50 |
51 | engine.message("succesfully (re)loaded queries")
52 |
53 | # Disable query sync
54 | def disable_query_sync():
55 | global user_queries
56 | global computer_queries
57 | global user_queries_location
58 | global computer_queries_location
59 |
60 | unique_user_queries_location = os.path.realpath(os.path.dirname(__file__)) + "/queries/user-queries-" + str(unique_id) + ".json"
61 | unique_computer_queries_location = os.path.realpath(os.path.dirname(__file__)) + "/queries/computer-queries-" + str(unique_id) + ".json"
62 |
63 | # If there are no previous seperate .json files, create them
64 | # If there are previous separate .json files, read them
65 |
66 | if not os.path.exists(unique_user_queries_location):
67 | write_json(user_queries, unique_user_queries_location)
68 | user_queries_location = unique_user_queries_location
69 | else:
70 | user_queries = read_json(unique_user_queries_location)
71 | user_queries_location = unique_user_queries_location
72 |
73 | if not os.path.exists(unique_computer_queries_location):
74 | write_json(computer_queries, unique_computer_queries_location)
75 | computer_queries_location = unique_computer_queries_location
76 |
77 | else:
78 | computer_queries = read_json(unique_computer_queries_location)
79 | computer_queries_location = unique_computer_queries_location
80 |
81 | engine.message("Query synchronization has been disabled!")
82 |
83 | # Enable query sync helpers
84 | def delete_query_files():
85 | unique_user_queries_location = os.path.realpath(os.path.dirname(__file__)) + "/queries/user-queries-" + str(unique_id) + ".json"
86 | unique_computer_queries_location = os.path.realpath(os.path.dirname(__file__)) + "/queries/computer-queries-" + str(unique_id) + ".json"
87 | os.remove(unique_user_queries_location)
88 | os.remove(unique_computer_queries_location)
89 |
90 | def restore_query_locations():
91 | global user_queries_location
92 | global computer_queries_location
93 | user_queries_location = os.path.realpath(os.path.dirname(__file__)) + "/queries/user-queries.json"
94 | computer_queries_location = os.path.realpath(os.path.dirname(__file__)) + "/queries/computer-queries.json"
95 |
96 | def save_conflicts(values):
97 | global merge_conflicts
98 | conflictfile_location = os.path.realpath(os.path.dirname(__file__)) + "/queries/conflict-" + str(unique_id) + ".json"
99 | write_json(merge_conflicts, conflictfile_location)
100 | aggressor.show_message("Merge conflicts were saved to " + conflictfile_location)
101 | merge_conflicts = []
102 |
103 | # Enable query sync
104 | def enable_query_sync(dialog, button_name, values):
105 | global user_queries
106 | global computer_queries
107 | global user_queries_location
108 | global computer_queries_location
109 | # There is no good reason to make this a global except for the fact that Aggressor script sucks and bugs out when passing variables to functions in prompts
110 | global merge_conflicts
111 |
112 | merge_conflicts = []
113 |
114 | unique_user_queries_location = os.path.realpath(os.path.dirname(__file__)) + "/queries/user-queries-" + str(unique_id) + ".json"
115 | unique_computer_queries_location = os.path.realpath(os.path.dirname(__file__)) + "/queries/computer-queries-" + str(unique_id) + ".json"
116 | general_user_queries_location = os.path.realpath(os.path.dirname(__file__)) + "/queries/user-queries.json"
117 | general_computer_queries_location = os.path.realpath(os.path.dirname(__file__)) + "/queries/computer-queries.json"
118 |
119 | if button_name == "Delete":
120 | delete_query_files()
121 | restore_query_locations()
122 |
123 | if button_name == "Merge":
124 | message = ""
125 |
126 | # User check
127 | custom_user_queries = [query for query in user_queries if query["custom"] == "True"]
128 | general_user_queries = read_json(general_user_queries_location)
129 |
130 | for custom_query in custom_user_queries:
131 | if not any(general_query["name"] == custom_query["name"] for general_query in general_user_queries):
132 | if not any(general_query["statement"] == custom_query["statement"] for general_query in general_user_queries):
133 | general_user_queries.append(custom_query)
134 | else:
135 | merge_conflicts.append(custom_query)
136 | message = message + "Merging '" + custom_query["name"] + "' failed because of a query conflict" + "\n"
137 | else:
138 | merge_conflicts.append(custom_query)
139 | message = message + "Merging '" + custom_query["name"] + "' failed because of a name conflict" + "\n"
140 |
141 | # Computer check
142 | custom_computer_queries = [query for query in computer_queries if query["custom"] == "True"]
143 | general_computer_queries = read_json(general_computer_queries_location)
144 |
145 | for custom_query in custom_computer_queries:
146 | if not any(general_query["name"] == custom_query["name"] for general_query in general_computer_queries):
147 | if not any(general_query["statement"] == custom_query["statement"] for general_query in general_computer_queries):
148 | general_computer_queries.append(custom_query)
149 | else:
150 | merge_conflicts.append(custom_query)
151 | message = message + "Merging '" + custom_query["name"] + "' failed because of a query conflict" + "\n"
152 | else:
153 | merge_conflicts.append(custom_query)
154 | message = message + "Merging '" + custom_query["name"] + "' failed because of a name conflict" + "\n"
155 |
156 | # Write out merged JSON
157 | write_json(general_user_queries, general_user_queries_location)
158 | write_json(general_computer_queries, general_computer_queries_location)
159 |
160 | # Prompt operator to keep/delete unique query files
161 | if merge_conflicts:
162 | message = message + "\n"
163 | message = message + "Do you want to keep these queries?"
164 | aggressor.prompt_confirm(message, "Merge queries", save_conflicts)
165 | delete_query_files()
166 | else:
167 | delete_query_files()
168 |
169 | if button_name == "Keep":
170 | restore_query_locations()
171 |
172 | def check_notify2():
173 | global settings
174 | try:
175 | import notify2
176 | return True
177 | except ImportError or ModuleNotFoundError:
178 | engine.error("Notify2 is not installed, falling back to native notifications!")
179 | settings["notifytype"] = "Native"
180 | return False
181 |
182 | def init_settings():
183 | global unique_id
184 | global cache_location
185 | global settings_location
186 | global user_queries_location
187 | global computer_queries_location
188 | global reportpath
189 | global settings
190 |
191 | unique_id = (netaddr.IPAddress(aggressor.localip())).value
192 | cache_location = os.path.realpath(os.path.dirname(__file__)) + "/cache/pycobalthound-" + str(unique_id) + ".cache"
193 | settings_location = os.path.realpath(os.path.dirname(__file__)) + "/settings/pycobalthound-" + str(unique_id) + ".settings"
194 | user_queries_location = os.path.realpath(os.path.dirname(__file__)) + "/queries/user-queries.json"
195 | computer_queries_location = os.path.realpath(os.path.dirname(__file__)) + "/queries/computer-queries.json"
196 | reportpath = ""
197 |
198 | # Check if settings have been saved
199 | if os.path.isfile(settings_location):
200 | try:
201 | settings = pickle.load(open(settings_location, "rb"))
202 | engine.message("Restored settings from: " + settings_location)
203 | except OSError:
204 | engine.debug("Could not load the settings file")
205 |
206 | # If no settings were saved apply the defaults
207 | else:
208 | settings = {
209 | "ignore_cache": False,
210 | "report": True,
211 | "notify": True,
212 | "notifytype": "Native",
213 | "sync_queries": True,
214 | "url": "http://localhost:7474/db/data/transaction/commit",
215 | "headers": { "Accept": "application/json; charset=UTF-8",
216 | "Content-Type": "application/json",
217 | "Authorization": "bmVvNGo6Ymxvb2Rob3VuZA=="
218 | }
219 | }
220 |
221 | # load the initial queries
222 | load_queries()
223 |
224 | # if query syncing has been disabled, set the correct values and reload queries
225 | if not settings["sync_queries"]:
226 | disable_query_sync()
227 | load_queries()
228 |
229 | ## If notify2 is selected as choice, check if it's installed. Otherwise default to native notifications
230 | check_notify2()
231 |
232 | @events.event("init", official_only=False)
233 | def init_wrapper():
234 | engine.message("Initializing pyCobaltHound")
235 | while aggressor.localip() == "127.0.0.1":
236 | engine.debug("")
237 | init_settings()
238 | engine.message("Initialization complete")
239 | connection_test_wrapper()
240 |
241 | # Cypher query functions
242 | def do_sync_cypher(query):
243 | data = {"statements": [{"statement": query}]}
244 | response = ""
245 |
246 | try:
247 | response = requests.post(url=settings["url"],headers=settings["headers"],json=data)
248 | response.raise_for_status()
249 | except HTTPError as http_err:
250 | engine.error(f"An HTTP error has occurred: {http_err}")
251 | except ConnectionError as conn_err:
252 | engine.error(f"A connection error has occurred: Is the database online/reachable?")
253 | except Exception as err:
254 | engine.error(f"An error has ocurred: {err}")
255 | if response:
256 | return response
257 |
258 | async def do_async_cypher(query, session):
259 | data = {"statements": [{"statement": query}]}
260 | try:
261 | response = await session.post(settings["url"], json=data)
262 | response.raise_for_status()
263 | except HTTPError as http_err:
264 | engine.error(f"HTTP error occurred: {http_err}")
265 | except Exception as err:
266 | engine.error(f"An error ocurred: {err}")
267 | result = await response.text()
268 |
269 | return result
270 |
271 | async def do_async_query(query, accounts, session):
272 | result = {"name": [], "result": []}
273 |
274 | with_statement = make_with_statement(accounts)
275 | final_query = query["query"].format(statement=with_statement)
276 |
277 | try:
278 | response = await do_async_cypher(final_query, session)
279 | result["name"].append(query["name"])
280 | result["result"].append(response)
281 | return result
282 | except Exception as err:
283 | engine.error(f"Exception occured: {err}")
284 | pass
285 |
286 | async def do_async_queries(queries, accounts):
287 | async with ClientSession(headers=settings["headers"]) as session:
288 | query_results = await asyncio.gather(*[do_async_query(query, accounts, session) for query in queries])
289 | return query_results
290 |
291 | # Data handling/parsing functions
292 | def check_valid_realm(credentials, domains):
293 | valid_users = []
294 |
295 | for x in credentials:
296 | if any(x["realm"].upper() in s for s in domains):
297 | valid_users.append(x)
298 |
299 | return valid_users
300 |
301 | def check_cache(valid_users):
302 | keys = ["user", "realm"]
303 | engine.message(cache_location)
304 | parsed_users = []
305 | cached_users = []
306 | new_users = []
307 |
308 | if not settings["ignore_cache"]:
309 | if not os.path.isdir(os.path.realpath(os.path.dirname(__file__)) + "/cache"):
310 | os.makedirs(os.path.realpath(os.path.dirname(__file__)) + "/cache")
311 |
312 | if not settings["ignore_cache"]:
313 | try:
314 | cached_users = pickle.load(open(cache_location, "rb"))
315 | engine.message("Restored users from: " + cache_location)
316 | except OSError:
317 | engine.debug("Could not find a cache file")
318 | else:
319 | engine.message("Ignoring cache. If you want the benefit of caching you should enable the cache")
320 |
321 | for user in valid_users:
322 | parsed_users.append({key: user[key].upper() for key in keys})
323 |
324 | for user in parsed_users:
325 | if(user in cached_users):
326 | engine.debug("User was found in cache, skipping")
327 | continue
328 | else:
329 | if not settings["ignore_cache"]:
330 | engine.debug("User was not found in cache, adding to cache and processing")
331 | cached_users.append(user)
332 | new_users.append(user)
333 |
334 | if not settings["ignore_cache"]:
335 | cached_users = [user for user in cached_users if user in parsed_users]
336 | try:
337 | engine.debug("Saving the cache to: " + cache_location)
338 | engine.message(cache_location)
339 | pickle.dump(cached_users, open(cache_location, "wb"))
340 | except OSError:
341 | engine.error("Could not save cache!")
342 |
343 | return new_users
344 |
345 | def check_user_type(new_users):
346 | transformed_users = new_users
347 |
348 | for user in transformed_users:
349 | if(user["user"][-1] == "$"):
350 | name = user["user"][:-1] + "." + user["realm"]
351 | user.update(type="Computer")
352 | user.update(username=name)
353 | else:
354 | name = user["user"] + "@" + user["realm"]
355 | user.update(type="User")
356 | user.update(username=name)
357 |
358 | return transformed_users
359 |
360 | def get_domains():
361 | domains = []
362 |
363 | query = "MATCH (n:Domain) RETURN n"
364 | r = do_sync_cypher(query)
365 | j = json.loads(r.text)
366 | for x in j["results"][0]["data"]:
367 | domains.append(x["row"][0]["name"])
368 |
369 | return domains
370 |
371 | def make_with_statement(accounts):
372 | account_names = []
373 |
374 | for account in accounts:
375 | account_names.append(account["username"])
376 | query = f"WITH {account_names} AS samAccountNames UNWIND samAccountNames AS names"
377 |
378 | return query
379 |
380 | def check_existence(transformed_users):
381 | existing_users = []
382 |
383 | with_statement = make_with_statement(transformed_users)
384 | query = f"{with_statement} MATCH (n) WHERE n.name STARTS with names RETURN n"
385 | r = do_sync_cypher(query)
386 | bh_json = json.loads(r.text)
387 |
388 | for transformed_user in transformed_users:
389 | for bh_user in bh_json["results"][0]["data"]:
390 | if transformed_user["username"].upper() in bh_user["row"][0]["name"].upper():
391 | existing_users.append({"username": bh_user["row"][0]["name"], "type": transformed_user["type"]})
392 |
393 | return existing_users
394 |
395 | def mark_owned(existing_users):
396 | with_statement = make_with_statement(existing_users)
397 | query = f"{with_statement} MATCH (n) WHERE n.name STARTS with names SET n.owned = TRUE"
398 | do_sync_cypher(query)
399 |
400 | def parse_results(queries, results):
401 | parsed_results = []
402 |
403 | for query in queries:
404 | data = []
405 | result = next((result for result in results if ("".join(result["name"])) == query["name"]), None)
406 | entries = json.loads(result["result"][0])
407 | for entry in entries["results"][0]["data"]:
408 | data.append("".join(entry["row"]))
409 |
410 | parsed_results.append({"name": query["name"], "report": query["report"], "result": data})
411 | return parsed_results
412 |
413 | def notify(header, message):
414 | if settings["notifytype"] == "pyNotify" and check_notify2:
415 | import notify2
416 | notify2.init("pyCobaltHound")
417 | u = notify2.Notification(header, message)
418 | u.set_timeout(300000)
419 | u.show()
420 | else:
421 | aggressor.show_message(message)
422 |
423 | def notify_operator(user_results, computer_results, reportpath):
424 | if all(len(result["result"]) == 0 for result in user_results) == False:
425 | message = ""
426 | for result in user_results:
427 | if len(result["result"]) != 0:
428 | message = message + result["report"].format(number=len(result["result"])) + "\n"
429 |
430 | if reportpath:
431 | message = message + "\n" + "More details can be found in: " + reportpath + "\n"
432 | notify("pyCobalthound - User report", message[:-1])
433 |
434 | if all(len(result["result"]) == 0 for result in computer_results) == False:
435 | message = ""
436 | for result in computer_results:
437 | if len(result["result"]) != 0:
438 | message = message + result["report"].format(number=len(result["result"])) + "\n"
439 | if reportpath:
440 | message = message + "\n" + "More details can be found in: " + reportpath + "\n"
441 | notify("pyCobaltHound - Computer report", message[:-1])
442 |
443 |
444 | # Neo4j connection test
445 | def connection_test():
446 | query = "MATCH (n:Domain) RETURN n"
447 | r = do_sync_cypher(query)
448 |
449 | if r:
450 | j = json.loads(r.text)
451 | if r.status_code != requests.codes.ok:
452 | if r.status_code in("400", "401"):
453 | engine.error("Neo4j connection failed: " + j["errors"][0]["message"])
454 | return False
455 | else:
456 | engine.error("Neo4j connection failed: unspecified failure")
457 | engine.error(r.text)
458 | return False
459 | else:
460 | engine.message("Neo4j connection succeeded")
461 | return True
462 | else:
463 | return False
464 |
465 | def connection_test_wrapper():
466 | if connection_test():
467 | return True
468 | else:
469 | aggressor.show_error("Could not connect to Neo4j, check your credentials and URL")
470 | return False
471 |
472 | # Main parsing and query logic
473 | def credential_action(credentials, event=True, report=True):
474 | engine.message("Investigation started!")
475 | if settings["sync_queries"]:
476 | load_queries()
477 | reportpath = ""
478 | if connection_test_wrapper():
479 | # Transforming data and checking validity
480 | domains = get_domains()
481 | valid_users = check_valid_realm(credentials, domains)
482 | if event:
483 | new_users = check_cache(valid_users)
484 | else:
485 | new_users = valid_users
486 | transformed_users = check_user_type(new_users)
487 |
488 | # Checking if the accounts exists in BloodHound
489 | existing_users = check_existence(transformed_users)
490 |
491 | if existing_users:
492 | # Marking the existing accounts as owned
493 | if event:
494 | mark_owned(existing_users)
495 |
496 | # Separate user and computer accounts
497 | user_accounts = [user for user in existing_users if user["type"] == "User"]
498 | computer_accounts = [user for user in existing_users if user["type"] == "Computer"]
499 |
500 | # Get enabled queries
501 | enabled_user_queries = [query for query in user_queries if query["enabled"] == "True"]
502 | enabled_computer_queries = [query for query in computer_queries if query["enabled"] == "True"]
503 |
504 | # Perform queries
505 | user_queries_results = asyncio.run(do_async_queries(enabled_user_queries, user_accounts))
506 | computer_queries_results = asyncio.run(do_async_queries(enabled_computer_queries, computer_accounts))
507 |
508 | # Parse results
509 | user_results = parse_results(enabled_user_queries, user_queries_results)
510 | computer_results = parse_results(enabled_computer_queries, computer_queries_results)
511 |
512 | # Report results
513 | if report:
514 | if settings["report"]:
515 | reportpath = generate_report(user_results, computer_results)
516 | if settings["notify"]:
517 | notify_operator(user_results, computer_results, reportpath)
518 | engine.message("Investigation ended!")
519 |
520 | # define aggressor menu and callbacks
521 | # wipe cache menu
522 | def wipe_cache(values):
523 | if os.path.exists(cache_location):
524 | os.remove(cache_location)
525 | aggressor.show_message("Cache wiped!")
526 | else:
527 | aggressor.show_error("No cache found")
528 |
529 | def wipe_cache_dialog():
530 | aggressor.prompt_confirm("Are you sure you want to wipe the cache? If you do so, pyCobaltHound will query every compromised user again upon its next run", "Wipe cache", wipe_cache)
531 |
532 | # re-evaluate menu
533 | def reevaluate():
534 | aggressor.fireEvent("credentials", aggressor.credentials())
535 |
536 | # investigate menu
537 | def investigate(dialog, button_name, values):
538 | targets = []
539 | parsed_targets = values["targets"].split(",")
540 |
541 | if values["domain_included"] == "Yes":
542 | for target in parsed_targets:
543 | entity = (target.strip()).upper()
544 | targets.append({"user": entity.partition("@")[0], "realm": entity.partition("@")[2]})
545 | else:
546 | for target in parsed_targets:
547 | entity = (target.strip()).upper()
548 | targets.append({"user": entity, "realm": values["domain"]})
549 |
550 | if values["report"] == "true":
551 | report = True
552 | else:
553 | report = False
554 |
555 | credential_action(targets, False, report)
556 |
557 | def investigate_dialog():
558 | drows = {
559 | "targets": "user1, user2, user3",
560 | "domain_included": "No",
561 | "domain": "CONTOSO.LOCAL",
562 | "report": "false"
563 | }
564 |
565 | domains = get_domains()
566 | dialog = aggressor.dialog("Investigate", drows, investigate)
567 | aggressor.dialog_description(dialog, "Investigate entities")
568 | aggressor.drow_text_big(dialog, "targets", "Targets")
569 | aggressor.drow_combobox(dialog, "domain_included", "Domain included", ["Yes", "No"])
570 | aggressor.drow_combobox(dialog, "domain", "Domain", domains)
571 | aggressor.drow_checkbox(dialog, "report", "Generate a report")
572 | aggressor.dbutton_action(dialog, "Investigate")
573 | aggressor.dialog_show(dialog)
574 |
575 | # settings menu
576 | def aggressor_empty_callback():
577 | engine.debug("")
578 |
579 | def enable_query_sync_dialog():
580 | if os.path.exists(os.path.realpath(os.path.dirname(__file__)) + "/queries/user-queries-" + str(unique_id) + ".json") or os.path.exists(os.path.realpath(os.path.dirname(__file__)) + "/queries/computer-queries-" + str(unique_id) + ".json"):
581 | message = "Unique query files detected, what do you want to do?"
582 | drows = {}
583 | dialog = aggressor.dialog("Enable query sync", drows, enable_query_sync)
584 | aggressor.dialog_description(dialog, message)
585 | aggressor.dbutton_action(dialog, "Delete")
586 | aggressor.dbutton_action(dialog, "Merge")
587 | aggressor.dbutton_action(dialog, "Keep")
588 | aggressor.dialog_show(dialog)
589 |
590 | def update_settings(dialog, button_name, values):
591 | global settings
592 | auth = (base64.b64encode((values["username"] + ":" + values["password"]).encode("ascii"))).decode("utf-8")
593 | settings["headers"]["Authorization"] = auth
594 |
595 | settings["url"] = values["url"] + "/db/data/transaction/commit"
596 |
597 | if values["cachecheck"] == "Disabled":
598 | settings["ignore_cache"] = True
599 | else:
600 | settings["ignore_cache"] = False
601 |
602 | if values["notificationcheck"] == "Enabled":
603 | settings["notify"] = True
604 | else:
605 | settings["notify"] = False
606 |
607 | if values["reportcheck"] == "Enabled":
608 | settings["report"] = True
609 | else:
610 | settings["report"] = False
611 |
612 | if values["notifytype"] == "pyNotify" and check_notify2:
613 | settings["notifytype"] = "pyNotify"
614 | else:
615 | settings["notifytype"] = "Native"
616 |
617 | if values["sync_queries"] == "Enabled":
618 | settings["sync_queries"] = True
619 | enable_query_sync_dialog()
620 | else:
621 | settings["sync_queries"] = False
622 | disable_query_sync()
623 |
624 | ## Save settings
625 | if not os.path.isdir(os.path.realpath(os.path.dirname(__file__)) + "/settings"):
626 | os.makedirs(os.path.realpath(os.path.dirname(__file__)) + "/settings")
627 | try:
628 | engine.debug("Saving the settings to: " + settings_location)
629 | pickle.dump(settings, open(settings_location, "wb"))
630 | except OSError:
631 | engine.error("Could not save cache!")
632 |
633 | ## Test new settings (TODO: Make check blocking for update if creds are wrong)
634 | connection_test_wrapper()
635 |
636 | def update_settings_dialog():
637 | global settings
638 | drows = {
639 | "username": "neo4j",
640 | "password": "bloodhound",
641 | }
642 |
643 | drows["url"] = settings["url"][:-27]
644 | drows["notifytype"] = settings["notifytype"]
645 |
646 | # Overkill just because I want nice menus :D
647 | if settings["ignore_cache"]:
648 | drows["cachecheck"] = "Disabled"
649 | else:
650 | drows["cachecheck"] = "Enabled"
651 |
652 | if settings["notify"]:
653 | drows["notificationcheck"] = "Enabled"
654 | else:
655 | drows["notificationcheck"] = "Disabled"
656 |
657 | if settings["report"]:
658 | drows["reportcheck"] = "Enabled"
659 | else:
660 | drows["reportcheck"] = "Disabled"
661 |
662 | if settings["sync_queries"]:
663 | drows["sync_queries"] = "Enabled"
664 | else:
665 | drows["sync_queries"] = "Disabled"
666 |
667 | dialog = aggressor.dialog("pyCobaltHound settings", drows, update_settings)
668 | aggressor.dialog_description(dialog, "Update your pyCobaltHound settings")
669 | aggressor.drow_text(dialog, "username", "Neo4j username: ")
670 | aggressor.drow_text(dialog, "password", "Neo4j password: ")
671 | aggressor.drow_text(dialog, "url", "Neo4j URL (http://server:port)")
672 | aggressor.drow_combobox(dialog, "cachecheck", "Caching", ["Enabled", "Disabled"])
673 | aggressor.drow_combobox(dialog, "notificationcheck", "Notifications", ["Enabled", "Disabled"])
674 | aggressor.drow_combobox(dialog, "notifytype", "Notification method", ["Native", "pyNotify"])
675 | aggressor.drow_combobox(dialog, "reportcheck", "Reporting", ["Enabled", "Disabled"])
676 | aggressor.drow_combobox(dialog, "sync_queries", "Synchronize queries", ["Enabled", "Disabled"])
677 | aggressor.dbutton_action(dialog, "Update")
678 | aggressor.dialog_show(dialog)
679 |
680 | # query updating menu
681 | def update_queries(dialog, button_name, values):
682 | global user_queries
683 | global computer_queries
684 |
685 | if values["type"] == "User":
686 | engine.message("Updating user queries")
687 | queries = user_queries
688 | query_location = user_queries_location
689 |
690 | for query in queries:
691 | if values[query["name"]] == "Enabled":
692 | query["enabled"] = "True"
693 |
694 | else:
695 | query["enabled"] = "False"
696 |
697 | user_queries = queries
698 | write_json(user_queries, query_location)
699 | else:
700 | engine.message("Updating computer queries")
701 | queries = computer_queries
702 | query_location = computer_queries_location
703 |
704 | for query in queries:
705 | if values[query["name"]] == "Enabled":
706 | query["enabled"] = "True"
707 |
708 | else:
709 | query["enabled"] = "False"
710 |
711 | computer_queries = queries
712 | write_json(computer_queries, query_location)
713 |
714 | def update_queries_dialog(dialog, button_name, values):
715 | if settings["sync_queries"]:
716 | load_queries()
717 |
718 | predrows = []
719 | drows = {}
720 |
721 | if values["type"] == "User":
722 | queries = user_queries
723 | else:
724 | queries = computer_queries
725 |
726 | for query in queries:
727 | dict = {"name": query["name"], "enabled": query["enabled"]}
728 | predrows.append(dict)
729 |
730 | for predrow in predrows:
731 | # Overkill just because I want nice menus :D
732 | if predrow["enabled"] == "True":
733 | state = "Enabled"
734 | opposite = "Disabled"
735 | else:
736 | state = "Disabled"
737 | opposite = "Enabled"
738 |
739 | drows[predrow["name"]] = state
740 |
741 | dialog = aggressor.dialog("Query selection", drows, update_queries)
742 | for drow in drows:
743 |
744 | aggressor.drow_combobox(dialog, drow, drow, ["Enabled", "Disabled"])
745 |
746 | drows["type"] = values["type"]
747 | # Ugly hack to pass query type to the next function
748 | aggressor.drow_combobox(dialog, "type", "Query type", [values["type"]])
749 | aggressor.dbutton_action(dialog, "Update")
750 | aggressor.dialog_show(dialog)
751 |
752 | def update_queries_choice_dialog():
753 | drows = {
754 | "type": "User"
755 | }
756 |
757 | dialog = aggressor.dialog("Query selection", drows, update_queries_dialog)
758 | aggressor.dialog_description(dialog, "Which type of query do you want to update?")
759 | aggressor.drow_combobox(dialog, "type", "Query type", ["User", "Computer"])
760 | aggressor.dbutton_action(dialog, "Choose")
761 | aggressor.dialog_show(dialog)
762 |
763 | # add query menu
764 | def add_query(dialog, button_name, values):
765 | global user_queries
766 | global computer_queries
767 |
768 | if values["enabled"] == "Enabled":
769 | state = "True"
770 | else:
771 | state = "False"
772 |
773 | new_query = {
774 | "name": values["name"],
775 | "statement": values["statement"],
776 | "report": values["report"],
777 | "enabled": state,
778 | "custom": "True"
779 | }
780 |
781 | if values["type"] == "User":
782 | user_queries.append(new_query)
783 | write_json(user_queries, user_queries_location)
784 |
785 | if values["type"] == "Computer":
786 | computer_queries.append(new_query)
787 | write_json(computer_queries, computer_queries_location)
788 |
789 | def add_query_dialog():
790 | if settings["sync_queries"]:
791 | load_queries()
792 |
793 | drows = {
794 | "name": "name of your query",
795 | "statement": "{statement} MATCH (x) WHERE x.name STARTS WITH names [insert cypher] RETURN DISTINCT(x.name)",
796 | "report": "{number} entity(s) has/have a path to target.",
797 | "enabled": "Enabled",
798 | "type": "User",
799 | }
800 |
801 | dialog = aggressor.dialog("Add a custom query", drows, add_query)
802 | aggressor.dialog_description(dialog, "Fill in the required information")
803 | aggressor.drow_text(dialog, "name", "Name")
804 | aggressor.drow_text_big(dialog, "statement", "Cypher query")
805 | aggressor.drow_text(dialog, "report", "Report headline")
806 | aggressor.drow_combobox(dialog, "enabled", "Status", ["Enabled", "Disabled"])
807 | aggressor.drow_combobox(dialog, "type", "Query type", ["User", "Computer"])
808 | aggressor.dbutton_action(dialog, "Add")
809 | aggressor.dialog_show(dialog)
810 |
811 | # remove query menu
812 | def remove_query(dialog, button_name, values):
813 | global user_queries
814 | global computer_queries
815 |
816 | if values["type"] == "User":
817 | user_queries = [query for query in user_queries if not (query["custom"] == "True" and values[query["name"]] == "Delete")]
818 | write_json(user_queries, user_queries_location)
819 |
820 | if values["type"] == "Computer":
821 | computer_queries = [query for query in computer_queries if not (query["custom"] == "True" and values[query["name"]] == "Delete")]
822 | write_json(computer_queries, computer_queries_location)
823 |
824 | def remove_query_dialog(dialog, button_name, values):
825 | if settings["sync_queries"]:
826 | load_queries()
827 |
828 | drows = {}
829 | custom_query_exists = False
830 |
831 | if values["type"] == "User":
832 | queries = user_queries
833 | else:
834 | queries = computer_queries
835 |
836 | # check if there is a custom query defined
837 | for query in queries:
838 | if query["custom"] == "True":
839 | custom_query_exists = True
840 |
841 | if custom_query_exists:
842 | dialog = aggressor.dialog("Remove a custom query", drows, remove_query)
843 | aggressor.dialog_description(dialog, "Which query do you want to remove?")
844 | for query in queries:
845 | if query["custom"] == "True":
846 | drows[query["name"]] = "Keep"
847 | aggressor.drow_combobox(dialog, query["name"], query["name"], ["Keep", "Delete"])
848 | drows["type"] = values["type"]
849 | # Ugly hack to pass query type to the next function
850 | aggressor.drow_combobox(dialog, "type", "Query type", [values["type"]])
851 | aggressor.dbutton_action(dialog, "Delete")
852 | aggressor.dialog_show(dialog)
853 | else:
854 | aggressor.show_error("There are no custom " + values["type"].lower() + " queries to delete!")
855 |
856 | def remove_query_choice_dialog():
857 | drows = {
858 | "type": "User"
859 | }
860 |
861 | dialog = aggressor.dialog("Query selection", drows, remove_query_dialog)
862 | aggressor.dialog_description(dialog, "Which type of query do you want to remove?")
863 | aggressor.drow_combobox(dialog, "type", "Query type", ["User", "Computer"])
864 | aggressor.dbutton_action(dialog, "Choose")
865 | aggressor.dialog_show(dialog)
866 |
867 |
868 | # menu layout
869 | menu = gui.popup("pycobalthound", callback=aggressor_empty_callback, children=[
870 | gui.item("Investigate", callback=investigate_dialog),
871 | gui.item("Settings", callback=update_settings_dialog),
872 | gui.menu("Queries", children=[
873 | gui.item("Update queries", callback=update_queries_choice_dialog),
874 | gui.item("Add query", callback=add_query_dialog),
875 | gui.item("Remove query", callback=remove_query_choice_dialog)
876 | ]),
877 | gui.item("Wipe cache", callback=wipe_cache_dialog),
878 | gui.item("Reevaluate", callback=reevaluate)
879 | ])
880 |
881 | # define credentials menu and callbacks
882 | def credentials_empty_callback(values):
883 | engine.debug("")
884 |
885 | def update_cache_callback(values):
886 | keys = ["user", "realm"]
887 | parsed_users = []
888 | try:
889 | cached_users = pickle.load(open(cache_location, "rb"))
890 | engine.debug("Restored users from: " + cache_location)
891 |
892 | if cached_users:
893 | for user in values:
894 | parsed_users.append({key: user[key].upper() for key in keys})
895 |
896 | new_cached_users = [user for user in cached_users if not (user in parsed_users)]
897 | try:
898 | engine.debug("Saving the cache to: " + cache_location)
899 | pickle.dump(new_cached_users, open(cache_location, "wb"))
900 | except OSError:
901 | engine.error("Could not save cache!")
902 | except OSError:
903 | engine.debug("Could not find a cache file")
904 |
905 | credential_menu = gui.popup("credentials", callback=credentials_empty_callback, children=[
906 | gui.menu("pyCobaltHound", children=[
907 | gui.insert_menu("pyCobaltHound_top"),
908 | gui.item("Remove from cache", callback=update_cache_callback),
909 | ])
910 | ])
911 |
912 | # define beacons menu and callbacks
913 | def beacons_empty_callback(values):
914 | engine.debug("")
915 |
916 | def beacon_investigate(dialog, button_name, values):
917 | beacons = aggressor.beacons()
918 | target_beacons = values["beacons"]
919 | targets = []
920 | for beacon in beacons:
921 | user = ""
922 | computer = ""
923 | if (beacon["id"] in target_beacons):
924 | user = beacon["user"]
925 | computer = beacon["computer"]
926 |
927 | # Check if beacon is running as LA or SYSTEM
928 | if user == "SYSTEM *":
929 | system = True
930 | # This will exclude the "Administrator" DA in AD too, but I guess you don't need to investigate if you've got a high integrity beacon as that :)
931 | elif user == "Administrator *":
932 | system == True
933 | else:
934 | system = False
935 |
936 | # Format user/computer names
937 | if user[-1] == "*":
938 | user = user[:-2].upper()
939 | else:
940 | user = user.upper()
941 |
942 | computer = computer.upper() + "$"
943 |
944 | # Add to list of objects to be marked
945 | if values["investigate"] == "Both":
946 | if system:
947 | targets.append({"user": computer, "realm": values["domain"]})
948 | else:
949 | targets.append({"user": user, "realm": values["domain"]})
950 | targets.append({"user": computer, "realm": values["domain"]})
951 | if values["investigate"] == "User":
952 | targets.append({"user": user, "realm": values["domain"]})
953 | if values["investigate"] == "Computer":
954 | targets.append({"user": computer, "realm": values["domain"]})
955 |
956 | if values["report"] == "true":
957 | report = True
958 | else:
959 | report = False
960 |
961 | credential_action(targets, False, report)
962 |
963 | def beacon_investigate_dialog(values):
964 | drows = {
965 | "beacons": values,
966 | "investigate": "Both",
967 | "domain": "CONTOSO.LOCAL",
968 | "report": "false"
969 | }
970 |
971 | investigate = ["Both", "Both without logic", "User", "Computer"]
972 | domains = get_domains()
973 |
974 | dialog = aggressor.dialog("Investigate", drows, beacon_investigate)
975 | aggressor.dialog_description(dialog, "Investigate beacons")
976 | aggressor.drow_combobox(dialog, "investigate", "Investigate", investigate)
977 | aggressor.drow_combobox(dialog, "domain", "Domain", domains)
978 | aggressor.drow_checkbox(dialog, "report", "Generate a report")
979 | aggressor.dbutton_action(dialog, "Investigate")
980 | aggressor.dialog_show(dialog)
981 |
982 | def mark_owned_action(dialog, button_name, values):
983 | beacons = aggressor.beacons()
984 | owned_beacons = values["beacons"]
985 | targets = []
986 | for beacon in beacons:
987 | user = ""
988 | computer = ""
989 | if (beacon["id"] in owned_beacons):
990 |
991 | user = beacon["user"]
992 | computer = beacon["computer"]
993 |
994 | # Cobalt Strike shows high integrity beacons as "User *"
995 | if user[-1] == "*":
996 | admin = True
997 | else:
998 | admin = False
999 | # Check if beacon is running as LA or SYSTEM
1000 | if user == "SYSTEM *":
1001 | system = True
1002 | elif user == "Administrator *":
1003 | system == True
1004 | else:
1005 | system = False
1006 | # Format user/computer names
1007 | if user[-1] == "*":
1008 | user = user[:-2].upper()
1009 | else:
1010 | user = user.upper()
1011 |
1012 | computer = computer.upper() + "$"
1013 |
1014 | # Add to list of objects to be marked
1015 | if values["nodetype"] == "Both":
1016 | if system:
1017 | targets.append({"user": computer, "realm": values["domain"]})
1018 | elif admin:
1019 | targets.append({"user": user, "realm": values["domain"]})
1020 | targets.append({"user": computer, "realm": values["domain"]})
1021 | else:
1022 | targets.append({"user": user, "realm": values["domain"]})
1023 | if values["nodetype"] == "User":
1024 | targets.append({"user": user, "realm": values["domain"]})
1025 | if values["nodetype"] == "Computer":
1026 | targets.append({"user": computer, "realm": values["domain"]})
1027 |
1028 | # Mark targets as owned
1029 | transformed_users = check_user_type(targets)
1030 | existing_users = check_existence(transformed_users)
1031 | if existing_users:
1032 | mark_owned(existing_users)
1033 |
1034 | def mark_owned_dialog(values):
1035 | drows = {
1036 | "beacons": values,
1037 | "nodetype": "Both",
1038 | "domain": "CONTOSO.LOCAL"
1039 | }
1040 |
1041 | nodetypes = ["Both", "User", "Computer"]
1042 | domains = get_domains()
1043 |
1044 | dialog = aggressor.dialog("Mark as owned", drows, mark_owned_action)
1045 | aggressor.dialog_description(dialog, "Mark beacons as owned")
1046 | aggressor.drow_combobox(dialog, "nodetype", "Nodetype", nodetypes)
1047 | aggressor.drow_combobox(dialog, "domain", "Domain", domains)
1048 | aggressor.dbutton_action(dialog, "Mark")
1049 | aggressor.dialog_show(dialog)
1050 |
1051 | beacon_menu = gui.popup("beacon", callback=beacons_empty_callback, children=[
1052 | gui.menu("pyCobaltHound", children=[
1053 | gui.insert_menu("pyCobaltHound_top"),
1054 | gui.item("Mark as owned", callback=mark_owned_dialog),
1055 | gui.item("Investigate", callback=beacon_investigate_dialog)
1056 | ])
1057 | ])
1058 |
1059 | # register menus
1060 | gui.register(menu)
1061 | gui.register(credential_menu)
1062 | gui.register(beacon_menu)
1063 | aggressor.menubar("pyCobaltHound", "pycobalthound")
1064 |
1065 | # Reacting to the "on credentials" event in Cobalt Strike
1066 | @events.event("credentials")
1067 | def credential_action_wrapper(credentials):
1068 | credential_action(credentials)
1069 |
1070 | @events.event("test", official_only=False)
1071 | def test():
1072 | engine.message(user_queries)
1073 |
1074 |
1075 |
1076 | aggressor.fireEvent("init")
1077 |
1078 | # Read commands from cobaltstrike. must be called last
1079 | engine.loop()
1080 |
1081 |
--------------------------------------------------------------------------------