```
├── .gitignore
├── CONFIG.md
├── LICENSE
├── README.md
├── config/
├── analysis/
├── group.yaml
├── privilege_rights.yaml
├── registry.yaml
├── gpo_files.yaml
├── gpo_files_structure/
├── csv/
├── audit.yaml
├── inf/
├── gpttmpl.yaml
├── ini/
├── gpt.yaml
├── pol/
├── registry.yaml
├── xml/
├── DataSources.yaml
├── Devices.yaml
├── Drives.yaml
├── EnvironmentVariables.yaml
├── Files.yaml
├── FolderOptions.yaml
├── Folders.yaml
├── Groups.yaml
├── IniFiles.yaml
├── InternetSettings.yaml
├── NTServices.yaml
├── NetworkOptions.yaml
├── NetworkShareSettings.yaml
├── PowerOptions.yaml
├── Printers.yaml
├── Regional.yaml
├── RegistrySettings.yaml
├── ScheduledTasks.yaml
├── Shortcuts.yaml
├── StartMenuTaskbar.yaml
├── neo4j.yaml
├── well_known_groups.yaml
├── customqueries.json
├── example/
├── bloodhound_north_sevenkingdoms_local.zip
├── north.sevenkingdoms.local/
├── Policies/
├── {01635BDB-1096-436C-8152-F05E71EE45CB}/
├── GPT.INI
├── Machine/
├── Microsoft/
├── Windows NT/
├── SecEdit/
├── GptTmpl.inf
├── {0A85301F-7CE4-4391-8354-BA1AEAD44FFC}/
├── GPT.INI
├── Machine/
├── Microsoft/
├── Windows NT/
├── SecEdit/
├── GptTmpl.inf
├── {21246D99-1426-495B-9E8E-556ABDD81F94}/
├── GPT.INI
├── Machine/
├── Preferences/
├── Groups/
├── Groups.xml
├── {276AA65B-86AE-4557-8858-3BC1B2C0B384}/
├── GPT.INI
├── Machine/
├── Microsoft/
├── Windows NT/
├── SecEdit/
├── GptTmpl.inf
├── {31B2F340-016D-11D2-945F-00C04FB984F9}/
├── GPT.INI
├── MACHINE/
├── Microsoft/
├── Windows NT/
├── SecEdit/
├── GptTmpl.inf
├── {47D7A63A-7ACA-484D-A3EB-FF5A3B5D6EB8}/
├── GPT.INI
├── Machine/
├── Registry.pol
├── comment.cmtx
├── {57C13291-8AC5-41C8-A934-258CBD70A7B5}/
├── GPT.INI
├── Machine/
├── Microsoft/
├── Windows NT/
├── SecEdit/
├── GptTmpl.inf
├── {6AC1786C-016F-11D2-945F-00C04fB984F9}/
├── GPT.INI
├── MACHINE/
├── Microsoft/
├── Windows NT/
├── SecEdit/
├── GptTmpl.inf
├── {98FBDD11-FA06-4F54-9119-B56DB4C52B81}/
├── GPT.INI
├── Machine/
├── Registry.pol
├── comment.cmtx
├── {A62549D8-9E57-4ED8-B9C0-F513637BEFAD}/
├── GPT.INI
├── Machine/
├── Microsoft/
├── Windows NT/
├── SecEdit/
├── GptTmpl.inf
├── {A98BEB12-AE4E-41C5-8F81-C9E318EB5338}/
├── GPT.INI
├── Machine/
├── Microsoft/
├── Windows NT/
├── SecEdit/
├── GptTmpl.inf
├── {AFC8E3D9-4440-4D1C-A0CC-B3D15BDE3101}/
├── GPO.cmt
├── GPT.INI
├── Machine/
├── Registry.pol
├── User/
├── Registry.pol
├── {B3CB4A8C-8396-4F60-B66C-E66851B3B814}/
├── GPT.INI
├── Machine/
├── Preferences/
├── Groups/
├── Groups.xml
├── {B9D151CC-2846-4695-BB75-B9A5B0534C19}/
├── GPT.INI
├── Machine/
├── Microsoft/
├── Windows NT/
├── SecEdit/
├── GptTmpl.inf
├── {CCF6CAE3-E280-4109-8F9D-25461DBB5D67}/
├── GPT.INI
├── Machine/
├── Preferences/
├── Registry/
├── Registry.xml
├── {D083FBC6-8E4E-499F-A183-DCBB27C52A70}/
├── GPT.INI
├── {D6A342D8-0BB9-4F8C-8579-93DE5A07CFC0}/
├── GPT.INI
├── User/
├── Scripts/
├── psscripts.ini
├── scripts.ini
├── {FBA8ADDE-55DA-448C-87ED-FBFB185E3A8C}/
├── GPT.INI
├── User/
├── Preferences/
├── Groups/
├── Groups.xml
├── scripts/
├── script.ps1
├── secret.ps1
├── gpohound.py
├── gpohound/
├── __init__.py
├── __main__.py
├── analyser.py
├── analysers/
├── groups.py
├── privilege_rights.py
├── registry.py
├── core.py
├── enricher.py
├── parser.py
├── parsers/
├── csv_files.py
├── inf_files.py
├── ini_files.py
├── pol_files.py
├── xml_files.py
├── processor.py
├── processors/
├── group_membership.py
├── pol_registry.py
├── privilege_rights.py
├── registry_values.py
├── xml_groups.py
├── xml_registry.py
├── utils/
├── ad.py
├── bloodhound.py
├── utils.py
```
## /.gitignore
```gitignore path="/.gitignore"
.vscode/
refs/
**__pycache**
*.egg-info
build/
```
## /CONFIG.md
# Configuration
All configuration files for the tool are located in the `config/` directory. These files are written in YAML format.
## Custom Configuration
You can override any default configuration by placing a file with the same name in your GPOHound user configuration directory.
This path is resolved automatically using [`platformdirs.user_config_dir`](https://pypi.org/project/platformdirs/) and is platform-specific.
On Linux, the configuration directory will be `~/.config/gpohound`.
> The configuration folder is created if it does not exist.
To create a custom config:
1. Copy the desired file from `config/` (e.g., `config/gpo_files_structure/xml/ScheduledTasks.yaml`).
2. Paste it into your user config folder (e.g., `~/.config/gpohound/`).
3. Modify it to suit your preferences.
## Structure
The `config/gpo_file_structures/` directory contains configuration files that specify the structure and display format for each type of GPO file. To exclude specific sections or attributes from being parsed, simply comment out the corresponding lines in the YAML configuration.
### Examples
#### Default configuration
```yaml
General:
include:
attributes:
- Version
- displayName
```
#### Exclude a section
```yaml
General:
#include:
attributes:
- Version
- displayName
```
#### Exclude an attribute
```yaml
General:
include:
attributes:
#- Version
- displayName
```
> [!NOTE]
> For XML files, sections that are not defined in the structure will be included in the output by default.
## /LICENSE
``` path="/LICENSE"
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
```
## /README.md
# GPOHound
`GPOHound` is a tool for dumping and analysing Group Policy Objects (GPOs) extracted from the SYSVOL share.
It provides a structured, formalized format to help uncover misconfigurations, insecure settings, and privilege escalation paths in Active Directory environments.
The tool integrates with BloodHound's Neo4j database, using it as an LDAP-like source for Active Directory information while also enriching it by adding new relationships (edges) and node properties based on the analysis.
## Features
### Dump
- [x] Dumps GPOs in a structured JSON or tree format
- [x] Handles multiple domains
- [x] Resolves GPO names with GPO GUIDs
- [x] Filters output by GPO files, GPO GUIDs, and domains
- [x] Searches in key/value pairs using regex
### Analysis
- [x] Groups settings by impacted object (e.g., Local Groups, Registry)
- [x] Detects members added to local privileged groups
- [x] Detects insecure registry settings, stored credentials, and privilege rights
- [x] Supports decrypting VNC credentials and GPP passwords
- [x] Finds domains, containers, and OUs affected by GPOs
- [x] Gets GPOs applied to a specific user, computer, OU, container, or domain
- [x] Enriches BloodHound data with relationships and properties
## Installation
### Install with pip
```
git clone "https://github.com/cogiceo/GPOHound"
cd GPOHound
pip install .
```
### Install with pipx
```
pipx install "git+https://github.com/cogiceo/GPOHound"
```
### Setup APOC for Neo4j
You need to setup Neo4j APOC for BloodHound data enrichment. If you're using the standard Neo4j installation, you can enable APOC by copying the APOC `jar` file to the plugin folder and then restart Neo4j:
```bash
cp /var/lib/neo4j/labs/apoc-* /var/lib/neo4j/plugins/
neo4j restart
```
> For more details or alternate installation methods, refer to the official [APOC Documentation](https://neo4j.com/docs/apoc/current/installation/).
### Add BloodHound Queries
To visualize the relationships and properties added by `GPOHound`, you can import the custom queries from the `customqueries.json` file into BloodHound. By default, this file is located at `~/.config/bloodhound/customqueries.json`.
## Prerequisites
### Dumping SYSVOL
Start by downloading the `SYSVOL` contents from the domain controller. You can do this using `smbclient` or other tools:
```bash
smbclient -U "$USER"%"$PASS" //"$DC_IP"/SYSVOL -c "recurse; prompt; mget *;"
```
For a faster download, target only the GPOs :
```bash
mkdir -p "$DOMAIN"/Policies && cd "$DOMAIN"/Policies
smbclient -U "$USER"%"$PASS" //"$DC_IP"/SYSVOL -c "recurse; prompt; cd $DOMAIN/Policies/; mget {*};" && cd -
```
### BloodHound
To enable name resolution and data enrichment, you must collect BloodHound data using a collector such as `bloodhound.py` or `SharpHound.exe` and import the gathered data into the BloodHound interface.
## Usage
See [CONFIG.md](./CONFIG.md) for instructions on customizing default values and configurations
```bash
gpohound --neo4j-user $USER --neo4j-pass $PASS -S ./example dump
gpohound --neo4j-user $USER --neo4j-pass $PASS -S ./example analysis
```
### Dump
```bash
gpohound dump -h
gpohound dump --json
gpohound dump --list --gpo-name
gpohound dump --guid 21246D99-1426-495B-9E8E-556ABDD81F94
gpohound dump --file scripts psscripts
gpohound dump --search 'VNC.*Server' --show
```
### Analysis
```bash
gpohound analysis -h
gpohound analysis --json
gpohound analysis --processed --object group registry
gpohound analysis --guid CCF6CAE3-E280-4109-8F9D-25461DBB5D67 --affected
gpohound analysis --computer 'SRV-PA-03.NORTH.SEVENKINGDOMS.LOCAL' --order
gpohound analysis --enrich
```
## Current analysis and enrichment
> [!IMPORTANT]
> - Conditions like security filters, WMI filters, and item-level targeting are not interpreted.
> - GPO conflicts are not simulated, to avoid missing valid settings.
### Local Groups
- Detection of users assigned to privileged local groups during logon
- Detection of renamed built-in privileged local groups.
- Detection of trustees added to privileged local groups using system-defined variables (e.g., %ComputerName%, %DomainName%) for possible `sAMAccountName` spoofing
- Detection of any trustees added to privileged local groups:
| Group | Edge |
|--------------------------------|--------------|
| Administrators | `AdminTo` |
| Remote Desktop Users | `CanRDP` |
| Distributed COM Users | `ExecuteDCOM`|
| Remote Management Users | `CanPSRemote`|
| Backup Operators | `CanPrivEsc` |
| Print Operators | `CanPrivEsc` |
| Network Configuration Operators| `CanPrivEsc` |
### Registry
| Analysis | Property |
|--------------------------------------------------------------------------|---------------------------|
| "Everyone" group includes "Anonymous Logon" | — |
| SMB server session signing is not enabled | `smbSigningEnabled: false`|
| SMB server session signing is not required | `smbSigningRequired: false`|
| NTLMv1 authentication is supported | `NTLMv1Support: true` |
| Windows automatic logon default password | — |
| VNC credentials (Generic: RealVNC, TightVNC, TigerVNC, etc.) | `*VNC*PASS*` (various) |
| FileZilla stored passwords | — |
| PuTTY proxy password | — |
| TeamViewer stored credentials | — |
| WinSCP saved sessions | — |
| Picasa stored password | — |
### Privileged Rights
Default privileged trustees, as well as service accounts with SIDs starting with `S-1-5-8`, are excluded from analysis.
| Privilege | Description | Edge |
|---------------------------------|--------------------------------------------------------|--------------|
| SeDebugPrivilege | Allows user to debug and interact with any process | `CanPrivEsc` |
| SeBackupPrivilege | Grants access to sensitive files | `CanPrivEsc` |
| SeRestorePrivilege | Bypasses object permissions during restore | `CanPrivEsc` |
| SeAssignPrimaryTokenPrivilege | Enables token impersonation for SYSTEM escalation | `CanPrivEsc` |
| SeImpersonatePrivilege | Allows creation of process under another user’s context| `CanPrivEsc` |
| SeTakeOwnershipPrivilege | Lets users take ownership of system objects | `CanPrivEsc` |
| SeTcbPrivilege | Grants the ability to act as part of the OS | `CanPrivEsc` |
| SeCreateTokenPrivilege | Permits creation of authentication tokens | `CanPrivEsc` |
| SeLoadDriverPrivilege | Authorizes driver loading/unloading | `CanPrivEsc` |
| SeManageVolumePrivilege | Grants volume or disk management privileges | `CanPrivEsc` |
# Improvement
- [ ] Improve logging
- [ ] HTML output
- [ ] Integrate LDAP
- [ ] Integrate SMB
- [ ] Highlight potential conflicts between GPOs
- [ ] Parse remaining extensions
## GPO Documentation
### SYSVOL and LDAP
- [x] [\[MS-GPAC\]](https://learn.microsoft.com/en-us/openspecs/windows_protocols/MS-GPAC/) Audit Configuration Extension
- [ ] [\[MS-GPCAP\]](https://learn.microsoft.com/en-us/openspecs/windows_protocols/MS-GPCAP/) Central Access Policies Protocol Extension
- [x] [\[MS-GPEF\]](https://learn.microsoft.com/en-us/openspecs/windows_protocols/MS-GPEF/) Encrypting File System Extension
- [x] [\[MS-GPFAS\]](https://learn.microsoft.com/en-us/openspecs/windows_protocols/MS-GPFAS/) Firewall and Advanced Security Data Structure
- [ ] [\[MS-GPIE\]](https://learn.microsoft.com/en-us/openspecs/windows_protocols/MS-GPIE/) Internet Explorer Maintenance Extension
- [x] [\[MS-GPNAP\]](https://learn.microsoft.com/en-us/openspecs/windows_protocols/MS-GPNAP/) Network Access Protection (NAP) Extension
- [x] [\[MS-GPNRPT\]](https://learn.microsoft.com/en-us/openspecs/windows_protocols/MS-GPNRPT/) Name Resolution Policy Table (NRPT) Data Extension
- [x] [\[MS-GPOL\]](https://learn.microsoft.com/en-us/openspecs/windows_protocols/MS-GPOL/) Core Protocol
- [x] [\[MS-GPPREF\]](https://learn.microsoft.com/en-us/openspecs/windows_protocols/MS-GPPREF/) Preferences Extension Data Structure
- [x] [\[MS-GPREG\]](https://learn.microsoft.com/en-us/openspecs/windows_protocols/MS-GPREG/) Registry Extension Encoding
- [x] [\[MS-GPSB\]](https://learn.microsoft.com/en-us/openspecs/windows_protocols/MS-GPSB/) Security Protocol Extension
- [x] [\[MS-GPSCR\]](https://learn.microsoft.com/en-us/openspecs/windows_protocols/MS-GPSCR/) Scripts Extension Encoding
- [ ] [\[MS-GPSI\]](https://learn.microsoft.com/en-us/openspecs/windows_protocols/MS-GPSI/) Software Installation Protocol Extension
## LDAP Only
- [\[MS-GPDPC\]](https://learn.microsoft.com/en-us/openspecs/windows_protocols/MS-GPDPC/) Deployed Printer Connections Extension
- [\[MS-GPFR\]](https://learn.microsoft.com/en-us/openspecs/windows_protocols/MS-GPFR/) Folder Redirection Protocol Extension
- [\[MS-GPWL\]](https://learn.microsoft.com/en-us/openspecs/windows_protocols/MS-GPWL/) Wireless/Wired Protocol Extension
## /config/analysis/group.yaml
```yaml path="/config/analysis/group.yaml"
S-1-5-32-544:
name : "Administrators"
sid : "S-1-5-32-544"
edge : "AdminTo"
edge_reference: "https://bloodhound.specterops.io/resources/edges/admin-to"
S-1-5-32-555:
name : "Remote Desktop Users"
sid : "S-1-5-32-555"
edge : "CanRDP"
edge_reference: "https://bloodhound.specterops.io/resources/edges/can-rdp"
S-1-5-32-562:
name : "Distributed COM Users"
sid : "S-1-5-32-562"
edge : "ExecuteDCOM"
edge_reference: "https://bloodhound.specterops.io/resources/edges/execute-dcom"
S-1-5-32-580:
name : "Remote Management Users"
sid : "S-1-5-32-580"
edge : "CanPSRemote"
edge_reference: "https://bloodhound.specterops.io/resources/edges/can-ps-remote"
S-1-5-32-551:
name : "Backup Operators"
sid : "S-1-5-32-551"
edge : "CanPrivEsc"
edge_reference: "https://www.bordergate.co.uk/backup-operator-privilege-escalation/"
S-1-5-32-550:
name : "Print Operators"
sid : "S-1-5-32-550"
edge : "CanPrivEsc"
edge_reference: "https://github.com/dollarboysushil/oscp-cpts-notes/blob/main/windows-privilege-escalation/group-privileges/print-operators.md"
S-1-5-32-556:
name : "Network Configuration Operators"
sid : "S-1-5-32-556"
edge : "CanPrivEsc"
edge_reference: "https://birkep.github.io/posts/Windows-LPE/?s=03#network-configuration-operators"
```
## /config/analysis/privilege_rights.yaml
```yaml path="/config/analysis/privilege_rights.yaml"
# Default trustees are based on the join groups values in "Default values" of the "User Rights Assignment" documentation
# https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-10/security/threat-protection/security-policy-settings/user-rights-assignment
SeDebugPrivilege:
analysis : "SeDebugPrivilege: Allows a user to debug and interact with any process running on the system"
default_trutees:
- S-1-5-32-544
edge : CanPrivEsc
references: https://gtworek.github.io/Priv2Admin/
SeBackupPrivilege:
analysis : "SeBackupPrivilege : Allows a user to access sensitive files"
default_trutees:
- S-1-5-32-544
- S-1-5-32-551
- S-1-5-32-549
edge : CanPrivEsc
references: https://gtworek.github.io/Priv2Admin/SeBackupPrivilege.html
SeManageVolumePrivilege:
analysis : "SeManageVolumePrivilege : Allows a user to perform volume or disk management tasks"
default_trutees:
- S-1-5-32-544
edge : CanPrivEsc
references: https://gtworek.github.io/Priv2Admin/
SeAssignPrimaryTokenPrivilege:
analysis : 'SeAssignPrimaryTokenPrivilege: Allows a user to impersonate tokens and escalate privilege to "NT AUTHORITY\SYSTEM" '
default_trutees:
- S-1-5-32-544
- S-1-5-20
- S-1-5-19
edge : CanPrivEsc
references: https://gtworek.github.io/Priv2Admin/
SeImpersonatePrivilege:
analysis : "SeImpersonatePrivilege : Allows a user to create a process under the security context of another user"
default_trutees:
- S-1-5-32-544
- S-1-5-19
- S-1-5-20
- S-1-5-6
edge : CanPrivEsc
references: https://gtworek.github.io/Priv2Admin/
SeRestorePrivilege:
analysis : "SeRestorePrivilege : Allows a users to bypass file, directory, registry, and other persistent object permissions when they restore backed up files and directories"
default_trutees:
- S-1-5-32-544
- S-1-5-32-551
- S-1-5-32-549
edge : CanPrivEsc
references: https://gtworek.github.io/Priv2Admin/
SeTakeOwnershipPrivilege:
analysis : "SeTakeOwnershipPrivilege : Allows users to take ownership of objects, such as Active Directory objects, NTFS files and folders, printers, registry keys, services, processes, and threads"
default_trutees:
- S-1-5-32-544
edge : CanPrivEsc
references: https://gtworek.github.io/Priv2Admin/
SeTcbPrivilege:
analysis : "SeTcbPrivilege : Determines whether a process can assume the identity of any user and thereby gain access to the resources that the user is authorized to access"
edge : CanPrivEsc
references: https://gtworek.github.io/Priv2Admin/
SeCreateTokenPrivilege:
analysis : "SeCreateTokenPrivilege : Determines which accounts a process can use to create a token"
default_trutees:
- S-1-5-18
edge : CanPrivEsc
references: https://gtworek.github.io/Priv2Admin/
SeLoadDriverPrivilege:
analysis : "SeLoadDriverPrivilege : Allows a user to dynamically load and unload device drivers"
default_trutees:
- S-1-5-32-544
- S-1-5-32-550
edge : CanPrivEsc
references: https://gtworek.github.io/Priv2Admin/
```
## /config/analysis/registry.yaml
```yaml path="/config/analysis/registry.yaml"
- analysis : |-
The "Everyone" group includes the "Anonymous Logon" group.
Try to authenticate with any username and an empty password
key : 'System\CurrentControlSet\Control\Lsa\EveryoneIncludesAnonymous'
condition : value_equals
value : 1
references: https://learn.microsoft.com/en-us/windows-server/identity/ad-ds/manage/understand-special-identities-groups#everyone
- analysis : 'SMB server session signing is not enabled'
bloodhound_property :
smbSigningEnabled : false
key : 'System\CurrentControlSet\Services\LanmanServer\Parameters\EnableSecuritySignature'
condition : value_equals
value : 0
references: https://www.thehacker.recipes/ad/movement/ntlm/relay
- analysis : 'SMB server session signing is not required'
bloodhound_property :
smbSigningRequired : false
key : 'System\CurrentControlSet\Services\LanmanServer\Parameters\RequireSecuritySignature'
condition : value_equals
value : 0
references: https://www.thehacker.recipes/ad/movement/ntlm/relay
- analysis : 'NTLMv1 authentication is supported allowing authentication downgrade and LDAP relay'
bloodhound_property :
NTLMv1Support : true
key : 'System\CurrentControlSet\Control\Lsa\LmCompatibilityLevel'
condition : value_less_than
value : 3
references: https://trustedsec.com/blog/practical-attacks-against-ntlmv1
- analysis : 'Windows automatic logon default password'
key : SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\DefaultPassword
condition : key_ends_with
references: https://learn.microsoft.com/en-us/troubleshoot/windows-server/user-profiles-and-logon/turn-on-automatic-logon
- analysis : 'VNC credentials'
key : 'Software\ORL\WinVNC3\Password'
condition : key_ends_with
decrypt: VNC
references: https://whatsoftware.com/crack-or-decrypt-vnc-server-encrypted-password/
- analysis : 'VNC credentials'
key : 'Software\ORL\WinVNC\Default\Password'
condition : key_ends_with
decrypt: VNC
references: https://whatsoftware.com/crack-or-decrypt-vnc-server-encrypted-password/
- analysis : 'VNC credentials'
bloodhound_property : "VNC Password"
key : 'Software\ORL\WinVNC3\Password'
condition : key_ends_with
decrypt: VNC
references: https://whatsoftware.com/crack-or-decrypt-vnc-server-encrypted-password/
- analysis : 'VNC credentials'
bloodhound_property : "VNC Default Password"
key : 'Software\ORL\WinVNC3\Default\Password'
condition : key_ends_with
decrypt: VNC
references: https://whatsoftware.com/crack-or-decrypt-vnc-server-encrypted-password/
- analysis : 'RealVNC Server credentials'
bloodhound_property : "RealVNC Password"
key : 'Software\RealVNC\WinVNC4\Password'
condition : key_ends_with
decrypt: VNC
references: https://github.com/frizb/PasswordDecrypts
- analysis : 'RealVNC Server credentials'
bloodhound_property : "RealVNC Default Password"
key : 'Software\RealVNC\WinVNC4\Default\Password'
condition : key_ends_with
decrypt: VNC
references: https://github.com/frizb/PasswordDecrypts
- analysis : 'TightVNC Server "primary" password used for accessing remote session'
bloodhound_property : "TightVNC Primary Password"
key : 'Software\TightVNC\Server\Password'
condition : key_ends_with
decrypt: VNC
references: https://github.com/frizb/PasswordDecrypts
- analysis : 'TightVNC Server "administrative" password'
bloodhound_property : "TightVNC Control Password"
key : 'Software\TightVNC\Server\ControlPassword'
condition : key_ends_with
decrypt: VNC
references: https://github.com/frizb/PasswordDecrypts
- analysis : 'TightVNC Server view-only remote session password'
bloodhound_property : "TightVNC View Only Password"
key : 'Software\TightVNC\Server\PasswordViewOnly'
condition : key_ends_with
decrypt: VNC
references: https://github.com/frizb/PasswordDecrypts
- analysis : 'TigerVNC Server password'
bloodhound_property : "TigerVNC Password"
key : 'Software\TigerVNC\WinVNC4\Password'
condition : key_ends_with
decrypt: VNC
references: https://github.com/frizb/PasswordDecrypts
- analysis : 'FileZilla Server password'
key : 'Software\\FileZilla\\Site Manager\\.*\\Pass'
condition : key_regex
- analysis : 'FileZilla Server password'
key : 'SOFTWARE\\Wow6432Node\\FileZilla Server\\.*\\Pass'
condition : key_regex
- analysis : 'PuTTY Proxy password'
key : 'Software\SimonTatham\PuTTY\Sessions\ProxyPassword'
condition : key_ends_with
- analysis : 'TeamViewer Stored Credentials'
key : 'Software\\WOW6432Node\\TeamViewer\\.*Password'
condition : key_regex
- analysis : 'WinSCP Sessions'
key : 'Software\Software\Martin Prikryl\WinSCP 2\Sessions'
condition : key_ends_with
- analysis : "Picasa stored password"
key : 'Software\Google\Picasa\Picasa2\Preferences\GaiaPass'
condition : key_ends_with
```
## /config/gpo_files.yaml
```yaml path="/config/gpo_files.yaml"
gpt: GPT.ini
gptemplate: GptTmpl.inf
scripts : scripts.ini
psscripts : PSscripts.ini
eventscripts: gposcripts
groups: Groups.xml
registry.pol: registry.pol
audit: audit.csv
datasources: DataSources.xml
devices: Devices.xml
drives: Drives.xml
env: EnvironmentVariables.xml
files: Files.xml
folderoptions: FolderOptions.xml
folders: Folders.xml
inifiles: IniFiles.xml
internetsettings: InternetSettings.xml
networkoptions: NetworkOptions.xml
networkshares: NetworkShares.xml
poweroptions: PowerOptions.xml
printers: Printers.xml
regional: RegionalOptions.xml
registry: Registry.xml
scheduledtasks: ScheduledTasks.xml
services: Services.xml
shortcuts: Shortcuts.xml
startmenu: StartMenuTaskbar.xml
```
## /config/gpo_files_structure/csv/audit.yaml
```yaml path="/config/gpo_files_structure/csv/audit.yaml"
Audit:
include:
attributes:
- Machine Name
- Policy Target
- Subcategory
- Subcategory GUID
- Inclusion Setting
- Exclusion Setting
- Setting Value
```
## /config/gpo_files_structure/inf/gpttmpl.yaml
```yaml path="/config/gpo_files_structure/inf/gpttmpl.yaml"
Unicode:
type : key-value
include:
attributes:
- Unicode
Version:
type : key-value
include:
attributes:
- signature
- Revision
System Access:
type : key-value
include:
attributes:
- MinimumPasswordAge
- MaximumPasswordAge
- MinimumPasswordLength
- PasswordComplexity
- PasswordHistorySize
- ClearTextPassword
- RequireLogonToChangePassword
- LockoutBadCount
- ResetLockoutCount
- LockoutDuration
- ForceLogoffWhenHourExpire
- LSAAnonymousNameLookup
- EnableAdminAccount
- EnableGuestAccount
- NewAdministratorName
- NewGuestName
Kerberos Policy:
type : key-value
include:
attributes:
- MaxTicketAge
- MaxRenewAge
- MaxServiceAge
- MaxClockSkew
- TicketValidateClient
System Log:
type : key-value
include:
attributes:
- MaximumLogSize
- AuditLogRetentionPeriod
- RetentionDays
- RestrictGuestAccess
Security Log:
type : key-value
include:
attributes:
- MaximumLogSize
- AuditLogRetentionPeriod
- RetentionDays
- RestrictGuestAccess
Application Log:
type : key-value
include:
attributes:
- MaximumLogSize
- AuditLogRetentionPeriod
- RetentionDays
- RestrictGuestAccess
Event Audit:
type : key-value
include:
attributes:
- AuditSystemEvents
- AuditLogonEvents
- AuditPrivilegeUse
- AuditPolicyChange
- AuditAccountManage
- AuditProcessTracking
- AuditDSAccess
- AuditObjectAccess
- AuditAccountLogon
Registry Values:
type : key-value
include:
attributes:
- Hive
- Type
- Data
Privilege Rights:
type : key-value
include:
attributes:
- SeNetworkLogonRight
- SeTcbPrivilege
- SeMachineAccountPrivilege
- SeIncreaseQuotaPrivilege
- SeRemoteInteractiveLogonRight
- SeBackupPrivilege
- SeChangeNotifyPrivilege
- SeCreatePagefilePrivilege
- SeSystemtimePrivilege
- SeCreateTokenPrivilege
- SeCreateGlobalPrivilege
- SeCreatePermanentPrivilege
- SeDebugPrivilege
- SeDenyNetworkLogonRight
- SeDenyBatchLogonRight
- SeDenyServiceLogonRight
- SeDenyInteractiveLogonRight
- SeDenyRemoteInteractiveLogonRight
- SeEnableDelegationPrivilege
- SeRemoteShutdownPrivilege
- SeAuditPrivilege
- SeImpersonatePrivilege
- SeIncreaseBasePriorityPrivilege
- SeLoadDriverPrivilege
- SeLockMemoryPrivilege
- SeBatchLogonRight
- SeServiceLogonRight
- SeInteractiveLogonRight
- SeSecurityPrivilege
- SeSystemEnvironmentPrivilege
- SeManageVolumePrivilege
- SeProfileSingleProcessPrivilege
- SeSystemProfilePrivilege
- SeUndockPrivilege
- SeAssignPrimaryTokenPrivilege
- SeRestorePrivilege
- SeShutdownPrivilege
- SeSyncAgentPrivilege
- SeTakeOwnershipPrivilege
- SeTrustedCredManAccessPrivilege
- SeTimeZonePrivilege
- SeCreateSymbolicLinkPrivilege
- SeIncreaseWorkingSetPrivilege
- SeRelabelPrivilege
Registry Keys:
type : comma-separated
include:
attributes:
- PermPropagationMode
- AclString
Service General Setting:
type : comma-separated
include:
attributes:
- AclString
- StartupMode
File Security:
type : comma-separated
include:
attributes:
- PermPropagationMode
- AclString
Group Membership:
type : key-value
include:
attributes:
- Members
- Memberof
```
## /config/gpo_files_structure/ini/gpt.yaml
```yaml path="/config/gpo_files_structure/ini/gpt.yaml"
General:
include:
attributes:
- Version
- displayName
```
## /config/gpo_files_structure/pol/registry.yaml
```yaml path="/config/gpo_files_structure/pol/registry.yaml"
REG_NONE:
include:
attributes:
- Hive
- Type
- Size
- Data
REG_SZ:
include:
attributes:
- Hive
- Type
- Size
- Data
REG_EXPAND_SZ:
include:
attributes:
- Hive
- Type
- Size
- Data
REG_BINARY:
include:
attributes:
- Hive
- Type
- Size
- Data
REG_DWORD:
include:
attributes:
- Hive
- Type
- Size
- Data
REG_DWORD_BIG_ENDIAN:
include:
attributes:
- Hive
- Type
- Size
- Data
REG_LINK:
include:
attributes:
- Hive
- Type
- Size
- Data
REG_MULTI_SZ:
include:
attributes:
- Hive
- Type
- Size
- Data
REG_RESOURCE_LIST:
include:
attributes:
- Hive
- Type
- Size
- Data
REG_FULL_RESOURCE_DESCRIPTOR:
include:
attributes:
- Hive
- Type
- Size
- Data
REG_RESOURCE_REQUIREMENTS_LIST:
include:
attributes:
- Hive
- Type
- Size
- Data
REG_QWORD:
include:
attributes:
- Hive
- Type
- Size
- Data
```
## /config/gpo_files_structure/xml/DataSources.yaml
```yaml path="/config/gpo_files_structure/xml/DataSources.yaml"
DataSources:
include:
attributes:
- clsid
- disabled
elements:
DataSource:
include:
attributes:
- clsid
- name
- image
- bypassErrors
- userContext
- removePolicy
- desc
- changed
- uid
elements:
Filters:
include:
Properties:
include:
attributes:
- action
- userDSN
- dsn
- driver
- description
- username
- cpassword
- disabled
elements:
Attributes:
include:
elements:
Attribute:
include:
attributes:
- name
- value
```
## /config/gpo_files_structure/xml/Devices.yaml
```yaml path="/config/gpo_files_structure/xml/Devices.yaml"
Devices:
include:
attributes:
- clsid
- disabled
elements:
Device:
include:
attributes:
- clsid
- name
- image
- changed
- uid
- desc
- bypassErrors
- userContext
- removePolicy
elements:
Properties:
include:
attributes:
- deviceAction
- deviceClass
- deviceType
- deviceClassGUID
- deviceTypeID
- disabled
```
## /config/gpo_files_structure/xml/Drives.yaml
```yaml path="/config/gpo_files_structure/xml/Drives.yaml"
Drives:
include:
attributes:
- clsid
- disabled
elements:
Drive:
include:
attributes:
- clsid
- name
- image
- changed
- uid
- desc
- bypassErrors
- userContext
- removePolicy
elements:
Properties:
include:
attributes:
- action
- thisDrive
- allDrives
- userName
- cpassword
- path
- label
- persistent
- useLetter
- letter
- disabled
```
## /config/gpo_files_structure/xml/EnvironmentVariables.yaml
```yaml path="/config/gpo_files_structure/xml/EnvironmentVariables.yaml"
EnvironmentVariables:
include:
attributes:
- clsid
- disabled
elements:
EnvironmentVariable:
include:
attributes:
- clsid
- name
- image
- changed
- uid
- desc
- bypassErrors
- userContext
- removePolicy
elements:
Properties:
include:
attributes:
- action
- name
- value
- user
- partial
- disabled
```
## /config/gpo_files_structure/xml/Files.yaml
```yaml path="/config/gpo_files_structure/xml/Files.yaml"
Files:
include:
attributes:
- clsid
- disabled
elements:
File:
include:
attributes:
- clsid
- name
- image
- changed
- uid
- desc
- bypassErrors
- userContext
- removePolicy
elements:
Properties:
include:
attributes:
- action
- fromPath
- targetPath
- readOnly
- archive
- hidden
- suppress
- disabled
```
## /config/gpo_files_structure/xml/FolderOptions.yaml
```yaml path="/config/gpo_files_structure/xml/FolderOptions.yaml"
FolderOptions:
include:
attributes:
- clsid
- disabled
elements:
FileType:
include:
attributes:
- clsid
- name
- image
- changed
- uid
- desc
- bypassErrors
- userContext
- removePolicy
elements:
Properties:
include:
attributes:
- action
- fileExt
- application
- appProgID
- configActions
- iconPath
- iconIndex
- confirmOpen
- alwaysShow
- sameWindow
- name
- appUsed
- default
- useDDE
- ddeMessage
- ddeApplication
- ddeAppNotRunning
- ddeTopic
- disabled
GlobalFolderOptions:
include:
attributes:
- clsid
- image
- name
- changed
- uid
- desc
- bypassErrors
- userContext
- removePolicy
elements:
Filters:
include:
Properties:
include:
attributes:
- noNetCrawling
- folderContentsInfoTip
- friendlyTree
- fullPathAddress
- fullPath
- disableThumbnailCache
- hidden
- hideFileExt
- separateProcess
- showSuperHidden
- classicViewState
- persistBrowsers
- showControlPanel
- showCompColor
- showInfoTip
- forceGuest
- webViewBarricade
- disabled
GlobalFolderOptionsVista:
include:
attributes:
- clsid
- image
- name
- changed
- uid
- desc
- bypassErrors
- userContext
- removePolicy
elements:
Filters:
include:
Properties:
include:
attributes:
- alwaysShowIcons
- alwaysShowMenus
- displayIconThumb
- displayFileSize
- displaySimpleFolders
- fullPath
- hidden
- hideFileExt
- showSuperHidden
- separateProcess
- classicViewState
- persistBrowsers
- showDriveLetter
- showCompColor
- showInfoTip
- showPreviewHandlers
- useCheckBoxes
- useSharingWizard
- listViewTyping
- disabled
OpenWith:
include:
attributes:
- clsid
- name
- image
- changed
- uid
- desc
- bypassErrors
- userContext
- removePolicy
elements:
Properties:
include:
attributes:
- action
- fileExtension
- applicationPath
- default
- disabled
```
## /config/gpo_files_structure/xml/Folders.yaml
```yaml path="/config/gpo_files_structure/xml/Folders.yaml"
Folders:
include:
attributes:
- clsid
- disabled
elements:
Folder:
include:
attributes:
- clsid
- name
- status
- image
- changed
- uid
- desc
- bypassErrors
- userContext
- removePolicy
elements:
Properties:
include:
attributes:
- action
- path
- readOnly
- archive
- hidden
- deleteSubFolders
- deleteFiles
- deleteFolder
- deleteReadOnly
- deleteIgnoreErrors
- disabled
```
## /config/gpo_files_structure/xml/Groups.yaml
```yaml path="/config/gpo_files_structure/xml/Groups.yaml"
Groups:
include:
attributes:
- clsid
- disabled
elements:
Group:
include:
attributes:
- clsid
- name
- image
- changed
- uid
- desc
- bypassErrors
- userContext
- removePolicy
elements:
Properties:
include:
attributes:
- action
- newName
- description
- userAction
- deleteAllUsers
- deleteAllGroups
- removeAccounts
- groupName
- groupSid
- disabled
elements:
Members:
include:
elements:
Member:
include:
attributes:
- name
- action
- sid
User:
include:
attributes:
- clsid
- name
- image
- changed
- uid
- desc
- bypassErrors
- userContext
- removePolicy
elements:
Properties:
include:
attributes:
- action
- newName
- fullName
- description
- cpassword
- changeLogon
- noChange
- neverExpires
- acctDisabled
- userName
- expires
```
## /config/gpo_files_structure/xml/IniFiles.yaml
```yaml path="/config/gpo_files_structure/xml/IniFiles.yaml"
IniFiles:
include:
attributes:
- clsid
- disabled
elements:
Ini:
include:
attributes:
- clsid
- name
- status
- image
- changed
- uid
- desc
- bypassErrors
- userContext
- removePolicy
elements:
Properties:
include:
attributes:
- path
- section
- value
- property
- action
- disabled
```
## /config/gpo_files_structure/xml/InternetSettings.yaml
```yaml path="/config/gpo_files_structure/xml/InternetSettings.yaml"
InternetSettings:
include:
attributes:
- clsid
- disabled
elements:
IE7:
include:
attributes:
- clsid
- name
- status
- image
- changed
- uid
- desc
- bypassErrors
- userContext
- removePolicy
elements:
Collection:
include:
attributes:
- clsid
elements:
Registry:
include:
attributes:
- clsid
- name
elements:
Properties:
include:
attributes:
- action
- default
- hive
- key
- name
- type
- value
Filters:
include:
Properties:
include:
elements:
Reg:
include:
attributes:
- id
- type
- hive
- key
- name
- value
- disabled
- defaultValue
- bitfield
elements:
SubProp:
include:
attributes:
- id
- value
- mask
Internet:
include:
attributes:
- clsid
- name
- status
- image
- changed
- uid
- desc
- bypassErrors
- userContext
- removePolicy
elements:
Filters:
include:
Properties:
include:
elements:
Reg:
include:
attributes:
- id
- type
- hive
- key
- name
- value
- disabled
- defaultValue
- bitfield
elements:
SubProp:
include:
attributes:
- id
- value
- mask
```
## /config/gpo_files_structure/xml/NTServices.yaml
```yaml path="/config/gpo_files_structure/xml/NTServices.yaml"
NTServices:
include:
attributes:
- clsid
- disabled
elements:
NTService:
include:
attributes:
- clsid
- name
- image
- changed
- uid
- desc
- bypassErrors
- userContext
- removePolicy
elements:
Properties:
include:
attributes:
- serviceAction
- startupType
- serviceName
- timeout
- accountName
- cpassword
- interact
- firstFailure
- secondFailure
- thirdFailure
- resetFailCountDelay
- restartServiceDelay
- restartComputerDelay
- restartMessage
- program
- args
- append
- disabled
```
## /config/gpo_files_structure/xml/NetworkOptions.yaml
```yaml path="/config/gpo_files_structure/xml/NetworkOptions.yaml"
NetworkOptions:
include:
attributes:
- clsid
- disabled
elements:
DUN:
include:
attributes:
- clsid
- name
- image
- changed
- uid
- desc
- bypassErrors
- userContext
- removePolicy
elements:
Properties:
include:
attributes:
- action
- user
- name
- phoneNumber
- disabled
VPN:
include:
attributes:
- clsid
- name
- image
- changed
- uid
- desc
- bypassErrors
- userContext
- removePolicy
elements:
Properties:
include:
attributes:
- action
- user
- name
- ipAddress
- useDNS
- dialFirst
- trayIcon
- showProgress
- showPassword
- showDomain
- redialCount
- redialPause
- idleDisconnect
- reconnect
- customSettings
- securePassword
- secureData
- useLogon
- vpnStrategy
- encryptionType
- eap
- pap
- spap
- chap
- msChap
- oldMsChap
- msChapV2
- disabled
```
## /config/gpo_files_structure/xml/NetworkShareSettings.yaml
```yaml path="/config/gpo_files_structure/xml/NetworkShareSettings.yaml"
NetworkShareSettings:
include:
attributes:
- clsid
- disabled
elements:
NetShare:
include:
attributes:
- clsid
- image
- name
- changed
- uid
- desc
- bypassErrors
- userContext
- removePolicy
elements:
Properties:
include:
attributes:
- action
- name
- path
- comment
- allRegular
- allHidden
- allAdminDrive
- limitUsers
- abe
- userLimit
- disabled
```
## /config/gpo_files_structure/xml/PowerOptions.yaml
```yaml path="/config/gpo_files_structure/xml/PowerOptions.yaml"
PowerOptions:
include:
attributes:
- clsid
- disabled
elements:
GlobalPowerOptions:
include:
attributes:
- clsid
- name
- image
- changed
- uid
- desc
- bypassErrors
- userContext
- removePolicy
elements:
Properties:
include:
attributes:
- showIcon
- promptPassword
- enableHibernation
- closeLid
- pressPowerBtn
- pressSleepBtn
- disabled
GlobalPowerOptionsV2:
include:
attributes:
- clsid
- name
- image
- changed
- uid
- desc
- bypassErrors
- userContext
- removePolicy
elements:
Properties:
include:
attributes:
- action
- nameGuid
- default
- requireWakePwdAC
- requireWakePwdDC
- turnOffHDAC
- turnOffHDDC
- sleepAfterAC
- sleepAfterDC
- allowHybridSleepAC
- allowHybridSleepDC
- hibernateAC
- hibernateDC
- lidCloseAC
- lidCloseDC
- pbActionAC
- pbActionDC
- strtMenuActionAC
- strtMenuActionDC
- linkPwrMgmtAC
- linkPwrMgmtDC
- procStateMinAC
- procStateMinDC
- procStateMaxAC
- procStateMaxDC
- displayOffAC
- displayOffDC
- adaptiveAC
- adaptiveDC
- critBatActionAC
- critBatActionDC
- lowBatteryLvlAC
- lowBatteryLvlDC
- critBatteryLvlAC
- critBatteryLvlDC
- lowBatteryNotAC
- lowBatteryNotDC
- lowBatteryActionAC
- lowBatteryActionDC
PowerScheme:
include:
attributes:
- clsid
- name
- image
- changed
- uid
- desc
- bypassErrors
- userContext
- removePolicy
elements:
Properties:
include:
attributes:
- action
- name
- default
- monitorAc
- monitorDc
- hardDiskAc
- hardDiskDc
- standbyAc
- standbyDc
- hibernateAc
- hibernateDc
- disabled
```
## /config/gpo_files_structure/xml/Printers.yaml
```yaml path="/config/gpo_files_structure/xml/Printers.yaml"
Printers:
include:
attributes:
- clsid
- disabled
elements:
LocalPrinter:
include:
attributes:
- clsid
- name
- image
- changed
- uid
- desc
- bypassErrors
- userContext
- removePolicy
elements:
Properties:
include:
attributes:
- action
- name
- port
- path
- default
- deleteAll
- location
- comment
- disabled
PortPrinter:
include:
attributes:
- clsid
- name
- image
- changed
- uid
- desc
- bypassErrors
- userContext
- removePolicy
elements:
Properties:
include:
attributes:
- ipAddress
- action
- location
- localName
- comment
- default
- skipLocal
- useDNS
- path
- deleteAll
- lprQueue
- snmpCommunity
- protocol
- portNumber
- doubleSpool
- snmpEnabled
- snmpDevIndex
- disabled
SharedPrinter:
include:
attributes:
- clsid
- name
- image
- changed
- uid
- desc
- bypassErrors
- userContext
- removePolicy
elements:
Properties:
include:
attributes:
- action
- comment
- path
- location
- default
- skipLocal
- deleteAll
- persistent
- deleteMaps
- port
- username
- cpassword
- disabled
```
## /config/gpo_files_structure/xml/Regional.yaml
```yaml path="/config/gpo_files_structure/xml/Regional.yaml"
Regional:
include:
attributes:
- clsid
- disabled
elements:
RegionalOptions:
include:
attributes:
- clsid
- name
- image
- changed
- uid
- desc
- bypassErrors
- userContext
- removePolicy
elements:
Properties:
include:
attributes:
- localeId
- localeName
- numDeciSymbol
- numNumDecimals
- numGrpSymbol
- numDigitGrpFmt
- numNegSymbol
- numNegFormat
- numLeadingZeros
- numListSeparator
- numMeasurement
- currSymbol
- currPosFormat
- currNegFormat
- currDeciSymbol
- currNumDecimals
- currGrpSymbol
- currDigitGrpFmt
- timeFormat
- timeSeparator
- timeAmSymbol
- timePmSymbol
- dateInterpretYearMax
- dateShortFormat
- dateSeparator
- dateLongFormat
- disabled
```
## /config/gpo_files_structure/xml/RegistrySettings.yaml
```yaml path="/config/gpo_files_structure/xml/RegistrySettings.yaml"
RegistrySettings:
include:
attributes:
- clsid
- disabled
elements:
Collection:
include:
attributes:
- clsid
- name
- image
- changed
- uid
- desc
- bypassErrors
- userContext
- removePolicy
- status
elements:
Collection:
include:
attributes:
- clsid
- name
elements:
Collection:
include:
attributes:
- clsid
- name
elements:
Collection:
include:
attributes:
- clsid
- name
- disabled
elements:
Registry:
include:
attributes:
- clsid
- name
- image
- desc
- status
- uid
elements:
Properties:
include:
attributes:
- action
- default
- hive
- key
- type
- name
- value
- defaultValue
- displayDecimal
- bitfield
elements:
SubProp:
include:
attributes:
- id
- value
- mask
Registry:
include:
attributes:
- clsid
- name
- status
- image
- changed
- uid
elements:
Properties:
include:
attributes:
- action
- default
- hive
- key
- name
- type
- value
- displayDecimal
- defaultValue
- bitfield
- disabled
elements:
SubProp:
include:
attributes:
- id
- value
- mask
```
## /config/gpo_files_structure/xml/ScheduledTasks.yaml
```yaml path="/config/gpo_files_structure/xml/ScheduledTasks.yaml"
ScheduledTasks:
include:
attributes:
- clsid
- disabled
elements:
ImmediateTask:
include:
attributes:
- clsid
- name
- image
- changed
- uid
- desc
- bypassErrors
- userContext
- removePolicy
elements:
Filters:
include:
Properties:
include:
attributes:
- name
- appName
- args
- startIn
- comment
- runAs
- cpassword
- enabled
- deleteWhenDone
- maxRunTime
- startOnlyIfIdle
- idleMinutes
- deadlineMinutes
- stopOnIdleEnd
- noStartIfOnBatteries
- stopIfGoingOnBatteries
- systemRequired
- action
ImmediateTaskV2:
include:
attributes:
- clsid
- name
- changed
- uid
- image
elements:
Filters:
include:
elements:
FilterOs:
include:
attributes:
- hidden
- not
- bool
- class
- version
- type
- edition
- sp
Properties:
include:
attributes:
- action
- name
- runAs
- logonType
- cpassword
elements:
Task:
include:
Task:
include:
attributes:
- clsid
- name
- image
- changed
- uid
- desc
- bypassErrors
- userContext
- removePolicy
elements:
Filters:
include:
Properties:
include:
attributes:
- action
- name
- appName
- args
- startIn
- comment
- maxRunTime
- runAs
- cpassword
- enabled
- deleteWhenDone
- deadlineMinutes
- startOnlyIfIdle
- stopOnIdleEnd
- noStartIfOnBatteries
- stopIfGoingOnBatteries
- systemRequired
elements:
Triggers:
include:
elements:
Trigger:
include:
attributes:
- type
- startHour
- startMinutes
- beginYear
- beginMonth
- beginDay
- hasEndDate
- repeatTask
- interval
- days
- months
- week
- idleMinute
- endYear
- endMonth
- endDay
- minutesInterval
- killAtDurationEnd
- minutesDuration
TaskV2:
include:
attributes:
- clsid
- name
- changed
- uid
- bypassErrors
- userContext
- removePolicy
- image
- desc
elements:
Filters:
include:
elements:
FilterRunOnce:
include:
attributes:
- hidden
- not
- bool
- id
Properties:
include:
attributes:
- action
- name
- runAs
- logonType
- cpassword
elements:
Task:
include:
```
## /config/gpo_files_structure/xml/Shortcuts.yaml
```yaml path="/config/gpo_files_structure/xml/Shortcuts.yaml"
Shortcuts:
include:
attributes:
- clsid
- disabled
elements:
Shortcut:
include:
attributes:
- clsid
- name
- image
- changed
- uid
- desc
- bypassErrors
- userContext
- removePolicy
elements:
Properties:
include:
attributes:
- pidl
- targetType
- action
- comment
- shortcutKey
- startIn
- arguments
- iconIndex
- targetPath
- iconPath
- window
- shortcutPath
- disabled
```
## /config/gpo_files_structure/xml/StartMenuTaskbar.yaml
```yaml path="/config/gpo_files_structure/xml/StartMenuTaskbar.yaml"
StartMenuTaskbar:
include:
attributes:
- clsid
- disabled
elements:
StartMenu:
include:
attributes:
- clsid
- name
- changed
- image
- uid
- disabled
elements:
Filters:
include:
Properties:
include:
attributes:
- largeMFUIcons
- minMFU
- autoCascade
- notifyNewApps
- showControlPanel
- enableDragDrop
- startMenuFavorites
- showHelp
- showMyComputer
- showMyDocs
- showMyMusic
- showNetPlaces
- showMyPics
- showNetConn
- showPrinters
- showRun
- scrollPrograms
- showSearch
- showRecentDocs
- clearStartDocsList
- cShowLogoff
- cShowRun
- cEnableDragDrop
- cCascadeControlPanel
- cCascadeMyDocuments
- cCascadeMyPictures
- cCascadeNetworkConnections
- cCascadePrinters
- cScrollPrograms
- cPersonalized
StartMenuVista:
include:
attributes:
- clsid
- name
- changed
- image
- uid
- desc
- bypassErrors
- userContext
- removePolicy
- disabled
elements:
Filters:
include:
elements:
FilterOs:
include:
attributes:
- hidden
- not
- bool
- class
- version
- type
- edition
- sp
Properties:
include:
attributes:
- minMFU
- showMyComputer
- connectTo
- showControlPanel
- defaultPrograms
- showMyDocs
- enableContextMenu
- showFavorites
- showGames
- showHelp
- highlightNew
- showMyMusic
- showNetPlaces
- openSubMenus
- personalFolders
- showMyPics
- showPrinters
- runCommand
- showSearch
- searchCommunications
- searchFavorites
- searchFiles
- searchPrograms
- trackProgs
- sortAllPrograms
- systemAdmin
- useLargeIcons
- showRecentDocs
- clearStartDocsList
- cShowAdminTools
- cShowFavorites
- cShowLogoff
- cShowRun
- cEnableDragDrop
- cCascadeControlPanel
- cCascadeMyDocuments
- cCascadeNetworkConnections
- cCascadeMyPictures
- cCascadePrinters
- cScrollPrograms
- cSmallIcons
- cPersonalized
```
## /config/neo4j.yaml
```yaml path="/config/neo4j.yaml"
neo4j-host: "127.0.0.1"
neo4j-port: 7687
neo4j-user: "neo4j"
neo4j-pass: "exegol4thewin"
```
## /config/well_known_groups.yaml
```yaml path="/config/well_known_groups.yaml"
- sid : "S-1-0"
displayname : "Null Authority"
description : "An identifier authority."
- sid : "S-1-0-0"
displayname : "Nobody"
description : "No security principal."
- sid : "S-1-1"
displayname : "World Authority"
description : "An identifier authority."
- sid : "S-1-1-0"
displayname : "Everyone"
- sid : "S-1-2"
displayname : "Local Authority"
description : "An identifier authority."
- sid : "S-1-2-0"
displayname : "Local"
description : "A group that includes all users who have logged on locally."
- sid : "S-1-2-1"
displayname : "Console Logon"
description : "A group that includes users who are logged on to the physical console."
- sid : "S-1-3"
displayname : "Creator Authority"
description : "An identifier authority."
- sid : "S-1-3-0"
displayname : "Creator Owner"
description : "A placeholder in an inheritable access control entry (ACE). When the ACE is inherited, the system replaces this SID with the SID for the object's creator."
- sid : "S-1-3-1"
displayname : "Creator Group"
description : "A placeholder in an inheritable ACE. When the ACE is inherited, the system replaces this SID with the SID for the primary group of the object's creator. The primary group is used only by the POSIX subsystem."
- sid : "S-1-3-2"
displayname : "Creator Owner Server"
description : "This SID is not used in Windows 2000."
- sid : "S-1-3-3"
displayname : "Creator Group Server"
description : "This SID is not used in Windows 2000."
- sid : "S-1-3-4"
displayname : "Owner Rights"
description : "A group that represents the current owner of the object. When an ACE that carries this SID is applied to an object, the system ignores the implicit READ_CONTROL and WRITE_DAC permissions for the object owner."
- sid : "S-1-5-80-0"
displayname : "All Services"
description : "A group that includes all service processes configured on the system. Membership is controlled by the operating system."
- sid : "S-1-4"
displayname : "Non-unique Authority"
description : "An identifier authority."
- sid : "S-1-5"
displayname : "NT Authority"
description : "An identifier authority."
- sid : "S-1-5-1"
displayname : "Dialup"
description : "A group that includes all users who have logged on through a dial-up connection. Membership is controlled by the operating system."
- sid : "S-1-5-2"
displayname : "Network"
description : "A group that includes all users that have logged on through a network connection. Membership is controlled by the operating system."
- sid : "S-1-5-3"
displayname : "Batch"
description : "A group that includes all users that have logged on through a batch queue facility. Membership is controlled by the operating system."
- sid : "S-1-5-4"
displayname : "Interactive"
description : "A group that includes all users that have logged on interactively. Membership is controlled by the operating system."
- sid : "S-1-5-6"
displayname : "Service"
description : "A group that includes all security principals that have logged on as a service. Membership is controlled by the operating system."
- sid : "S-1-5-7"
displayname : "Anonymous"
description : "A group that includes all users that have logged on anonymously. Membership is controlled by the operating system."
- sid : "S-1-5-8"
displayname : "Proxy"
description : "This SID is not used in Windows 2000."
- sid : "S-1-5-9"
displayname : "Enterprise Domain Controllers"
description : "A group that includes all domain controllers in a forest that uses an Active Directory directory service. Membership is controlled by the operating system."
- sid : "S-1-5-10"
displayname : "Principal Self"
description : "A placeholder in an inheritable ACE on an account object or group object in Active Directory. When the ACE is inherited, the system replaces this SID with the SID for the security principal who holds the account."
- sid : "S-1-5-11"
displayname : "Authenticated Users"
description : "A group that includes all users whose identities were authenticated when they logged on. Membership is controlled by the operating system."
- sid : "S-1-5-12"
displayname : "Restricted Code"
description : "This SID is reserved for future use."
- sid : "S-1-5-13"
displayname : "Terminal Server Users"
description : "A group that includes all users that have logged on to a Terminal Services server. Membership is controlled by the operating system."
- sid : "S-1-5-14"
displayname : "Remote Interactive Logon"
description : "A group that includes all users who have logged on through a terminal services logon."
- sid : "S-1-5-15"
displayname : "This Organization"
description : "A group that includes all users from the same organization. Only included with AD accounts and only added by a Windows Server 2003 or later domain controller."
- sid : "S-1-5-17"
displayname : "This Organization"
description : "An account that is used by the default Internet Information Services (IIS) user."
- sid : "S-1-5-18"
displayname : "Local System"
description : "A service account that is used by the operating system."
- sid : "S-1-5-19"
displayname : "NT Authority\\Local Service"
description : "Local Service"
- sid : "S-1-5-20"
displayname : "NT Authority\\Network Service"
description : "Network Service"
- sid : "S-1-5-32-544"
displayname : "Administrators"
description : "A built-in group. After the initial installation of the operating system, the only member of the group is the Administrator account. When a computer joins a domain, the Domain Admins group is added to the Administrators group. When a server becomes a domain controller, the Enterprise Admins group also is added to the Administrators group."
- sid : "S-1-5-32-544"
displayname : "BUILTIN\\Administrators"
description : "A built-in group. After the initial installation of the operating system, the only member of the group is the Administrator account. When a computer joins a domain, the Domain Admins group is added to the Administrators group. When a server becomes a domain controller, the Enterprise Admins group also is added to the Administrators group."
- sid : "S-1-5-32-545"
displayname : "Users"
description : "A built-in group. After the initial installation of the operating system, the only member is the Authenticated Users group. When a computer joins a domain, the Domain Users group is added to the Users group on the computer."
- sid : "S-1-5-32-545"
displayname : "BUILTIN\\Users"
description : "A built-in group. After the initial installation of the operating system, the only member is the Authenticated Users group. When a computer joins a domain, the Domain Users group is added to the Users group on the computer."
- sid : "S-1-5-32-546"
displayname : "Guests"
description : "A built-in group. By default, the only member is the Guest account. The Guests group allows occasional or one-time users to log on with limited privileges to a computer's built-in Guest account."
- sid : "S-1-5-32-546"
displayname : "BUILTIN\\Guests"
description : "A built-in group. By default, the only member is the Guest account. The Guests group allows occasional or one-time users to log on with limited privileges to a computer's built-in Guest account."
- sid : "S-1-5-32-547"
displayname : "Power Users"
description : "A built-in group. By default, the group has no members. Power users can create local users and groups; modify and delete accounts that they have created; and remove users from the Power Users, Users, and Guests groups. Power users also can install programs; create, manage, and delete local printers; and create and delete file shares."
- sid : "S-1-5-32-547"
displayname : "BUILTIN\\Power Users"
description : "A built-in group. By default, the group has no members. Power users can create local users and groups; modify and delete accounts that they have created; and remove users from the Power Users, Users, and Guests groups. Power users also can install programs; create, manage, and delete local printers; and create and delete file shares."
- sid : "S-1-5-32-548"
displayname : "Account Operators"
description : "A built-in group that exists only on domain controllers. By default, the group has no members. By default, Account Operators have permission to create, modify, and delete accounts for users, groups, and computers in all containers and organizational units of Active Directory except the Builtin container and the Domain Controllers OU. Account Operators do not have permission to modify the Administrators and Domain Admins groups, nor do they have permission to modify the accounts for members of those groups."
- sid : "S-1-5-32-548"
displayname : "BUILTIN\\Account Operators"
description : "A built-in group that exists only on domain controllers. By default, the group has no members. By default, Account Operators have permission to create, modify, and delete accounts for users, groups, and computers in all containers and organizational units of Active Directory except the Builtin container and the Domain Controllers OU. Account Operators do not have permission to modify the Administrators and Domain Admins groups, nor do they have permission to modify the accounts for members of those groups."
- sid : "S-1-5-32-549"
displayname : "Server Operators"
description : "A built-in group that exists only on domain controllers. By default, the group has no members. Server Operators can log on to a server interactively; create and delete network shares; start and stop services; back up and restore files; format the hard disk of the computer; and shut down the computer."
- sid : "S-1-5-32-549"
displayname : "BUILTIN\\Server Operators"
description : "A built-in group that exists only on domain controllers. By default, the group has no members. Server Operators can log on to a server interactively; create and delete network shares; start and stop services; back up and restore files; format the hard disk of the computer; and shut down the computer."
- sid : "S-1-5-32-550"
displayname : "Print Operators"
description : "A built-in group that exists only on domain controllers. Print Operators can manage printers and document queues."
- sid : "S-1-5-32-550"
displayname : "BUILTIN\\Print Operators"
description : "A built-in group that exists only on domain controllers. Print Operators can manage printers and document queues."
- sid : "S-1-5-32-551"
displayname : "Backup Operators"
description : "A built-in group. By default, the group has no members. Backup Operators can back up and restore all files on a computer, regardless of the permissions that protect those files. Backup Operators also can log on to the computer and shut it down."
- sid : "S-1-5-32-551"
displayname : "BUILTIN\\Backup Operators"
description : "A built-in group. By default, the group has no members. Backup Operators can back up and restore all files on a computer, regardless of the permissions that protect those files. Backup Operators also can log on to the computer and shut it down."
- sid : "S-1-5-32-552"
displayname : "Replicators"
description : "A built-in group that is used by the File Replication service on domain controllers. By default, the group has no members. Do not add users to this group."
- sid : "S-1-5-32-552"
displayname : "BUILTIN\\Replicators"
description : "A built-in group that is used by the File Replication service on domain controllers. By default, the group has no members. Do not add users to this group."
- sid : "S-1-5-64-10"
displayname : "NTLM Authentication"
description : "A SID that is used when the NTLM authentication package authenticated the client"
- sid : "S-1-5-64-14"
displayname : "SChannel Authentication"
description : "A SID that is used when the SChannel authentication package authenticated the client."
- sid : "S-1-5-64-21"
displayname : "Digest Authentication"
description : "A SID that is used when the Digest authentication package authenticated the client."
- sid : "S-1-5-80"
displayname : "NT Service"
description : "An NT Service account prefix"
- sid : "S-1-5-80-0"
displayname : "All Services"
description : "A group that includes all service processes that are configured on the system. Membership is controlled by the operating system."
- sid : "S-1-5-83-0"
displayname : "NT VIRTUAL MACHINE\\Virtual Machines"
description : "A built-in group. The group is created when the Hyper-V role is installed. Membership in the group is maintained by the Hyper-V Management Service (VMMS). This group requires the \"Create Symbolic Links\" right (SeCreateSymbolicLinkPrivilege), and also the \"Log on as a Service\" right (SeServiceLogonRight)."
- sid : "S-1-16-0"
displayname : "Untrusted Mandatory Level"
description : "An untrusted integrity level. Note Added in Windows Vista and Windows Server 2008"
- sid : "S-1-16-4096"
displayname : "Low Mandatory Level"
description : "A low integrity level."
- sid : "S-1-16-8192"
displayname : "Medium Mandatory Level"
description : "A medium integrity level."
- sid : "S-1-16-8448"
displayname : "Medium Plus Mandatory Level"
description : "A medium plus integrity level."
- sid : "S-1-16-12288"
displayname : "High Mandatory Level"
description : "A high integrity level."
- sid : "S-1-16-16384"
displayname : "System Mandatory Level"
description : "A system integrity level."
- sid : "S-1-16-20480"
displayname : "Protected Process Mandatory Level"
description : "A protected-process integrity level."
- sid : "S-1-16-28672"
displayname : "Secure Process Mandatory Level"
description : "A secure process integrity level."
- sid : "S-1-5-32-554"
displayname : "BUILTIN\\Pre-Windows 2000 Compatible Access"
description : "An alias added by Windows 2000. A backward compatibility group which allows read access on all users and groups in the domain."
- sid : "S-1-5-32-555"
displayname : "BUILTIN\\Remote Desktop Users"
description : "An alias. Members in this group are granted the right to logon remotely."
- sid : "S-1-5-32-556"
displayname : "BUILTIN\\Network Configuration Operators"
description : "An alias. Members in this group can have some administrative privileges to manage configuration of networking features."
- sid : "S-1-5-32-557"
displayname : "BUILTIN\\Incoming Forest Trust Builders"
description : "An alias. Members of this group can create incoming, one-way trusts to this forest."
- sid : "S-1-5-32-558"
displayname : "BUILTIN\\Performance Monitor Users"
description : "An alias. Members of this group have remote access to monitor this computer."
- sid : "S-1-5-32-559"
displayname : "BUILTIN\\Performance Log Users"
description : "An alias. Members of this group have remote access to schedule logging of performance counters on this computer."
- sid : "S-1-5-32-560"
displayname : "BUILTIN\\Windows Authorization Access Group"
description : "An alias. Members of this group have access to the computed tokenGroupsGlobalAndUniversal attribute on User objects."
- sid : "S-1-5-32-561"
displayname : "BUILTIN\\Terminal Server License Servers"
description : "An alias. A group for Terminal Server License Servers. When Windows Server 2003 Service Pack 1 is installed, a new local group is created."
- sid : "S-1-5-32-562"
displayname : "BUILTIN\\Distributed COM Users"
description : "An alias. A group for COM to provide computerwide access controls that govern access to all call, activation, or launch requests on the computer."
- sid : "S-1-5-32-569"
displayname : "BUILTIN\\Cryptographic Operators"
description : "A Builtin Local group. Members are authorized to perform cryptographic operations."
- sid : "S-1-5-32-573"
displayname : "BUILTIN\\Event Log Readers"
description : "A Builtin Local group. Members of this group can read event logs from local machine."
- sid : "S-1-5-32-574"
displayname : "BUILTIN\\Certificate Service DCOM Access"
description : "A Builtin Local group. Members of this group are allowed to connect to Certification Authorities in the enterprise."
- sid : "S-1-5-32-575"
displayname : "BUILTIN\\RDS Remote Access Servers"
description : "A Builtin Local group. Servers in this group enable users of RemoteApp programs and personal virtual desktops access to these resources. In Internet-facing deployments, these servers are typically deployed in an edge network. This group needs to be populated on servers running RD Connection Broker. RD Gateway servers and RD Web Access servers used in the deployment need to be in this group."
- sid : "S-1-5-32-576"
displayname : "BUILTIN\\RDS Endpoint Servers"
description : "A Builtin Local group. Servers in this group run virtual machines and host sessions where users RemoteApp programs and personal virtual desktops run. This group needs to be populated on servers running RD Connection Broker. RD Session Host servers and RD Virtualization Host servers used in the deployment need to be in this group."
- sid : "S-1-5-32-577"
displayname : "BUILTIN\\RDS Management Servers"
description : "A Builtin Local group. Servers in this group can perform routine administrative actions on servers running Remote Desktop Services. This group needs to be populated on all servers in a Remote Desktop Services deployment. The servers running the RDS Central Management service must be included in this group."
- sid : "S-1-5-32-578"
displayname : "BUILTIN\\Hyper-V Administrators"
description : "A Builtin Local group. Members of this group have complete and unrestricted access to all features of Hyper-V."
- sid : "S-1-5-32-579"
displayname : "BUILTIN\\Access Control Assistance Operators"
description : "A Builtin Local group. Members of this group can remotely query authorization attributes and permissions for resources on this computer."
- sid : "S-1-5-32-580"
displayname : "BUILTIN\\Remote Management Users"
description : "A Builtin Local group. Members of this group can access WMI resources over management protocols (such as WS-Management via the Windows Remote Management service). This applies only to WMI namespaces that grant access to the user."
```
## /customqueries.json
```json path="/customqueries.json"
{
"queries": [
{
"name": "All relationships added by GPO",
"category": "GPOHound",
"queryList": [
{
"final": true,
"query": "MATCH p=()-[r]-() WHERE r.gpohound = true RETURN p"
}
]
},
{
"name": "Local Administrators",
"category": "GPOHound",
"queryList": [
{
"final": true,
"query": "MATCH p1=()-[r:AdminTo]->() WHERE r.gpohound = true WITH p1 OPTIONAL MATCH p2=()-[r1:MemberOf*1..]->()-[r2:AdminTo]->() WHERE r2.gpohound = true RETURN p1,p2"
}
]
},
{
"name": "Local Remote Desktop Users",
"category": "GPOHound",
"queryList": [
{
"final": true,
"query": "MATCH p1=()-[r:CanRDP]->() WHERE r.gpohound = true WITH p1 OPTIONAL MATCH p2=()-[r1:MemberOf*1..]->()-[r2:CanRDP]->() WHERE r2.gpohound = true RETURN p1,p2"
}
]
},
{
"name": "Local Distributed COM Users",
"category": "GPOHound",
"queryList": [
{
"final": true,
"query": "MATCH p1=()-[r:ExecuteDCOM]->() WHERE r.gpohound = true WITH p1 OPTIONAL MATCH p2=()-[r1:MemberOf*1..]->()-[r2:ExecuteDCOM]->() WHERE r2.gpohound = true RETURN p1,p2"
}
]
},
{
"name": "Local Remote Management Users",
"category": "GPOHound",
"queryList": [
{
"final": true,
"query": "MATCH p1=()-[r:CanPSRemote]->() WHERE r.gpohound = true WITH p1 OPTIONAL MATCH p2=()-[r1:MemberOf*1..]->()-[r2:CanPSRemote]->() WHERE r2.gpohound = true RETURN p1,p2"
}
]
},
{
"name": "Local Privilege Escalation",
"category": "GPOHound",
"queryList": [
{
"final": true,
"query": "MATCH p1=()-[r:CanPrivEsc]->() WHERE r.gpohound = true WITH p1 OPTIONAL MATCH p2=()-[r1:MemberOf*1..]->()-[r2:CanPrivEsc]->() WHERE r2.gpohound = true RETURN p1,p2"
}
]
},
{
"name": "Find Computers where SMB Signing is not Required",
"category": "GPOHound",
"queryList": [
{
"final": true,
"query": "MATCH (n:Computer) WHERE n.smbSigningRequired = False RETURN n"
}
]
},
{
"name": "Find Computers where SMB Signing is not Enabled",
"category": "GPOHound",
"queryList": [
{
"final": true,
"query": "MATCH (n:Computer) WHERE n.smbSigningEnabled = False RETURN n"
}
]
},
{
"name": "Find Computers where NTLMv1 is Supported",
"category": "GPOHound",
"queryList": [
{
"final": true,
"query": "MATCH (n:Computer) WHERE n.NTLMv1Support = True RETURN n"
}
]
},
{
"name": "Find Computers with VNC credentials",
"category": "GPOHound",
"queryList": [
{
"final": true,
"query": "MATCH (n:Computer) WHERE ANY(k IN keys(n) WHERE toLower(k) CONTAINS 'vnc' and toLower(k) CONTAINS 'pass') RETURN n"
}
]
}
]
}
```
## /example/bloodhound_north_sevenkingdoms_local.zip
Binary file available at https://raw.githubusercontent.com/cogiceo/GPOHound/refs/heads/main/example/bloodhound_north_sevenkingdoms_local.zip
## /example/north.sevenkingdoms.local/Policies/{01635BDB-1096-436C-8152-F05E71EE45CB}/GPT.INI
```INI path="/example/north.sevenkingdoms.local/Policies/{01635BDB-1096-436C-8152-F05E71EE45CB}/GPT.INI"
[General]
Version=2
displayName=New Group Policy Object
```
## /example/north.sevenkingdoms.local/Policies/{01635BDB-1096-436C-8152-F05E71EE45CB}/Machine/Microsoft/Windows NT/SecEdit/GptTmpl.inf
Binary file available at https://raw.githubusercontent.com/cogiceo/GPOHound/refs/heads/main/example/north.sevenkingdoms.local/Policies/{01635BDB-1096-436C-8152-F05E71EE45CB}/Machine/Microsoft/Windows NT/SecEdit/GptTmpl.inf
## /example/north.sevenkingdoms.local/Policies/{0A85301F-7CE4-4391-8354-BA1AEAD44FFC}/GPT.INI
```INI path="/example/north.sevenkingdoms.local/Policies/{0A85301F-7CE4-4391-8354-BA1AEAD44FFC}/GPT.INI"
[General]
Version=4
displayName=New Group Policy Object
```
## /example/north.sevenkingdoms.local/Policies/{0A85301F-7CE4-4391-8354-BA1AEAD44FFC}/Machine/Microsoft/Windows NT/SecEdit/GptTmpl.inf
Binary file available at https://raw.githubusercontent.com/cogiceo/GPOHound/refs/heads/main/example/north.sevenkingdoms.local/Policies/{0A85301F-7CE4-4391-8354-BA1AEAD44FFC}/Machine/Microsoft/Windows NT/SecEdit/GptTmpl.inf
## /example/north.sevenkingdoms.local/Policies/{21246D99-1426-495B-9E8E-556ABDD81F94}/GPT.INI
```INI path="/example/north.sevenkingdoms.local/Policies/{21246D99-1426-495B-9E8E-556ABDD81F94}/GPT.INI"
[General]
Version=4
displayName=New Group Policy Object
```
## /example/north.sevenkingdoms.local/Policies/{21246D99-1426-495B-9E8E-556ABDD81F94}/Machine/Preferences/Groups/Groups.xml
```xml path="/example/north.sevenkingdoms.local/Policies/{21246D99-1426-495B-9E8E-556ABDD81F94}/Machine/Preferences/Groups/Groups.xml"
```
## /example/north.sevenkingdoms.local/Policies/{276AA65B-86AE-4557-8858-3BC1B2C0B384}/GPT.INI
```INI path="/example/north.sevenkingdoms.local/Policies/{276AA65B-86AE-4557-8858-3BC1B2C0B384}/GPT.INI"
[General]
Version=3
displayName=New Group Policy Object
```
## /example/north.sevenkingdoms.local/Policies/{276AA65B-86AE-4557-8858-3BC1B2C0B384}/Machine/Microsoft/Windows NT/SecEdit/GptTmpl.inf
Binary file available at https://raw.githubusercontent.com/cogiceo/GPOHound/refs/heads/main/example/north.sevenkingdoms.local/Policies/{276AA65B-86AE-4557-8858-3BC1B2C0B384}/Machine/Microsoft/Windows NT/SecEdit/GptTmpl.inf
## /example/north.sevenkingdoms.local/Policies/{31B2F340-016D-11D2-945F-00C04FB984F9}/GPT.INI
```INI path="/example/north.sevenkingdoms.local/Policies/{31B2F340-016D-11D2-945F-00C04FB984F9}/GPT.INI"
[General]
Version=2
```
## /example/north.sevenkingdoms.local/Policies/{31B2F340-016D-11D2-945F-00C04FB984F9}/MACHINE/Microsoft/Windows NT/SecEdit/GptTmpl.inf
Binary file available at https://raw.githubusercontent.com/cogiceo/GPOHound/refs/heads/main/example/north.sevenkingdoms.local/Policies/{31B2F340-016D-11D2-945F-00C04FB984F9}/MACHINE/Microsoft/Windows NT/SecEdit/GptTmpl.inf
## /example/north.sevenkingdoms.local/Policies/{47D7A63A-7ACA-484D-A3EB-FF5A3B5D6EB8}/GPT.INI
```INI path="/example/north.sevenkingdoms.local/Policies/{47D7A63A-7ACA-484D-A3EB-FF5A3B5D6EB8}/GPT.INI"
[General]
Version=1
displayName=New Group Policy Object
```
## /example/north.sevenkingdoms.local/Policies/{47D7A63A-7ACA-484D-A3EB-FF5A3B5D6EB8}/Machine/Registry.pol
```pol path="/example/north.sevenkingdoms.local/Policies/{47D7A63A-7ACA-484D-A3EB-FF5A3B5D6EB8}/Machine/Registry.pol"
PReg [ S o f t w a r e \ P o l i c i e s \ M i c r o s o f t \ W i n d o w s \ P e r s o n a l i z a t i o n ; F o r c e S t a r t B a c k g r o u n d ; ; ; ]
```
## /example/north.sevenkingdoms.local/Policies/{47D7A63A-7ACA-484D-A3EB-FF5A3B5D6EB8}/Machine/comment.cmtx
```cmtx path="/example/north.sevenkingdoms.local/Policies/{47D7A63A-7ACA-484D-A3EB-FF5A3B5D6EB8}/Machine/comment.cmtx"
```
## /example/north.sevenkingdoms.local/Policies/{57C13291-8AC5-41C8-A934-258CBD70A7B5}/GPT.INI
```INI path="/example/north.sevenkingdoms.local/Policies/{57C13291-8AC5-41C8-A934-258CBD70A7B5}/GPT.INI"
[General]
Version=2
displayName=New Group Policy Object
```
## /example/north.sevenkingdoms.local/Policies/{57C13291-8AC5-41C8-A934-258CBD70A7B5}/Machine/Microsoft/Windows NT/SecEdit/GptTmpl.inf
Binary file available at https://raw.githubusercontent.com/cogiceo/GPOHound/refs/heads/main/example/north.sevenkingdoms.local/Policies/{57C13291-8AC5-41C8-A934-258CBD70A7B5}/Machine/Microsoft/Windows NT/SecEdit/GptTmpl.inf
## /example/north.sevenkingdoms.local/Policies/{6AC1786C-016F-11D2-945F-00C04fB984F9}/GPT.INI
```INI path="/example/north.sevenkingdoms.local/Policies/{6AC1786C-016F-11D2-945F-00C04fB984F9}/GPT.INI"
[General]
Version=1
```
## /example/north.sevenkingdoms.local/Policies/{6AC1786C-016F-11D2-945F-00C04fB984F9}/MACHINE/Microsoft/Windows NT/SecEdit/GptTmpl.inf
Binary file available at https://raw.githubusercontent.com/cogiceo/GPOHound/refs/heads/main/example/north.sevenkingdoms.local/Policies/{6AC1786C-016F-11D2-945F-00C04fB984F9}/MACHINE/Microsoft/Windows NT/SecEdit/GptTmpl.inf
## /example/north.sevenkingdoms.local/Policies/{98FBDD11-FA06-4F54-9119-B56DB4C52B81}/GPT.INI
```INI path="/example/north.sevenkingdoms.local/Policies/{98FBDD11-FA06-4F54-9119-B56DB4C52B81}/GPT.INI"
[General]
Version=1
displayName=New Group Policy Object
```
## /example/north.sevenkingdoms.local/Policies/{98FBDD11-FA06-4F54-9119-B56DB4C52B81}/Machine/Registry.pol
```pol path="/example/north.sevenkingdoms.local/Policies/{98FBDD11-FA06-4F54-9119-B56DB4C52B81}/Machine/Registry.pol"
PReg [ S o f t w a r e \ P o l i c i e s \ M i c r o s o f t \ W i n d o w s \ P e r s o n a l i z a t i o n ; F o r c e S t a r t B a c k g r o u n d ; ; ; ]
```
## /example/north.sevenkingdoms.local/Policies/{98FBDD11-FA06-4F54-9119-B56DB4C52B81}/Machine/comment.cmtx
```cmtx path="/example/north.sevenkingdoms.local/Policies/{98FBDD11-FA06-4F54-9119-B56DB4C52B81}/Machine/comment.cmtx"
```
## /example/north.sevenkingdoms.local/Policies/{A62549D8-9E57-4ED8-B9C0-F513637BEFAD}/GPT.INI
```INI path="/example/north.sevenkingdoms.local/Policies/{A62549D8-9E57-4ED8-B9C0-F513637BEFAD}/GPT.INI"
[General]
Version=8
displayName=New Group Policy Object
```
## /example/north.sevenkingdoms.local/Policies/{A62549D8-9E57-4ED8-B9C0-F513637BEFAD}/Machine/Microsoft/Windows NT/SecEdit/GptTmpl.inf
Binary file available at https://raw.githubusercontent.com/cogiceo/GPOHound/refs/heads/main/example/north.sevenkingdoms.local/Policies/{A62549D8-9E57-4ED8-B9C0-F513637BEFAD}/Machine/Microsoft/Windows NT/SecEdit/GptTmpl.inf
## /example/north.sevenkingdoms.local/Policies/{A98BEB12-AE4E-41C5-8F81-C9E318EB5338}/GPT.INI
```INI path="/example/north.sevenkingdoms.local/Policies/{A98BEB12-AE4E-41C5-8F81-C9E318EB5338}/GPT.INI"
[General]
Version=8
displayName=New Group Policy Object
```
## /example/north.sevenkingdoms.local/Policies/{A98BEB12-AE4E-41C5-8F81-C9E318EB5338}/Machine/Microsoft/Windows NT/SecEdit/GptTmpl.inf
Binary file available at https://raw.githubusercontent.com/cogiceo/GPOHound/refs/heads/main/example/north.sevenkingdoms.local/Policies/{A98BEB12-AE4E-41C5-8F81-C9E318EB5338}/Machine/Microsoft/Windows NT/SecEdit/GptTmpl.inf
## /example/north.sevenkingdoms.local/Policies/{AFC8E3D9-4440-4D1C-A0CC-B3D15BDE3101}/GPO.cmt
```cmt path="/example/north.sevenkingdoms.local/Policies/{AFC8E3D9-4440-4D1C-A0CC-B3D15BDE3101}/GPO.cmt"
C h a n g e W a l l p a p e r
```
## /example/north.sevenkingdoms.local/Policies/{AFC8E3D9-4440-4D1C-A0CC-B3D15BDE3101}/GPT.INI
```INI path="/example/north.sevenkingdoms.local/Policies/{AFC8E3D9-4440-4D1C-A0CC-B3D15BDE3101}/GPT.INI"
[General]
Version=131073
displayName=New Group Policy Object
```
## /example/north.sevenkingdoms.local/Policies/{AFC8E3D9-4440-4D1C-A0CC-B3D15BDE3101}/Machine/Registry.pol
```pol path="/example/north.sevenkingdoms.local/Policies/{AFC8E3D9-4440-4D1C-A0CC-B3D15BDE3101}/Machine/Registry.pol"
PReg [ S o f t w a r e \ P o l i c i e s \ M i c r o s o f t \ W i n d o w s N T \ C u r r e n t V e r s i o n \ W i n L o g o n ; S y n c F o r e g r o u n d P o l i c y ; ; ; ]
```
## /example/north.sevenkingdoms.local/Policies/{AFC8E3D9-4440-4D1C-A0CC-B3D15BDE3101}/User/Registry.pol
```pol path="/example/north.sevenkingdoms.local/Policies/{AFC8E3D9-4440-4D1C-A0CC-B3D15BDE3101}/User/Registry.pol"
PReg [ C o n t r o l P a n e l \ C o l o r s ; B a c k g r o u n d ; ; ; 1 0 0 1 7 5 2 0 0 ] [ C o n t r o l P a n e l \ D e s k t o p ; W a l l p a p e r ; ; ; ]
```
## /example/north.sevenkingdoms.local/Policies/{B3CB4A8C-8396-4F60-B66C-E66851B3B814}/GPT.INI
```INI path="/example/north.sevenkingdoms.local/Policies/{B3CB4A8C-8396-4F60-B66C-E66851B3B814}/GPT.INI"
[General]
Version=8
displayName=New Group Policy Object
```
## /example/north.sevenkingdoms.local/Policies/{B3CB4A8C-8396-4F60-B66C-E66851B3B814}/Machine/Preferences/Groups/Groups.xml
```xml path="/example/north.sevenkingdoms.local/Policies/{B3CB4A8C-8396-4F60-B66C-E66851B3B814}/Machine/Preferences/Groups/Groups.xml"
```
## /example/north.sevenkingdoms.local/Policies/{B9D151CC-2846-4695-BB75-B9A5B0534C19}/GPT.INI
```INI path="/example/north.sevenkingdoms.local/Policies/{B9D151CC-2846-4695-BB75-B9A5B0534C19}/GPT.INI"
[General]
Version=16
displayName=New Group Policy Object
```
## /example/north.sevenkingdoms.local/Policies/{B9D151CC-2846-4695-BB75-B9A5B0534C19}/Machine/Microsoft/Windows NT/SecEdit/GptTmpl.inf
Binary file available at https://raw.githubusercontent.com/cogiceo/GPOHound/refs/heads/main/example/north.sevenkingdoms.local/Policies/{B9D151CC-2846-4695-BB75-B9A5B0534C19}/Machine/Microsoft/Windows NT/SecEdit/GptTmpl.inf
## /example/north.sevenkingdoms.local/Policies/{CCF6CAE3-E280-4109-8F9D-25461DBB5D67}/GPT.INI
```INI path="/example/north.sevenkingdoms.local/Policies/{CCF6CAE3-E280-4109-8F9D-25461DBB5D67}/GPT.INI"
[General]
Version=32
displayName=New Group Policy Object
```
## /example/north.sevenkingdoms.local/Policies/{CCF6CAE3-E280-4109-8F9D-25461DBB5D67}/Machine/Preferences/Registry/Registry.xml
```xml path="/example/north.sevenkingdoms.local/Policies/{CCF6CAE3-E280-4109-8F9D-25461DBB5D67}/Machine/Preferences/Registry/Registry.xml"
```
## /example/north.sevenkingdoms.local/Policies/{D083FBC6-8E4E-499F-A183-DCBB27C52A70}/GPT.INI
```INI path="/example/north.sevenkingdoms.local/Policies/{D083FBC6-8E4E-499F-A183-DCBB27C52A70}/GPT.INI"
[General]
Version=0
displayName=New Group Policy Object
```
## /example/north.sevenkingdoms.local/Policies/{D6A342D8-0BB9-4F8C-8579-93DE5A07CFC0}/GPT.INI
```INI path="/example/north.sevenkingdoms.local/Policies/{D6A342D8-0BB9-4F8C-8579-93DE5A07CFC0}/GPT.INI"
[General]
Version=131072
displayName=New Group Policy Object
```
## /example/north.sevenkingdoms.local/Policies/{D6A342D8-0BB9-4F8C-8579-93DE5A07CFC0}/User/Scripts/psscripts.ini
Binary file available at https://raw.githubusercontent.com/cogiceo/GPOHound/refs/heads/main/example/north.sevenkingdoms.local/Policies/{D6A342D8-0BB9-4F8C-8579-93DE5A07CFC0}/User/Scripts/psscripts.ini
## /example/north.sevenkingdoms.local/Policies/{D6A342D8-0BB9-4F8C-8579-93DE5A07CFC0}/User/Scripts/scripts.ini
Binary file available at https://raw.githubusercontent.com/cogiceo/GPOHound/refs/heads/main/example/north.sevenkingdoms.local/Policies/{D6A342D8-0BB9-4F8C-8579-93DE5A07CFC0}/User/Scripts/scripts.ini
## /example/north.sevenkingdoms.local/Policies/{FBA8ADDE-55DA-448C-87ED-FBFB185E3A8C}/GPT.INI
```INI path="/example/north.sevenkingdoms.local/Policies/{FBA8ADDE-55DA-448C-87ED-FBFB185E3A8C}/GPT.INI"
[General]
Version=262144
displayName=New Group Policy Object
```
## /example/north.sevenkingdoms.local/Policies/{FBA8ADDE-55DA-448C-87ED-FBFB185E3A8C}/User/Preferences/Groups/Groups.xml
```xml path="/example/north.sevenkingdoms.local/Policies/{FBA8ADDE-55DA-448C-87ED-FBFB185E3A8C}/User/Preferences/Groups/Groups.xml"
```
## /example/north.sevenkingdoms.local/scripts/script.ps1
```ps1 path="/example/north.sevenkingdoms.local/scripts/script.ps1"
# fake script in netlogon with creds
$task = '/c TODO'
$taskName = "fake task"
$user = "NORTH\jeor.mormont"
$password = "_L0ngCl@w_"
# passwords in sysvol still ...
```
## /example/north.sevenkingdoms.local/scripts/secret.ps1
```ps1 path="/example/north.sevenkingdoms.local/scripts/secret.ps1"
# cypher script
# $domain="sevenkingdoms.local"
# $EncryptionKeyBytes = New-Object Byte[] 32
# [Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($EncryptionKeyBytes)
# $EncryptionKeyBytes | Out-File "encryption.key"
# $EncryptionKeyData = Get-Content "encryption.key"
# Read-Host -AsSecureString | ConvertFrom-SecureString -Key $EncryptionKeyData | Out-File -FilePath "secret.encrypted"
# secret stored :
$keyData = 177, 252, 228, 64, 28, 91, 12, 201, 20, 91, 21, 139, 255, 65, 9, 247, 41, 55, 164, 28, 75, 132, 143, 71, 62, 191, 211, 61, 154, 61, 216, 91
$secret="76492d1116743f0423413b16050a5345MgB8AGkAcwBDACsAUwArADIAcABRAEcARABnAGYAMwA3AEEAcgBFAEIAYQB2AEEAPQA9AHwAZQAwADgANAA2ADQAMABiADYANAAwADYANgA1ADcANgAxAGIAMQBhAGQANQBlAGYAYQBiADQAYQA2ADkAZgBlAGQAMQAzADAANQAyADUAMgAyADYANAA3ADAAZABiAGEAOAA0AGUAOQBkAGMAZABmAGEANAAyADkAZgAyADIAMwA="
# T.L.
```
## /gpohound.py
```py path="/gpohound.py"
#! /usr/bin/env python3
import gpohound
gpohound.main()
```
## /gpohound/__init__.py
```py path="/gpohound/__init__.py"
#! /usr/bin/env python3
import argparse
import os
import sys
import logging
from pathlib import Path
from platformdirs import user_config_dir
from gpohound.utils.utils import load_yaml_config
from gpohound.core import GPOHoundCore
def main():
# Create configuration directory if it does not exist
os.makedirs(user_config_dir("gpohound"), exist_ok=True)
# YAML configuration
file_map = load_yaml_config("config", "gpo_files.yaml")
neo4j_conf = load_yaml_config("config", "neo4j.yaml")
parser = argparse.ArgumentParser(description="GPOHound - Group Policy Object Dumper & Analyser")
# SYSVOL
sysvol = parser.add_argument_group("SYSVOL source")
sysvol.add_argument(
"-S",
dest="sysvol_path",
metavar="SYSVOL_PATH",
default=Path.cwd(),
type=str,
help="Path to the SYSVOL directory containing domain GPO data (default: current working directory)",
)
# Neo4j configuration
neo4j = parser.add_argument_group("Neo4j settings")
neo4j.add_argument(
"--neo4j-host",
default=neo4j_conf.get("neo4j-host"),
metavar="HOST",
help=f"IP address or hostname of the Neo4j server (default: {neo4j_conf.get('neo4j-host')})",
)
neo4j.add_argument(
"--neo4j-port",
default=neo4j_conf.get("neo4j-port"),
metavar="PORT",
help=f"Port used by Neo4j's Bolt protocol (default: {str(neo4j_conf.get('neo4j-port'))})",
type=int,
)
neo4j.add_argument(
"--neo4j-user",
default=neo4j_conf.get("neo4j-user"),
metavar="USER",
help=f"Username for Neo4j authentication (default: {neo4j_conf.get('neo4j-user')})",
)
neo4j.add_argument(
"--neo4j-pass",
default=neo4j_conf.get("neo4j-pass"),
metavar="PASS",
help=f"Password for Neo4j authentication (default: {neo4j_conf.get('neo4j-pass')})",
)
# Commands
subparsers = parser.add_subparsers(title="Commands", dest="command", required=True)
# Dump command
dump = subparsers.add_parser("dump", help="Dump all GPOs in a structured tree format")
dump.add_argument("--debug", action="store_true", help="Enable DEBUG output")
dump_parser = dump.add_argument_group(title="Options")
dump_parser.add_argument("--gpo-name", action="store_true", help="Resolve and display GPO names")
dump_parser.add_argument("--list", action="store_true", help="List GPOs")
dump_parser.add_argument("--json", action="store_true", help="Display results in JSON format")
search_parser = dump.add_argument_group(title="Search")
search_parser.add_argument("--search", help="Search for a regex pattern in key and value")
search_parser.add_argument(
"--show",
action="store_true",
help="Display the values associated with search hits",
)
dump_filters = dump.add_argument_group(title="Filters")
dump_filters.add_argument("--domain", metavar="", help="Filter by one or more domains", nargs="+")
dump_filters.add_argument("--guid", metavar="", help="Filter by one or more GPO GUIDs", nargs="+")
dump_filters.add_argument(
"--file",
metavar="",
help="Filter by file type : " + ", ".join(file_map.keys()),
choices=file_map.keys(),
nargs="+",
)
# Analysis command
analysis = subparsers.add_parser("analysis", help="Analyse GPOs and identify potentially interesting settings")
analysis.add_argument("--debug", action="store_true", help="Enable DEBUG output")
analysis_parser = analysis.add_argument_group(title="Analysis Options")
analysis_parser.add_argument(
"--processed",
action="store_true",
help="Display processed settings (group, registry and privilege)",
)
analysis_parser.add_argument(
"--affected",
action="store_true",
help="List containers with at least one user or machine affected by a GPO",
)
analysis_parser.add_argument(
"--enrich",
action="store_true",
help="Augment BloodHound data with additional relationships/properties",
)
analysis_output = analysis.add_argument_group(title="Output options")
analysis_output.add_argument("--json", action="store_true", help="Format output as JSON")
analysis_output.add_argument("--gpo-name", action="store_true", help="Resolve and display GPO names")
analysis_target_parser = analysis.add_argument_group(title="Target object")
analysis_target_parser.add_argument("--container", metavar="ID/DN", help="Target container (DN or object ID)")
analysis_target_parser.add_argument("--computer", help="Target machine (machine.domain, DN or SID)")
analysis_target_parser.add_argument("--user", help="Target user (user@domain, DN or SID)")
analysis_container_parser = analysis.add_argument_group(title="Target Output")
analysis_container_parser.add_argument(
"--order",
action="store_true",
help="Show order of applied GPOs for a given container",
)
analysis_container_parser.add_argument("--show", action="store_true", help="Display GPO settings of ordered GPOs")
analysis_objects = [
"group",
"registry",
"privilege",
"gpppassword",
]
analysis_filters = analysis.add_argument_group(title="Filters")
analysis_filters.add_argument("--domain", metavar="", help="Filter by one or more domains", nargs="+")
analysis_filters.add_argument("--guid", metavar="", help="Filter by one or more GPO GUIDs", nargs="+")
analysis_filters.add_argument(
"--object",
metavar="",
help="Filter by object : " + ", ".join(analysis_objects),
choices=analysis_objects,
nargs="+",
)
analysis_filters.add_argument(
"--file",
metavar="",
help="Filter by file : " + ", ".join(file_map.keys()),
choices=file_map.keys(),
nargs="+",
)
if len(sys.argv) == 1:
parser.print_help()
sys.exit(1)
args = parser.parse_args()
# Logging options
logger = logging.getLogger()
logger.setLevel(logging.INFO)
stream = logging.StreamHandler(sys.stderr)
stream.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(levelname)s: %(message)s")
stream.setFormatter(formatter)
logger.addHandler(stream)
if args.debug is True:
logger.setLevel(logging.DEBUG)
# Check if the provided GPO file path exists
if not os.path.exists(args.sysvol_path):
logging.error("'%s' does not exist.", args.sysvol_path)
return
# Set the list of files to parse
if args.file:
policy_files = [file_map[file] for file in args.file]
else:
policy_files = list(file_map.values())
# Set the list of domains to parse
if args.domain:
domains = [domain.lower() for domain in args.domain]
else:
domains = None
gpohound_core = GPOHoundCore(
policy_files,
args.neo4j_host,
args.neo4j_user,
args.neo4j_pass,
args.neo4j_port,
)
if args.command == "dump":
gpohound_core.dump(
args.sysvol_path,
domains,
args.guid,
args.gpo_name,
args.json,
args.list,
args.search,
args.show,
)
elif args.command == "analysis":
gpohound_core.analyser(
args.sysvol_path,
domains,
args.guid,
args.processed,
args.affected,
args.enrich,
args.gpo_name,
args.order,
args.show,
args.object,
args.container,
args.computer,
args.user,
args.json,
)
```
## /gpohound/__main__.py
```py path="/gpohound/__main__.py"
#! /usr/bin/env python3
import gpohound
gpohound.main()
```
## /gpohound/analyser.py
```py path="/gpohound/analyser.py"
from base64 import b64decode
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
from gpohound.utils.utils import find_keys_recursive
from gpohound.analysers.groups import GroupAnalyser
from gpohound.analysers.registry import RegistryAnalyser
from gpohound.analysers.privilege_rights import PrivilegeRightsAnalyser
class GPOAnalyser:
"""Analyse GPOs"""
def __init__(self, ad_utils):
self.group_analyser = GroupAnalyser()
self.registry_analyser = RegistryAnalyser()
self.privilege_rights_analyser = PrivilegeRightsAnalyser(ad_utils)
def analyse(self, gpo_settings, proccessed_gpo, objects):
"""
Try to find interesting settings in GPO settings:
- Sensitive group
- Sensitive registry (network settings, password, etc...)
- Sensitive priviliege allowing privilege escalation
- Group Policy Preference Passwords
"""
output = {}
if proccessed_gpo:
if not objects or "group" in objects:
group_output = self.group_analyser.analyse(proccessed_gpo)
if group_output:
output["Groups"] = group_output
if not objects or "registry" in objects:
registry_output = self.registry_analyser.analyse(proccessed_gpo)
if registry_output:
output["Registry"] = registry_output
if not objects or "privilege" in objects:
privilege_rights_output = self.privilege_rights_analyser.analyse(proccessed_gpo)
if privilege_rights_output:
output["Privilege Rights"] = privilege_rights_output
if gpo_settings:
if not objects or "gpppassword" in objects:
cpasswords_output = self.find_gpp_password(gpo_settings)
if cpasswords_output:
output["GPP Password"] = cpasswords_output
return output
def find_gpp_password(self, gpo_settings):
"""
Find GPP Passwords in raw gpo settings
"""
output = {}
found_cpasswords = find_keys_recursive(gpo_settings, "cpassword")
if found_cpasswords:
for found_cpassword in found_cpasswords.get("cpassword", []):
b64_password = found_cpassword.get("value")
# Decrypt password if found
if b64_password:
password = self.decrypt_gpppassword(b64_password)
output["\\".join(found_cpassword.get("path"))] = {
"encrypted": b64_password,
"decrypted": password,
}
return output
def decrypt_gpppassword(self, b64_password):
"""
Decrypt GPP Password
"""
# Decode base64 cpassword
b64_password += "=" * ((4 - len(b64_password) % 4) % 4)
cpassword = b64decode(b64_password)
# Decryption key
key = bytes.fromhex("4e9906e8fcb66cc9faf49310620ffee8f496e806cc057990209b09a433b66c1b")
# Decrypt the password
ctx = AES.new(key, AES.MODE_CBC, b"\x00" * 16)
decrypted_password = unpad(ctx.decrypt(cpassword), ctx.block_size)
return decrypted_password.decode("utf-16-le")
```
## /gpohound/analysers/groups.py
```py path="/gpohound/analysers/groups.py"
import re
from gpohound.utils.utils import load_yaml_config
class GroupAnalyser:
"""Analyse group memberships"""
def __init__(self, config="config.analysis", config_file="group.yaml"):
self.privileged_groups = load_yaml_config(config, config_file)
def analyse(self, processed_gpo):
"""
Analyse group membership and get the following findings :
- Trustee added to sensitive groups
- User added to sensitive group on logon
- Renamed sensitive groups
- Trustee added to sensitive group and containing "System Defined Variables"
"""
results = {}
for policy_type in ["User", "Machine"]:
output_groups = {}
for config in ["Groups.xml", "Group Membership"]:
groups = processed_gpo.get(policy_type, {}).get(config, [])
# Iterates over groups
for group in groups:
if group:
group_sid = group.get("Group").get("sid")
# Only analyse group membership that does not remove the group
if group_sid in self.privileged_groups and group.get("Action") != "REMOVE":
output_groups.setdefault(group_sid, {})["sid"] = group_sid
output_groups.setdefault(group_sid, {})["name"] = self.privileged_groups[group_sid]["name"]
# Members in privileged group
if group.get("Members", {}):
output_groups.setdefault(group_sid, {}).setdefault("analysis", set()).add(
f"The following trustees are added to the \"{self.privileged_groups[group_sid]['name']}\" local group."
)
output_groups.setdefault(group_sid, {}).setdefault("references", set()).add(
self.privileged_groups[group_sid]["edge_reference"]
)
output_groups.setdefault(group_sid, {})["edge"] = self.privileged_groups[group_sid][
"edge"
]
# Iterates over group members
for member in group.get("Members", {}):
# Only if the user is added to the group
if member.get("action") == "ADD":
# Append member
entry = {
"sid": member.get("sid"),
"name": member.get("name"),
}
output_groups.setdefault(group_sid, {}).setdefault("Members", []).append(entry)
# Find System Defined Variables
name = member.get("name") if member.get("name") else ""
env_match = re.findall(r"(\%.*?\%)", name)
if env_match:
output_groups[group_sid].setdefault("analysis", set()).add(
'One or more member contain "System Defined Variable".\nTry sAMAccountName spoofing with a user, service account, group or computer (MAQ).'
)
output_groups[group_sid].setdefault("references", set()).add(
"https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-r2-and-2012/dn789194(v=ws.11)#preference-process-variables"
)
# User policy type with logged on user added to the group
if policy_type == "User" and group.get("Group").get("useraction") == "ADD":
output_groups.setdefault(group_sid, {}).setdefault("analysis", set()).add(
f"Any user who can log on with a fully interactive session will be assigned to the \"{group.get('Group').get('name')}\" local group."
)
output_groups.setdefault(group_sid, {}).setdefault("references", set()).add(
"https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-gppref/4b6788a7-c106-4e55-9cfc-1a52bb786e86"
)
# Privileged group being renamed
if group.get("Group").get("newname"):
output_groups.setdefault(group_sid, {}).setdefault("analysis", set()).add(
f"The privileged group is being renamed to \"{group.get('Group').get('newname')}\""
)
output_groups.setdefault(group_sid, {}).setdefault("references", set()).add(
"https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-gppref/4b6788a7-c106-4e55-9cfc-1a52bb786e86"
)
# Add findings to the output
for priv_group_sid, priv_group in output_groups.items():
if priv_group.get("analysis"):
priv_group["analysis"] = "\n\n".join(list(output_groups[priv_group_sid]["analysis"]))
priv_group["references"] = "\n".join(list(output_groups[priv_group_sid]["references"]))
results.setdefault(policy_type, []).append(priv_group)
return results
```
## /gpohound/analysers/privilege_rights.py
```py path="/gpohound/analysers/privilege_rights.py"
from gpohound.utils.utils import load_yaml_config
class PrivilegeRightsAnalyser:
"""Analyse Privilege Rights"""
def __init__(self, ad_utils, config="config.analysis", config_file="privilege_rights.yaml"):
self.ad_utils = ad_utils
self.privileged_groups = load_yaml_config(config, config_file)
def analyse(self, processed_gpo):
"""
Get trustees that can elevate their privilege using User Rights Assignment
"""
output = {}
privilege_rights = processed_gpo.get("Machine", {}).get("Privilege Rights")
if privilege_rights:
for privilege, trustees in privilege_rights.items():
not_default = []
if privilege in self.privileged_groups.keys():
dangereous_privilege = self.privileged_groups.get(privilege)
# Iterates over trustees that have dangerous privilege
for trustee in trustees:
sid = trustee.get("sid")
# Don't take into account default trustees and service account SID
if sid and (
sid in dangereous_privilege.get("default_trutees", []) or sid.startswith("S-1-5-8")
):
continue
not_default.append(trustee)
if not_default:
entry = {
"analysis": dangereous_privilege.get("analysis"),
"edge": dangereous_privilege.get("edge"),
"references": dangereous_privilege.get("references"),
"trustees": not_default,
}
output[privilege] = entry
if output:
return {"Machine": output}
return output
```
## /gpohound/analysers/registry.py
```py path="/gpohound/analysers/registry.py"
import re
import logging
from Crypto.Cipher import DES
from gpohound.utils.utils import load_yaml_config
class RegistryAnalyser:
"""Analyse registry keys content"""
def __init__(self, config="config.analysis", config_file="registry.yaml"):
self.registry_config = load_yaml_config(config, config_file)
def analyse(self, processed_gpo):
"""
Find interesting keys based on some conditions
"""
results = {}
for policy_type in ["User", "Machine"]:
for config in ["Registry.xml", "registry.pol", "Registry Values"]:
# Iterates over sensitive registry keys
for sensitive_registry in self.registry_config:
for registry in processed_gpo.get(policy_type, {}).get(config, []):
# Try to match sensitive registry condition with current key
match sensitive_registry.get("condition"):
case "value_equals":
if (
registry.get("Key").lower() == sensitive_registry.get("key").lower()
and str(registry.get("Data").lower())
== str(sensitive_registry.get("value")).lower()
):
entry = self.analysis_output(registry, sensitive_registry)
results.setdefault(policy_type, []).append(entry)
case "value_less_than":
if registry.get("Key").lower() == sensitive_registry.get("key").lower() and int(
registry.get("Data")
) < int(sensitive_registry.get("value")):
entry = self.analysis_output(registry, sensitive_registry)
results.setdefault(policy_type, []).append(entry)
case "key_ends_with":
if registry.get("Key").lower().endswith(sensitive_registry.get("key").lower()):
entry = self.analysis_output(registry, sensitive_registry)
results.setdefault(policy_type, []).append(entry)
case "key_regex":
pattern = re.compile(sensitive_registry.get("key").lower())
if pattern.search(registry.get("Key").lower()):
entry = self.analysis_output(registry, sensitive_registry)
results.setdefault(policy_type, []).append(entry)
return results
def analysis_output(self, registry, sensitive_registry):
"""
Return a dictionary for the analysed key and add property for bloodhound if specified
"""
# Analysis output
entry = {
"analysis": sensitive_registry.get("analysis"),
"regkey": f'{registry.get("Hive")}\\{registry.get("Key")}',
"value": registry.get("Data"),
"references": sensitive_registry.get("references"),
}
# If finding is a VNC password, try to decrypt it
if sensitive_registry.get("decrypt") == "VNC" and entry.get("value"):
decrypted_pass = self.decrypt_vnc_password(entry.get("value"))
if decrypted_pass:
entry.update({"VNC Password": decrypted_pass})
entry.update({"bloodhound_property": {sensitive_registry.get("bloodhound_property"): decrypted_pass}})
# Add a bloohound property if specified
elif sensitive_registry.get("bloodhound_property"):
entry.update({"bloodhound_property": sensitive_registry.get("bloodhound_property")})
return entry
def decrypt_vnc_password(self, cipher_hex):
"""
Decrypt VNC password with public key
"""
try:
# Convert hex strings to bytes
ciphertext = bytes.fromhex(cipher_hex)
key = bytes.fromhex("e84ad660c4721ae0")
iv = bytes.fromhex("0000000000000000")
# Decrypt using DES CBC mode
cipher = DES.new(key, DES.MODE_CBC, iv)
plaintext = cipher.decrypt(ciphertext).rstrip(b"\x00").decode("utf-8")
# Return as string (decode assuming ASCII or fallback to latin1 for raw binary)
return plaintext
except ValueError as error:
logging.debug("Error decrypting VNC password : %s", error)
return None
```
## /gpohound/core.py
```py path="/gpohound/core.py"
import json
import copy
import sys
import logging
from gpohound.parser import GPOParser
from gpohound.processor import GPOProcessor
from gpohound.analyser import GPOAnalyser
from gpohound.enricher import BloodHoundEnricher
from gpohound.utils.utils import (
search_keys_values,
print_dict_as_tree,
print_processed,
print_analysed,
merge_nested_dicts,
)
from gpohound.utils.bloodhound import BloodHoundConnector
from gpohound.utils.ad import ActiveDirectoryUtils
class GPOHoundCore:
"""
Class for parsing, processing and analysis of GPOs
"""
def __init__(
self,
policy_files,
neo4j_host=None,
neo4j_user=None,
neo4j_password=None,
neo4j_port=None,
):
# BloodHound interactions
self.bloodhound_connector = BloodHoundConnector(neo4j_host, neo4j_user, neo4j_password, neo4j_port)
self.bloodhound_enricher = BloodHoundEnricher(self.bloodhound_connector)
# Active Directory utilities
self.ad_utils = ActiveDirectoryUtils(self.bloodhound_connector)
# GPO parser, processor and analyser
self.gpo_parser = GPOParser(policy_files)
self.gpo_processor = GPOProcessor(self.ad_utils)
self.gpo_analyser = GPOAnalyser(self.ad_utils)
def dump(
self,
sysvol_path,
domains=None,
guids=None,
gpo_name=None,
print_json=None,
list_gpos=None,
search=None,
show=None,
):
"""
Dump GPO files and enrich data with bloodhound
"""
if not self.ad_utils.bloodhound.connection and gpo_name:
logging.info("This command requires a working bloodhound connection")
sys.exit()
self.gpo_parser.parse_domain_policies(sysvol_path)
if not self.gpo_parser.policies:
logging.info("No GPOs were found...")
sys.exit()
output = copy.deepcopy(self.gpo_parser.policies)
# Only keep the specified domains
if domains:
tmp = {}
for domain in domains:
if domain in output:
tmp.update({domain: output[domain]})
output = tmp
# Only keep the specified GUIDs
if guids:
extracted = {}
for domain, gpos in output.items():
tmp = {}
for guid in guids:
guid = "{" + guid.upper().strip("{").strip("}") + "}"
if guid in gpos:
tmp.setdefault(domain, {}).setdefault(guid, {}).update(gpos[guid])
extracted.update(tmp)
output = extracted
# Searches in the output with a regex
if search:
output = search_keys_values(output, search, show)
# Resolves GPO names
if gpo_name and not search:
output = self.ad_utils.resolve_gpo_name(output)
# Only list the GPO GUIDs/names
if list_gpos:
tmp_dict = {}
for domain, gpos in output.items():
tmp_list = []
for guid, data in gpos.items():
gpo_name = data.get("GPO Name")
if gpo_name:
tmp_list.append(f"{guid}: {gpo_name}")
else:
tmp_list.append(guid)
tmp_dict[domain] = tmp_list
output = tmp_dict
# Print output
if not output:
logging.info("No GPOs were found for the given filter(s)...")
sys.exit()
if print_json:
logging.info(json.dumps(output, indent=4))
else:
if search:
print_dict_as_tree("Search results", output)
else:
print_dict_as_tree("GPOs", output)
def analyser(
self,
sysvol_path,
domains=None,
guids=None,
processed=False,
affected=False,
enrich=False,
gpo_name=False,
order=False,
show=False,
objects=None,
container=None,
computer=None,
user=None,
print_json=False,
):
"""
Process the GPO and groups settings types
Analysis of vulnerabilities in the GPOs settings
Enrich bloodhooud with found vulnerabilites
"""
if not self.ad_utils.bloodhound.connection and (
affected or order or enrich or container or user or computer or gpo_name or show
):
logging.info("This command requires a working bloodhound connection")
sys.exit()
if not self.ad_utils.bloodhound.apoc and enrich:
logging.info(
"This command requires to have APOC installed for Neo4j. Check the GPOHound documentation for more information"
)
sys.exit()
if order and not (container or computer or user):
logging.info("You need to specify a target...")
sys.exit()
self.gpo_parser.parse_domain_policies(sysvol_path)
if not self.gpo_parser.policies:
logging.info("No GPOs were found...")
sys.exit()
output_show = {}
output_order = {}
output_proccessed = {}
output_analysis = {}
output_enrichment = {}
# Guids to parse
if guids:
guids = ["{" + guid.upper().strip("{").strip("}") + "}" for guid in guids]
if container or computer or user:
if container:
found_container = self.ad_utils.find_container(container)
elif computer:
found_container = self.ad_utils.find_trustee_container(computer)
else:
found_container = self.ad_utils.find_trustee_container(user)
if found_container:
container_id = found_container.get("objectid")
container_dn = found_container.get("distinguishedname")
domain_sid = found_container.get("domainsid")
domain = self.ad_utils.find_by_sid(domain_sid).get("name", "").lower()
ordered_gpos = self.ad_utils.container_inheritance(container_id)
if show:
gpo_inheritance = {}
for idx, gpo in enumerate(ordered_gpos, start=1):
if "name" in gpo:
gpo_guid = "{" + gpo["gpcpath"].split("{", 1)[1].split("}")[0] + "}"
if gpo_guid in self.gpo_parser.policies[domain]:
gpo_name = gpo["name"]
title = f"{idx} - {gpo_guid}: {gpo_name}"
data = self.gpo_parser.policies[domain][gpo_guid]
if data:
if container:
gpo_inheritance[title] = data
elif computer and data.get("Machine"):
gpo_inheritance[title] = data.get("Machine")
elif user and data.get("User"):
gpo_inheritance[title] = data.get("User")
else:
title = f"{idx} - Empty GPO"
gpo_inheritance[title] = None
else:
title = f"{idx} - Unknown GPO"
gpo_inheritance[title] = None
output_show.update({container_dn: gpo_inheritance})
elif order:
gpo_inheritance = []
for idx, gpo in enumerate(ordered_gpos, start=1):
if "name" in gpo:
gpo_guid = "{" + gpo["gpcpath"].split("{", 1)[1].split("}")[0] + "}"
gpo_name = gpo["name"]
gpo_inheritance.append(f"{idx} - {gpo_guid}: {gpo_name}")
else:
gpo_inheritance.append(f"{idx} - Unknown GPO")
output_order.update({container_dn: gpo_inheritance})
elif domain and domain_sid and domain in self.gpo_parser.policies:
gpo_settings = {}
for gpo in ordered_gpos:
if "name" in gpo:
gpo_guid = "{" + gpo["gpcpath"].split("{", 1)[1].split("}")[0] + "}"
if gpo_guid in self.gpo_parser.policies[domain]:
gpo_name = gpo["name"]
gpo_settings = self.gpo_parser.policies[domain][gpo_guid]
if gpo_settings:
proccessed_gpo = self.gpo_processor.process(gpo_settings, objects, domain_sid)
if proccessed_gpo and processed:
output_proccessed.setdefault(domain, {}).setdefault(gpo_guid, {}).update(
proccessed_gpo
)
elif proccessed_gpo:
analysis = self.gpo_analyser.analyse(gpo_settings, proccessed_gpo, objects)
if analysis:
output_analysis.setdefault(domain, {}).setdefault(gpo_guid, {}).update(
analysis
)
else:
# Iterates over domains
for domain, gpos in self.gpo_parser.policies.items():
containers_to_enrich = {}
domain_sid = self.ad_utils.domain_to_sid(domain)
if domains and domain not in domains:
continue
# Iterates over GPOs
for gpo_guid, gpo_settings in gpos.items():
if guids and gpo_guid not in guids:
continue
# Process the GPOs
proccessed_gpo = self.gpo_processor.process(gpo_settings, objects, domain_sid)
# Analyse the GPOs settings
if proccessed_gpo and processed:
output_proccessed.setdefault(domain, {}).setdefault(gpo_guid, {}).update(proccessed_gpo)
else:
analysis = self.gpo_analyser.analyse(gpo_settings, proccessed_gpo, objects)
if analysis:
# Get container list affected by the GPO
if (affected or enrich) and domain_sid:
found_containers = self.ad_utils.get_containers_affected_by_gpo(gpo_guid, domain_sid)
if found_containers:
containers_dn = [
container.get("distinguishedname") for container in found_containers
]
# Container list for enrichement
for container in found_containers:
containers_to_enrich[container.get("objectid")] = container
# Add container list to processed GPO and vulnerability outputs
if affected:
output_analysis.setdefault(domain, {}).setdefault(gpo_guid, {}).setdefault(
"Affected Containers", []
).extend(containers_dn)
output_analysis.setdefault(domain, {}).setdefault(gpo_guid, {}).update(analysis)
else:
output_analysis.setdefault(domain, {}).setdefault(gpo_guid, {}).update(analysis)
# Enrich bloodhound with found vulnerabilities
if enrich and domain_sid and containers_to_enrich:
enrichement = self.enrich(containers_to_enrich, domain, domain_sid, objects)
if enrichement:
output_enrichment.setdefault(domain, {}).update(enrichement)
# Print processed settings
if processed:
if not output_proccessed:
logging.info("No processed GPO settings were found...")
sys.exit()
if gpo_name:
output_proccessed = self.ad_utils.resolve_gpo_name(output_proccessed)
if print_json:
print(json.dumps(output_proccessed, indent=4))
else:
print_processed(output_proccessed)
# Print enrichement output
elif enrich:
if not output_enrichment:
logging.info("No GPOs found to enrich BloodHound data...")
sys.exit()
if print_json:
print(json.dumps(output_enrichment, indent=4))
else:
print_dict_as_tree("Enrichement Output", output_enrichment)
# Print GPO settings in order
elif show:
if output_show:
if print_json:
print(json.dumps(output_show, indent=4))
else:
print_dict_as_tree("Applied GPO in order ", output_show)
# Print GPO order output
elif order:
if not output_order:
logging.info("No order for this target...")
sys.exit()
if print_json:
print(json.dumps(output_order, indent=4))
else:
print_dict_as_tree("GPO Order ", output_order)
# Print analysis output
elif output_analysis:
if gpo_name:
output_analysis = self.ad_utils.resolve_gpo_name(output_analysis)
if print_json:
print(json.dumps(output_analysis, indent=4))
else:
print_analysed(output_analysis)
else:
logging.info("No results were found for the specified settings...")
sys.exit()
def enrich(self, containers, domain, domain_sid, objects):
"""
Apply found vulnerabilies to containers trustees
"""
output = {}
# Iterates over containers
for container_id, container in containers.items():
results = {}
ordered_gpos = self.ad_utils.container_inheritance(container_id)
if ordered_gpos:
for gpo in ordered_gpos:
if "name" in gpo:
gpo_guid = "{" + gpo["gpcpath"].split("{", 1)[1].split("}")[0] + "}"
if gpo_guid in self.gpo_parser.policies[domain]:
gpo_settings = self.gpo_parser.policies[domain][gpo_guid]
proccessed_gpo = self.gpo_processor.process(gpo_settings, objects, domain_sid)
if proccessed_gpo:
# Analyse GPOs
analysis = self.gpo_analyser.analyse(gpo_settings, proccessed_gpo, objects)
if analysis:
# Enrich bloodhound data
result = self.bloodhound_enricher.enrich(container_id, analysis, domain_sid)
if result:
results = merge_nested_dicts(results, result)
if results:
output.setdefault(container.get("distinguishedname"), {}).update(results)
return output
```
## /gpohound/enricher.py
```py path="/gpohound/enricher.py"
class BloodHoundEnricher:
"""
Enrich BloodHound data
"""
def __init__(self, bloodhound_connector):
self.bloodhound = bloodhound_connector
def enrich(self, container_id, analysed_gpo, domain_sid):
"""
Enrich BloodHound with the interesting settings found in a analaysed GPOs
"""
results = {}
if "Groups" in analysed_gpo:
for policy_type, analysed_settings in analysed_gpo["Groups"].items():
for group in analysed_settings:
group_sid = group.get("sid")
edge = group.get("edge")
if group_sid and edge:
for member in group.get("Members", []):
member_sid = member.get("sid")
if member_sid:
# Try to add new relationship between the members of the groups and the machines in the container
outputs = self.bloodhound.add_edges(domain_sid, container_id, member_sid, edge)
if outputs:
if not isinstance(outputs, list):
results.setdefault("Groups", {}).setdefault(policy_type, {}).setdefault(
edge, []
).append(f'{outputs["t"]["name"]} -> {outputs["c"]["name"]}')
else:
for output in outputs:
results.setdefault("Groups", {}).setdefault(policy_type, {}).setdefault(
edge, []
).append(f'{output["t"]["name"]} -> {output["c"]["name"]}')
if "Registry" in analysed_gpo:
for policy_type, analysed_settings in analysed_gpo["Registry"].items():
for registry in analysed_settings:
bloodhound_property = registry.get("bloodhound_property")
if bloodhound_property:
# Try to add new property to the machines in the container
((key, value),) = bloodhound_property.items()
outputs = self.bloodhound.add_extra_property(container_id, key, value)
if outputs:
if not isinstance(outputs, list):
results.setdefault("Registry", {}).setdefault(policy_type, {}).setdefault(
f"{key} is {value}", []
).append(f'{outputs["n"]["name"]}')
else:
for output in outputs:
results.setdefault("Registry", {}).setdefault(policy_type, {}).setdefault(
f"{key} is {value}", []
).append(f'{output["n"]["name"]}')
if "Privilege Rights" in analysed_gpo:
for policy_type, analysed_settings in analysed_gpo["Privilege Rights"].items():
for privilege in analysed_settings.values():
edge = privilege.get("edge")
for trustee in privilege.get("trustees", []):
trustee_sid = trustee.get("sid")
if trustee_sid:
# Try to add new relationship between the privileged trustee and the machines in the container
outputs = self.bloodhound.add_edges(domain_sid, container_id, trustee_sid, edge)
if outputs:
if not isinstance(outputs, list):
results.setdefault("Privilege Rights", {}).setdefault(policy_type, {}).setdefault(
edge, []
).append(f'{outputs["t"]["name"]} -> {outputs["c"]["name"]}')
else:
for output in outputs:
results.setdefault("Privilege Rights", {}).setdefault(
policy_type, {}
).setdefault(edge, []).append(f'{output["t"]["name"]} -> {output["c"]["name"]}')
return results
```
## /gpohound/parser.py
```py path="/gpohound/parser.py"
import os
import re
import logging
from gpohound.parsers.xml_files import XMLParser
from gpohound.parsers.pol_files import POLParser
from gpohound.parsers.inf_files import INFParser
from gpohound.parsers.ini_files import INIParser
from gpohound.parsers.csv_files import CSVParser
class GPOParser:
"""
Class to parse the files contain in the Policies
"""
def __init__(self, policy_files):
self.policy_files = [file.lower() for file in policy_files]
self.scripts_folder = ["Startup", "Shutdown", "Logon", "Logoff"]
self.xmlparser = XMLParser()
self.polparser = POLParser()
self.infparser = INFParser()
self.iniparser = INIParser()
self.csvparser = CSVParser()
self.domain_policies_info = {}
self.policies = {}
def get_files_info(self, policy_path):
"""
Get informations on the files to parse for a GPO
"""
files_info = []
# Walk through the directories to find files
for root, _, files in os.walk(policy_path):
for file in files:
path = [items for items in os.path.join(root, file).split(os.sep)]
if file.lower() in self.policy_files:
files_info.append(self.file_info(root, policy_path, file))
elif (
("scripts.ini" in self.policy_files or "PSscripts.ini" in self.policy_files)
and path[-3] == "Scripts"
and path[-2] in self.scripts_folder
):
script = self.file_info(root, policy_path, file)
if script:
script["type"] = path[-2]
files_info.append(script)
return files_info
def file_info(self, root, policy_path, file):
"""
Get information on the file in the file system
"""
# Retrive information on the file
full_path = os.path.join(root, file)
relative_path = full_path.replace(policy_path, "")
relative_path_list = [items.lower() for items in relative_path.split(os.sep)]
policy_type = ""
if "machine" in relative_path_list:
policy_type = "Machine"
elif "user" in relative_path_list:
policy_type = "User"
size = os.path.getsize(full_path)
file_name, file_extension = os.path.splitext(file)
# Store GPO file information
entry = {
"name": file_name,
"extension": file_extension,
"relative_path": relative_path,
"policy_type": policy_type,
"full_path": full_path,
"size": f"{size} bytes",
}
return entry
def find_policy_info(self, sysvol_path):
"""
Built a dictionary of files to be parsed by domain and GPO GUID
"""
policy_info = {}
# Regular expression to match the GUID pattern inside /Policies/
pattern = re.compile(r"(.*?/([^/]+)/Policies/(\{[0-9A-Fa-f-]{36}\}))$")
# Walk through the directories
for dirpath, dirnames, _ in os.walk(sysvol_path):
for dirname in dirnames:
full_path = os.path.join(dirpath, dirname)
match_path = pattern.search(full_path)
# Get file path that match the pattern
if match_path:
policy_path = match_path.group(1)
domain = match_path.group(2)
guid = match_path.group(3)
files = self.get_files_info(policy_path)
# Store the files path by domain and GPO guids
policy_info.setdefault(domain, {}).update({guid: {"path": policy_path, "files": files}})
return policy_info
def parse_domain_policies(self, sysvol_path):
"""
Extract settings from SYSVOL to dictionary
"""
results = {}
domain_policies_info = self.find_policy_info(sysvol_path)
for domain, policies_info in domain_policies_info.items():
for policy_guid, policy_data in policies_info.items():
policy = self.parse_policy(policy_guid, policy_data)
if policy:
results.setdefault(domain.lower(), {}).update(policy)
if results:
self.policies.update(results)
def parse_policy(self, policy_guid, policy_data):
"""
Parse all the files in a GPO to dictionary
"""
results = {}
if not policy_data["files"]:
return None
# Iterates over the files in a GPO
for policy_file in policy_data["files"]:
configuration = {}
extension = policy_file["extension"].lower()
# Parse file based on file extension
match extension:
case ".xml":
configuration = self.xmlparser.parse(policy_file["full_path"])
case ".pol":
configuration = self.polparser.parse(policy_file["full_path"], policy_file["policy_type"])
case ".inf":
configuration = self.infparser.parse(policy_file["full_path"])
case ".ini":
configuration = self.iniparser.parse(policy_file["full_path"])
case ".csv":
configuration = self.csvparser.parse(policy_file["full_path"])
case _:
if policy_file.get("type") in self.scripts_folder:
try:
raw = open(policy_file["full_path"], "r", encoding="utf-8").read()
configuration = {
policy_file.get("type"): {
"file": policy_file["relative_path"],
"content": raw,
}
}
except UnicodeDecodeError as error:
logging.debug("Could not decode file : %s", error)
except FileNotFoundError as error:
logging.debug("File not found : %s", error)
continue
if configuration and policy_file["policy_type"] == "Machine":
results.setdefault("Machine", {}).update(configuration)
elif configuration and policy_file["policy_type"] == "User":
results.setdefault("User", {}).update(configuration)
elif configuration:
results = configuration
return {policy_guid.upper(): results}
```
## /gpohound/parsers/csv_files.py
```py path="/gpohound/parsers/csv_files.py"
import csv
import logging
from gpohound.utils.utils import load_yaml_config
class CSVParser:
"""Parse the audit policy file"""
def __init__(self, config="config.gpo_files_structure.csv") -> None:
self.config = load_yaml_config(config)
def parse(self, file_path):
"""
Parse the audit.csv file
"""
# Verify if the files needs to be included in the output
if "include" in self.config["Audit"]:
extracted_data = []
# Convert the CSV table to a directory
with open(file_path, "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
try:
next(reader)
except StopIteration:
logging.debug("Unable to parse CSV file : %s", file_path)
return {"audit.csv": None }
# Filter column that are not in the config
for line in reader:
extracted_data.append({key: line[key] for key in self.config["Audit"]["attributes"] if key in line})
return {"audit.csv": extracted_data}
return None
```
## /gpohound/parsers/inf_files.py
```py path="/gpohound/parsers/inf_files.py"
import re
from gpohound.utils.utils import load_yaml_config
class INFParser:
"""Parse GptTmpl.inf"""
def __init__(self, config="config.gpo_files_structure.inf") -> None:
# Load INF files
self.config = load_yaml_config(config)
# Regular expressions to identify sections and key/value pairs
self.section_pattern = re.compile(r"\[\s*(.*?)\s*\]")
# Registry Values types
self.reg_types = {
"0": "REG_NONE",
"1": "REG_SZ",
"2": "REG_EXPAND_SZ",
"3": "REG_BINARY",
"4": "REG_DWORD",
"5": "REG_DWORD_BIG_ENDIAN",
"6": "REG_LINK",
"7": "REG_MULTI_SZ",
"8": "REG_RESOURCE_LIST",
"9": "REG_FULL_RESOURCE_DESCRIPTOR",
"10": "REG_RESOURCE_REQUIREMENTS_LIST",
"11": "REG_QWORD",
}
def parse(self, file_path):
"""
Read an INF file and populate the results dictionary with its contents
"""
current_section = None
with open(file_path, "r", encoding="utf-16") as f:
results = {}
for line in f:
line = line.strip()
# Ignore empty lines or comments
if not line or line.startswith(";"):
continue
# Check if the line is a section
section_match = self.section_pattern.match(line)
if section_match:
# Extract the section name
current_section = section_match.group(1)
if current_section not in results:
results[current_section] = {}
continue
# Parse Key = Value settings
if self.config.get(current_section).get("type") == "key-value":
key_value_match = line.split("=", 1)
if len(key_value_match) == 2:
key, value = key_value_match
key = key.strip().strip('"')
value = value.strip()
if "include" in self.config[current_section]:
# Privilege Rights
if (
current_section == "Privilege Rights"
and key in self.config[current_section]["attributes"]
):
results[current_section][key] = value.split(",")
# Group Membership
elif current_section == "Group Membership":
values = value.split(",")
if not value:
continue
if "__Members" in key:
group_name = key.replace("__Members", "")
membership = "Members"
elif "__Memberof" in key:
group_name = key.replace("__Memberof", "")
membership = "Memberof"
else:
continue
if membership not in self.config[current_section]["attributes"]:
continue
results.setdefault(current_section, {}).setdefault(group_name, {}).update(
{membership: values}
)
# Registry Values
elif current_section == "Registry Values":
value_type, registry_value = value.split(",", 1)
if key.startswith("USER"):
hive = "HKEY_USERS"
else:
hive = "HKEY_LOCAL_MACHINE"
entry = {
"Hive": hive,
"Type": self.reg_types[value_type],
"Data": registry_value.strip('"'),
}
entry = {
key: {attr: entry[attr] for attr in self.config[current_section]["attributes"]}
}
results[current_section].update(entry)
# Simple Key Value
elif key in self.config[current_section]["attributes"]:
results[current_section][key] = value.strip('"')
# Parse comma-separated settings
if self.config.get(current_section).get("type") == "comma-separated":
key, value = line.split(",", 1)
key = key.strip('"')
attr1, attr2 = [items.strip('"') for items in value.split(",", 1)]
# Registry Keys and File Security
if current_section == "Registry Keys" or current_section == "File Security":
entry = {"PermPropagationMode": attr1, "AclString": attr2}
entry = {key: {attr: entry[attr] for attr in self.config[current_section]["attributes"]}}
results[current_section].update(entry)
# Service General Setting
elif current_section == "Service General Setting":
entry = {"AclString": attr1, "StartupMode": attr2}
entry = {key: {attr: entry[attr] for attr in self.config[current_section]["attributes"]}}
results[current_section].update(entry)
if results:
return {"GptTmpl.inf": results}
return None
```
## /gpohound/parsers/ini_files.py
```py path="/gpohound/parsers/ini_files.py"
import os
import configparser
from gpohound.utils.utils import load_yaml_config
class INIParser:
"""Parse .ini files"""
def __init__(self, config="config.gpo_files_structure.ini") -> None:
self.config = load_yaml_config(config)
def parse(self, file_path):
"""
Parses an INI file based on YAML configuration and specific file rules.
Args:
file_path (str): Path to the INI file.
policy_mode (str, optional): 'computer' or 'user' for Scripts.ini and Psscripts.ini modes. Defaults to None.
Returns:
dict: Parsed data structured according to the configuration.
"""
filename = os.path.basename(file_path).lower()
if filename == "gpt.ini":
return self._parse_gpt(file_path)
elif filename == "scripts.ini":
return self._parse_scripts(file_path)
elif filename == "psscripts.ini":
return self._parse_psscripts(file_path)
else:
return None
def _parse_gpt(self, file_path):
"""Parses GPT.ini based on the YAML configuration."""
output = {}
ini_parser = configparser.ConfigParser(allow_no_value=True)
with open(file_path, "r", encoding="utf-8", errors="replace") as ini_file:
ini_lines = [
line for line in ini_file if line.strip() and not line.strip().startswith(("#", ";"))
] # Remove comments and empty lines
ini_parser.read_string("".join(ini_lines))
for section, rules in self.config.items():
if "include" in rules:
output[section] = {}
attributes = rules.get("attributes", [])
for attr in attributes:
if attr in ini_parser[section]: # Only add attributes that exist in the INI file
output[section][attr] = ini_parser[section][attr]
return {"GPT.ini": output}
def _parse_scripts(self, file_path):
"""Parses Scripts.ini based on Microsoft's 2.2.2 Syntax."""
valid_sections = ["Startup", "Shutdown", "Logon", "Logoff"]
ini_parser = configparser.ConfigParser(allow_no_value=True, delimiters=["="])
with open(file_path, "r", encoding="utf-16le") as f:
content = f.read().lstrip("\ufeff") # Remove BOM if present
ini_lines = [line for line in content.splitlines() if line.strip()] # Remove empty lines
ini_parser.read_string("\n".join(ini_lines))
output = {}
for section in ini_parser.sections():
if section not in valid_sections:
continue # Ignore invalid sections
commands = {}
for key, value in ini_parser.items(section):
if key.lower().endswith("cmdline"):
index = key[:-7] # Remove 'CmdLine' to get index
cmd_key = f"{index}cmdline"
param_key = f"{index}parameters"
if cmd_key in ini_parser[section] and param_key in ini_parser[section]:
commands[index] = {
"CmdLine": ini_parser[section][cmd_key],
"Parameters": ini_parser[section][param_key],
}
output[section] = dict(sorted(commands.items())) # Ensure sorted execution order
return {"Scripts.ini": output}
def _parse_psscripts(self, file_path):
"""Parses Psscripts.ini based on Microsoft's 2.2.3 Syntax."""
valid_sections = [
"Startup",
"Shutdown",
"ScriptsConfig",
"Logon",
"Logoff",
"ScriptsConfig",
]
ini_parser = configparser.ConfigParser(allow_no_value=True, delimiters=["="])
with open(file_path, "r", encoding="utf-16le") as f:
content = f.read().lstrip("\ufeff") # Remove BOM if present
ini_lines = [line for line in content.splitlines() if line.strip()] # Remove empty lines
ini_parser.read_string("\n".join(ini_lines))
output = {}
for section in ini_parser.sections():
if section not in valid_sections:
continue # Ignore invalid sections
if section == "ScriptsConfig":
config_settings = {}
for key, value in ini_parser.items(section):
if key in ["startexecutepsfirst", "endexecutepsfirst"]:
config_settings[key] = value.lower() == "true"
if config_settings:
output[section] = config_settings
else:
commands = {}
for key, value in ini_parser.items(section):
if key.endswith("cmdline"):
index = key[:-7] # Remove 'CmdLine' to get index
cmd_key = f"{index}cmdline"
param_key = f"{index}parameters"
if cmd_key in ini_parser[section] and param_key in ini_parser[section]:
commands[index] = {
"CmdLine": ini_parser[section][cmd_key],
"Parameters": ini_parser[section][param_key],
}
output[section] = dict(sorted(commands.items())) # Ensure sorted execution order
return {"PSscripts.ini": output}
```
## /gpohound/parsers/pol_files.py
```py path="/gpohound/parsers/pol_files.py"
import struct
from gpohound.utils.utils import load_yaml_config
class POLParser:
"""Parse Registry.pol files"""
def __init__(self, config="config.gpo_files_structure.pol"):
self.config = load_yaml_config(config)
self.magic_string = b"\x50\x52\x65\x67\x01\x00\x00\x00"
self.reg_types = {
0: "REG_NONE",
1: "REG_SZ",
2: "REG_EXPAND_SZ",
3: "REG_BINARY",
4: "REG_DWORD",
5: "REG_DWORD_BIG_ENDIAN",
6: "REG_LINK",
7: "REG_MULTI_SZ",
8: "REG_RESOURCE_LIST",
9: "REG_FULL_RESOURCE_DESCRIPTOR",
10: "REG_RESOURCE_REQUIREMENTS_LIST",
11: "REG_QWORD",
}
def reg_value_to_string(self, keytype, keyvalue):
"""
Convert registry values to string if possible
"""
# Remove the "0x" prefix if present
if keyvalue.upper().startswith("0X"):
hex_str = keyvalue[2:]
else:
hex_str = keyvalue
try:
if keytype in ["REG_DWORD", "REG_QWORD"]:
num_val = int(hex_str, 16)
return str(num_val)
elif keytype in ["REG_SZ", "REG_EXPAND_SZ"]:
b = bytes.fromhex(hex_str)
return b.decode("utf-8", errors="replace").replace("\x00", "")[::-1]
elif keytype == "REG_MULTI_SZ":
b = bytes.fromhex(hex_str)
return b.decode("utf-8", errors="replace").replace("\x00\x00\x00", ",").replace("\x00", "")[::-1]
elif keytype == "REG_NONE":
return None
else:
return keyvalue
# If we can not convert just return the hex value
except ValueError:
return keyvalue
def parse(self, pol_file, policy_type):
"""Parse contents of Registry.pol file to a dictionary"""
results = {}
with open(pol_file, "rb") as f:
file_data = f.read()
body = file_data[len(self.magic_string) :]
while len(body) > 0:
if body[0:2] != b"[\x00":
print('Error: Entry does not start with "["')
break
body = body[2:]
# Key
key, _, body = body.partition(b";\x00")
key = key.decode("utf-16-le").strip("\x00")
# Value
value, _, body = body.partition(b";\x00")
value = value.decode("utf-16-le").strip("\x00")
# Type
reg_type = body[0:4]
body = body[4 + 2 :] # len of field plus semicolon delimieter
reg_type = struct.unpack(" None:
self.config = load_yaml_config(config_folder)
def find_child_config(self, tag, config):
"""
Recursively search all child configurations to find the first match for a given tag.
This does NOT check the parent but looks through all child nodes in the config.
"""
if not isinstance(config, dict) or "elements" not in config:
return {}
if tag in config["elements"]:
return config["elements"][tag]
# Search recursively in all child configs
for value in config["elements"].values():
if isinstance(value, dict):
found_config = self.find_child_config(tag, value)
if found_config:
return found_config
return None # Default to an empty config if nothing is found
def parse_element(self, element, config):
"""
Recursively parse an XML element based on the configuration.
"""
if config and "include" not in config:
return None
data = {}
# Extract attributes
if config.get("attributes"):
for attr in config["attributes"]:
if attr in element.attrib:
data[attr] = element.attrib[attr]
elif element.attrib:
for attr in element.attrib:
data[attr] = element.attrib[attr]
if element.text and not element.text.replace("\n", "").isspace():
data = element.text
# Process child elements
all_child_elements = element.findall("*")
for child in all_child_elements:
child_config = self.find_child_config(child.tag, config)
if child_config:
# Parse based on found config
if "include" in child_config:
if len(element.findall(child.tag)) > 1:
if child.tag not in data:
data[child.tag] = []
data[child.tag].append(self.parse_element(child, child_config))
else:
data[child.tag] = self.parse_element(child, child_config)
else:
# If no config is found, get all the data from the unknown child element
if len(element.findall(child.tag)) > 1:
if child.tag not in data:
data[child.tag] = []
data[child.tag].append(self.parse_element(child, {}))
else:
data[child.tag] = self.parse_element(child, {})
return data
def parse(self, xml_file):
"""
Parse the XML file based on the YAML configuration.
"""
tree = ET.parse(xml_file)
root = tree.getroot()
if root.tag not in self.config:
return None
parsed_policy = self.parse_element(root, self.config[root.tag])
if not parsed_policy:
return None
filename = os.path.basename(xml_file)
policy_data = {filename: parsed_policy}
return policy_data
```
## /gpohound/processor.py
```py path="/gpohound/processor.py"
from gpohound.processors.group_membership import GroupMembershipProcessor
from gpohound.processors.xml_groups import XMLGroupsProcessor
from gpohound.processors.registry_values import RegistryValuesProcessor
from gpohound.processors.xml_registry import XMLRegistryProcessor
from gpohound.processors.pol_registry import POLRegistryProcessor
from gpohound.processors.privilege_rights import PrivilegeRightsProcessor
class GPOProcessor:
"""
Process the GPOs settings for analysis
"""
def __init__(self, ad_utils):
self.ad_utils = ad_utils
self.processors = {}
self.processors["Group Membership"] = GroupMembershipProcessor(ad_utils).process
self.processors["Groups.xml"] = XMLGroupsProcessor(ad_utils).process
self.processors["Registry Values"] = RegistryValuesProcessor().process
self.processors["Registry.xml"] = XMLRegistryProcessor().process
self.processors["registry.pol"] = POLRegistryProcessor().process
self.processors["Privilege Rights"] = PrivilegeRightsProcessor(ad_utils).process
def process(self, gpo_settings, objects, domain_sid):
"""
Process GPO and group settings that impact the same objects
"""
# Move the sections of GptTmpl.inf to gpo_settings root
gptemplate = gpo_settings.get("Machine", {}).get("GptTmpl.inf", {})
if gptemplate:
gpo_settings["Machine"].update(gptemplate)
del gpo_settings["Machine"]["GptTmpl.inf"]
# Extract settings
processed_settings = {}
for config in ["User", "Machine"]:
for setting_type, setting in gpo_settings.get(config, {}).items():
if setting:
if (not objects or "group" in objects) and setting_type in [
"Group Membership",
"Groups.xml",
]:
processor = self.processors.get(setting_type, domain_sid)
output = processor(setting, domain_sid)
elif (not objects or "registry" in objects) and setting_type in [
"Registry Values",
"Registry.xml",
"registry.pol",
]:
processor = self.processors.get(setting_type)
output = processor(setting)
elif (not objects or "privilege" in objects) and setting_type == "Privilege Rights":
processor = self.processors.get(setting_type)
output = processor(setting)
else:
continue
if output and isinstance(output, list):
processed_settings.setdefault(config, {}).setdefault(setting_type, []).extend(output)
elif output and isinstance(output, dict):
processed_settings.setdefault(config, {})[setting_type] = output
return processed_settings
```
## /gpohound/processors/group_membership.py
```py path="/gpohound/processors/group_membership.py"
class GroupMembershipProcessor:
"""Process Group Membership"""
def __init__(self, ad_utils=None):
self.ad_utils = ad_utils
def process(self, settings, domain_sid):
"""
Extract the "Group Membership" settings that will be applied to a computer
Output the settings applied to group and there impact on previous setting :
- "Members" is processed first : "Members" delete the previous group members
- "MemberOf" is processed second : "MemberOf" add group member
"""
output = []
members_of = {}
# Extract "Members" settings
for group, membership in settings.items():
if group.startswith("*"):
sid = group.strip("*")
name = self.ad_utils.get_trustee(sid).get("name")
group_dict = {"sid": sid, "name": name}
else:
sid = self.ad_utils.get_trustee(group, domain_sid).get("sid")
group_dict = {"sid": sid, "name": group}
members = []
for member in membership.get("Members", []):
if member:
if member.startswith("*"):
sid = member.strip("*")
name = self.ad_utils.get_trustee(sid).get("name")
members.append({"sid": sid, "name": name, "action": "ADD"})
else:
sid = self.ad_utils.get_trustee(member, domain_sid).get("sid")
members.append({"sid": sid, "name": member, "action": "ADD"})
if members:
output.append(
{
"Group": group_dict,
"Members": members,
"Action": "REPLACE",
"DeleteUsers": True,
"DeleteGroups": True,
}
)
# Extract "MemberOf" settings
for member_of in membership.get("Memberof", []):
if member_of:
members_of.setdefault(member_of, []).append(group)
# Unified output for "MemberOf" settings
if members_of:
for group, members in members_of.items():
if group.startswith("*"):
sid = group.strip("*")
name = self.ad_utils.get_trustee(sid).get("name")
parsed_group = {"sid": sid, "name": name}
else:
sid = self.ad_utils.get_trustee(group, domain_sid).get("sid")
parsed_group = {"sid": sid, "name": group}
parsed_members = []
for member in members:
if member.startswith("*"):
sid = member.strip("*")
name = self.ad_utils.get_trustee(sid).get("name")
parsed_members.append({"sid": sid, "name": name, "action": "ADD"})
else:
sid = self.ad_utils.get_trustee(member, domain_sid).get("sid")
parsed_members.append({"sid": sid, "name": member, "action": "ADD"})
if parsed_members and parsed_group:
output.append(
{
"Group": parsed_group,
"Members": parsed_members,
"Action": "UPDATE",
"DeleteUsers": False,
"DeleteGroups": False,
}
)
return output
```
## /gpohound/processors/pol_registry.py
```py path="/gpohound/processors/pol_registry.py"
class POLRegistryProcessor:
"""Process registry.pol"""
def __init__(self, ad_utils=None):
self.ad_utils = ad_utils
def process(self, settings):
"""
Format registy key for analysis
"""
output = []
for reg_key, data in settings.items():
# Set as DELETE options if key contains "**del"
# https://learn.microsoft.com/en-us/previous-versions/windows/desktop/policy/registry-policy-file-format
if "**del" in reg_key.lower():
action = "DELETE"
else:
action = "UPDATE"
entry = {
"Hive": data.get("Hive"),
"Key": reg_key,
"Type": data.get("Type"),
"Data": data.get("Data"),
"Action": action,
}
output.append(entry)
return output
```
## /gpohound/processors/privilege_rights.py
```py path="/gpohound/processors/privilege_rights.py"
class PrivilegeRightsProcessor:
"""Process Privilege Rights"""
def __init__(self, ad_utils):
self.ad_utils = ad_utils
def process(self, settings):
"""
Extract the "Privilege Rights" settings that will be applied to a computer
Resolves SID of trustees contained in privilege rights
"""
output = {}
for privilege, trustees in settings.items():
for trustee in trustees:
if trustee:
found_trustee = self.ad_utils.get_trustee(trustee)
output.setdefault(privilege, []).append(
{
"name": found_trustee.get("name"),
"sid": found_trustee.get("sid"),
}
)
return output
```
## /gpohound/processors/registry_values.py
```py path="/gpohound/processors/registry_values.py"
class RegistryValuesProcessor:
"""Process Registry Values"""
def __init__(self, ad_utils=None):
self.ad_utils = ad_utils
def process(self, settings):
"""
Format registy key for analysis
"""
output = []
for reg_key, data in settings.items():
entry = {
"Hive": data.get("Hive"),
"Key": reg_key.split("\\", 1)[1],
"Type": data.get("Type"),
"Data": data.get("Data"),
"Action": "UPDATE",
}
output.append(entry)
return output
```
## /gpohound/processors/xml_groups.py
```py path="/gpohound/processors/xml_groups.py"
class XMLGroupsProcessor:
def __init__(self, ad_utils):
self.ad_utils = ad_utils
self.action_type = {"D": "DELETE", "U": "UPDATE", "C": "CREATE", "R": "REPLACE"}
def process(self, settings, domain_sid):
"""
Output the settings applied to group and there impact on previous setting.
The groups settings are processed based on the order define in the preference settings,
Order 1 is processed first, order 2 is processed second...
"""
if settings.get("Group"):
output = []
groups = settings.get("Group")
if isinstance(groups, dict):
groups = [groups]
for group in groups:
properties = group.get("Properties")
if properties.get("groupSid"):
sid = properties.get("groupSid")
if not properties.get("groupName"):
# If groupSid try to find the name
name = self.ad_utils.get_trustee(sid).get("name")
else:
name = properties.get("groupName")
group_dict = {"sid": sid, "name": name}
elif properties.get("groupName"):
# If only groupName try to find the associated sid
name = properties.get("groupName")
if "\\" in name:
# If the name is in format NetbiosName\Username try to find name and sid
info = self.ad_utils.get_trustee(name)
name = info["name"]
sid = info["sid"]
else:
# Domain nme without the domain
sid = self.ad_utils.get_trustee(name, domain_sid).get("sid")
group_dict = {"sid": sid, "name": name}
else:
continue
# If the newName property is not empty then the group as a different name locally
if properties.get("newName"):
group_dict["newname"] = properties.get("newName")
if properties.get("userAction"):
group_dict["useraction"] = properties.get("userAction")
action_type = self.action_type.get(properties.get("action"), "UPDATE")
# DELETE group action
if action_type and action_type == "DELETE":
if properties.get("groupSid"):
output.append({"Group": group_dict, "Action": "DELETE"})
else:
# UPDATE setting is default if not set
if not action_type:
action_type = "UPDATE"
members_out = []
# Attributes that define if the users or groups need to be remove from the group
delete_users = True if properties.get("deleteAllUsers") == "1" else False
delete_groups = True if properties.get("deleteAllGroups") == "1" else False
if properties.get("Members"):
# Process the members
for members in properties.get("Members").values():
if isinstance(members, dict):
members = [members]
for member in members:
trustee = {"sid": None, "name": None}
if member.get("sid"):
trustee["sid"] = member.get("sid")
if member.get("name"):
trustee["name"] = member.get("name")
else:
trustee["name"] = self.ad_utils.get_trustee(trustee["sid"]).get("name")
else:
trustee["name"] = member.get("name")
trustee["sid"] = self.ad_utils.get_trustee(trustee["name"], domain_sid).get("sid")
if trustee.get("sid") or trustee.get("name"):
trustee["action"] = member.get("action")
members_out.append(trustee)
if trustee:
output.append(
{
"Group": group_dict,
"Members": members_out,
"Action": action_type,
"DeleteUsers": delete_users,
"DeleteGroups": delete_groups,
}
)
else:
output.append(
{
"Group": group_dict,
"Members": members_out,
"Action": action_type,
"DeleteUsers": delete_users,
"DeleteGroups": delete_groups,
}
)
return output
return None
```
## /gpohound/processors/xml_registry.py
```py path="/gpohound/processors/xml_registry.py"
from gpohound.utils.utils import find_keys_recursive
class XMLRegistryProcessor:
"""Process XML"""
def __init__(self, ad_utils=None):
self.ad_utils = ad_utils
def process(self, settings):
"""
Extract registry.xml settings to fit the format for registy key analysis
"""
action_type = {"D": "DELETE", "U": "UPDATE", "C": "CREATE", "R": "REPLACE"}
output = []
# Find Registry settings as it can be embeded in collections
found_registries = find_keys_recursive(settings, "Registry").get("Registry")
if found_registries:
for found_registry in found_registries:
registries = found_registry.get("value")
if isinstance(registries, dict):
registries = [registries]
for registry in registries:
# Extract properties and output registry key in the correct format
properties = registry.get("Properties")
action = action_type.get(properties.get("action"), "UPDATE")
if properties.get("type") == "REG_DWORD":
data = str(int(properties.get("value"), 16))
else:
data = properties.get("value")
entry = {
"Hive": properties.get("hive"),
"Key": properties.get("key") + "\\" + properties.get("name"),
"Type": properties.get("type"),
"Data": data,
"Action": action,
}
output.append(entry)
return output
```
## /gpohound/utils/ad.py
```py path="/gpohound/utils/ad.py"
from rich.prompt import Prompt
from rich.prompt import Confirm
from gpohound.utils.utils import load_yaml_config
class ActiveDirectoryUtils:
"""
Class to interact with AD objects
"""
def __init__(
self,
bloodhound_connector,
config="config",
config_file="well_known_groups.yaml",
):
self.config_trustee = load_yaml_config(config, config_file)
self.bloodhound = bloodhound_connector
self.netbios_names = {}
def node_to_dict(self, query_result, attributes=None):
"""
Convert a bloodhound node "n" to a dictionary
"""
node_dict = dict(query_result["n"])
if attributes:
extract = {}
for attribute in attributes:
extract.update({attribute: node_dict.get(attribute)})
node_dict = extract
return node_dict
def nodes_to_dict(self, query_results):
"""
Convert multiples BloodHound node to a dictionary list
"""
if len(query_results) == 1:
return [self.node_to_dict(query_results)]
else:
return [self.node_to_dict(result) for result in query_results]
def is_sid(self, value):
"""
Test if the value is a SID
"""
return value.startswith("*S-1-") or value.startswith("S-1-")
def sid_to_name(self, sid):
"""
Convert a SID to a name
"""
sid = sid.strip("*")
trustee = next(
(item for item in self.config_trustee if item["sid"].lower() == sid.lower()),
None,
)
if trustee:
# Builtin group
return trustee["displayname"]
elif self.bloodhound.connection:
# Domain group or user
node = self.bloodhound.find_by_objectid(sid)
if node and "displayname" in node["n"]:
return node["n"]["displayname"]
elif node and "samaccountname" in node["n"]:
return node["n"]["samaccountname"]
return None
def displayname_to_sid(self, name, domain_sid=None):
"""
Convert a display name to a SID
"""
# Try to find Builtin groups
trustee = next(
(item for item in self.config_trustee if item["displayname"].lower() == name.lower()),
None,
)
if trustee:
return trustee["sid"]
trustee = next(
(item for item in self.config_trustee if item["displayname"].lower() == ("BUILTIN\\" + name).lower()),
None,
)
if trustee:
return trustee["sid"]
if self.bloodhound.connection and domain_sid:
node = self.bloodhound.find_by_displayname(name)
if node and "objectid" in node["n"]:
return node["n"]["objectid"]
return None
def netbios_to_domain(self, netbios_name):
"""
Netbios name to a domain name
"""
netbios_name = netbios_name.upper()
if netbios_name in self.netbios_names:
return self.netbios_names.get(netbios_name)
else:
domains = self.get_domains()
if not domains:
return None
elif len(domains) == 1:
domain_name = domains[0]["name"].lower()
confirm_domain = Confirm.ask(
f"Is {netbios_name} the netbios name of {domain_name}",
default=False,
)
if confirm_domain:
self.netbios_names.update({netbios_name: domain_name})
return domain_name
else:
self.netbios_names.update({netbios_name: None})
else:
prompt_string = f"[bold][underline]Enter the domain associated with the netbios name [red]{netbios_name}[/red]:[/underline]\n 0. Not found[/bold]"
domains_dict = {"0": None}
for idx, domain in enumerate(domains, start=1):
domain_name = domain["name"].lower()
domains_dict.update({str(idx): domain_name})
prompt_string += f"\n[bold] {idx}. " + domain_name + "[/bold]"
domain_idx = Prompt.ask(
prompt_string + "\n",
choices=domains_dict.keys(),
default=None,
show_choices=False,
)
if domain_idx:
output_domain_name = domains_dict.get(domain_idx)
self.netbios_names.update({netbios_name: output_domain_name})
return output_domain_name
else:
self.netbios_names.update({netbios_name: None})
return None
def get_trustee(self, trustee, domain_sid=None):
"""
Get trustee based on name or sid
"""
trustee_output = {}
if trustee:
# Find based on sid
if self.is_sid(trustee):
sid = trustee.strip("*")
name = self.sid_to_name(sid)
# Builtin groups
elif self.displayname_to_sid(trustee):
name = trustee
sid = self.displayname_to_sid(trustee)
# Find based on netbios\username
elif "\\" in trustee and not trustee.upper().startswith("BUILTIN\\"):
netbios_name, samaccountname = trustee.split("\\", 1)
netbios_name = netbios_name.upper()
domain_name = self.netbios_to_domain(netbios_name)
if domain_name:
domain_sid = self.domain_to_sid(domain_name)
sid = self.displayname_to_sid(samaccountname, domain_sid)
else:
sid = None
name = trustee
# Find based on name and domain_sid
else:
name = trustee
sid = self.displayname_to_sid(name, domain_sid)
if sid and name and domain_sid:
domain = self.find_by_sid(domain_sid)
if domain:
domain_name = domain.get("name")
trustee_output["name"] = f"{name}@{domain_name}"
trustee_output["sid"] = sid.replace(f"{domain_name.upper()}-", "")
trustee_output["domain_sid"] = domain_sid
return trustee_output
else:
trustee_output["name"] = name
trustee_output["sid"] = sid
trustee_output["domain_sid"] = domain_sid
return trustee_output
return trustee_output
def find_by_sid(self, sid, attributes=None):
"""
Find an object based on it's SID
"""
sid = sid.strip("*")
if self.bloodhound.connection:
node = self.bloodhound.find_by_objectid(sid)
return self.node_to_dict(node, attributes)
return None
def find_container(self, target, attributes=None):
"""
Find container based on a machine/user or directly a container
"""
if self.bloodhound.connection:
node = self.bloodhound.find_container(target)
if node:
return self.node_to_dict(node, attributes)
return None
def find_trustee_container(self, target, attributes=None):
"""
Find container based on a machine/user or directly a container
"""
if self.bloodhound.connection:
node = self.bloodhound.find_trustee_container(target)
if node:
return self.node_to_dict(node, attributes)
return None
def find_by_gpo_guid(self, guid, domain_sid, attributes=None):
"""
Find a gpo based on a GUID and makes sure it is not empty
"""
if self.bloodhound.connection:
node = self.bloodhound.find_by_gpo_guid(guid, domain_sid)
if node and "name" in node["n"]:
output = self.node_to_dict(node, attributes)
if "name" in output:
output["name"] = output["name"].rsplit("@", 1)[0]
return output
return None
def get_domains(self):
"""
Find all the domains
"""
if self.bloodhound.connection:
results = self.bloodhound.find_domains()
if results:
return self.nodes_to_dict(results)
return None
def domain_to_sid(self, domain):
"""
Domain name to sid
"""
if self.bloodhound.connection:
result = self.bloodhound.find_by_domain_name(domain)
if result and "objectid" in result["n"]:
return result["n"]["objectid"]
def container_inheritance(self, container_id):
"""
Get GPO application order (inheritance)
"""
if self.bloodhound.connection:
gpo_inheritance = self.bloodhound.get_gpo_inheritance(container_id)
if gpo_inheritance:
return self.nodes_to_dict(gpo_inheritance)
return None
def get_containers(self, domain_sid):
"""
Get all the containers of a domain
"""
if self.bloodhound.connection:
results = self.bloodhound.get_containers(domain_sid)
if results:
return self.nodes_to_dict(results)
return None
def get_containers_affected_by_gpo(self, gpo_guid, domain_sid):
"""
Get containers (Domain, OU, Container) affected by a GPO
"""
if self.bloodhound.connection:
results = self.bloodhound.containers_affected_by_gpo(gpo_guid, domain_sid)
if results:
return self.nodes_to_dict(results)
return None
def resolve_gpo_name(self, domainpolicies):
"""
Resolves the GPO names
"""
for domain, gpos in domainpolicies.items():
domain_sid = self.domain_to_sid(domain)
if domain_sid:
guids = list(gpos.keys())
for guid in guids:
gpo = self.find_by_gpo_guid(guid, domain_sid)
if gpo:
# Move Name to the top of the dictionary
gpo_with_name = {"GPO Name": gpo.get("name")}
gpo_with_name.update(domainpolicies[domain][guid])
domainpolicies[domain][guid] = gpo_with_name
return domainpolicies
```
## /gpohound/utils/bloodhound.py
```py path="/gpohound/utils/bloodhound.py"
import logging
from neo4j import GraphDatabase
from neo4j.exceptions import ServiceUnavailable, AuthError
logging.getLogger("neo4j").setLevel(logging.INFO)
class BloodHoundConnector:
"""
Class to interact with BloodHound data
"""
def __init__(self, host=None, user=None, password=None, port=None):
self.uri = f"{host}:{port}"
self.user = user
self.password = password
self.driver = None
self.connection = bool(self.query("RETURN 1"))
if self.connection:
self.apoc = bool(self.query("RETURN apoc.version()"))
else:
self.apoc = None
def query(self, query_str, params=None):
"""
Execute query on the neo4j database
"""
if params is None:
params = {}
try:
self.driver = GraphDatabase.driver(f"bolt://{self.uri}", auth=(self.user, self.password))
with self.driver.session() as session:
result = session.run(query_str, params)
result_data = [record for record in result]
if result_data:
if len(result_data) == 1:
return result_data[0]
else:
return result_data
return None
except ServiceUnavailable as error:
logging.debug("Unable to connect to Neo4j instance : %s", error)
return None
except AuthError as error:
logging.debug("Could not authenticate to Neo4j database: %s", error)
return None
finally:
if self.driver:
self.driver.close()
def find_domains(self):
"""
Find all domains
"""
query = """
MATCH (n:Domain)
RETURN n
"""
return self.query(query)
def find_by_domain_name(self, domain):
"""
Find domain by by domain name
"""
params = {"domain": domain}
query = """
MATCH (n:Domain {domain:toUpper($domain)})
RETURN n LIMIT 1
"""
return self.query(query, params)
def find_by_gpo_guid(self, gpo_guid, domain_sid):
"""
Find a GPO with his GUID and domain SID
"""
params = {"gpo_guid": gpo_guid, "domain_sid": domain_sid}
query = """
MATCH (n:GPO)
WHERE toUpper(n.gpcpath) CONTAINS toUpper($gpo_guid) and toUpper(n.domainsid) = toUpper($domain_sid)
RETURN n LIMIT 1
"""
return self.query(query, params)
def find_by_displayname(self, name):
"""
Find an object by his name
"""
params = {"name": name}
query = """
MATCH (n)
WHERE toUpper(n.samaccountname) = toUpper($name) OR toUpper(n.displayname) = toUpper($name)
RETURN n LIMIT 1
"""
return self.query(query, params)
def find_by_objectid(self, objectid):
"""
Find an object by his objectid
"""
params = {"objectid": objectid}
query = """
MATCH (n)
WHERE toUpper(n.objectid) = toUpper($objectid)
RETURN n LIMIT 1
"""
return self.query(query, params)
def find_container(self, target):
"""
Find a container with a attribut of the container
"""
params = {"target": target}
query = """
MATCH (n)
WHERE (toUpper(n.distinguishedname) = toUpper($target) OR toUpper(n.objectid) = toUpper($target))
AND ANY(label IN labels(n) WHERE label IN ['Container', 'Domain', 'OU'])
RETURN n LIMIT 1
"""
return self.query(query, params)
def find_trustee_container(self, target):
"""
Find the container of a trustee
"""
params = {"target": target}
query = """
MATCH (n)-[r1:Contains]->(t)
WHERE (toUpper(t.distinguishedname) = toUpper($target) OR toUpper(t.objectid) = toUpper($target) OR toUpper(t.name) = toUpper($target))
AND ANY(label IN labels(t) WHERE label IN ['User', 'Computer'])
AND ANY(label IN labels(n) WHERE label IN ['Container', 'Domain', 'OU'])
RETURN n LIMIT 1
"""
return self.query(query, params)
# Disabled links fix in https://github.com/dirkjanm/BloodHound.py/pull/218
def get_gpo_inheritance(self, objectid):
"""
Get GPO application order for a container
"""
params = {"objectid": objectid}
query = """
MATCH (o {objectid: $objectid})
WITH o
// Collect direct GPLinks first
OPTIONAL MATCH (n:GPO)-[r1:GPLink]->(o)
WITH o, COLLECT({
node: n,
enforced: r1.enforced,
distance: 1,
id: ID(n),
firstGPLinkId: ID(r1) // Store the ID of the first GPLink relationship
}) AS directLinks
// Collect indirect GPLinks
OPTIONAL MATCH p2 = (n:GPO)-[r2:GPLink]-(c)-[r3:Contains*1..]->(o)
WHERE (
(NONE(x IN TAIL(TAIL(NODES(p2))) WHERE x.blocksinheritance = true AND 'OU' IN LABELS(x)))
OR r2.enforced = true
// TODO: Check this OR
OR ANY(label IN labels(o) WHERE label IN ['Container', 'Domain'])
)
WITH directLinks, COLLECT({
node: n,
enforced: ANY(r2 IN RELATIONSHIPS(p2) WHERE type(r2) = "GPLink" AND r2.enforced = true),
distance: LENGTH(p2),
id: ID(n),
firstGPLinkId: ID(r2)
}) AS indirectLinks
WITH [g IN directLinks + indirectLinks WHERE g.node IS NOT NULL] AS allGPOs
UNWIND allGPOs AS result
// Sorting logic:
// Enforced relationships first (by enforced DESC), then by distance DESC, then GPLink ID DESC
// Non-enforced relationships second, by distance ASC, then GPLink ID DESC
WITH result
ORDER BY
result.enforced DESC,
CASE WHEN result.enforced = true THEN result.distance END DESC, // Enforced: distance DESC
CASE WHEN result.enforced = false THEN result.distance END ASC, // Non-enforced: distance ASC
result.firstGPLinkId DESC // GPLink ID DESC
// Debug : RETURN result.node.name AS gpo_order, result.enforced AS enforced, result.firstGPLinkId AS first_gpLink_id, result.distance
RETURN result.node AS n
"""
return self.query(query, params)
def containers_affected_by_gpo(self, gpo_guid, domain_sid):
"""
Get not empty containers that are affected by a GPO
"""
params = {"gpo_guid": gpo_guid, "domain_sid": domain_sid}
query = """
MATCH (g)
WHERE toUpper(g.gpcpath) CONTAINS toUpper($gpo_guid) and toUpper(g.domainsid) = toUpper($domain_sid)
WITH g
// Collect direct GPLinks first
OPTIONAL MATCH (g:GPO)-[r1:GPLink]->(c)-[r2:Contains]->(t)
WHERE ANY(label IN labels(c) WHERE label IN ['Container','OU', 'Domain'])
AND ANY(label IN labels(t) WHERE label IN ['User','Computer'])
WITH g, COLLECT(DISTINCT c) as directContainer
// Collect indirect GPLinks
OPTIONAL MATCH p2 = (g:GPO)-[r3:GPLink]-()-[r4:Contains*1..]->(c)-[r5:Contains]->(t)
WHERE (
((NONE(x IN TAIL(TAIL(NODES(p2))) WHERE x.blocksinheritance = true AND 'OU' IN LABELS(x))) OR r3.enforced = true)
AND ANY(label IN labels(c) WHERE label IN ['Container','OU', 'Domain'])
AND ANY(label IN labels(t) WHERE label IN ['User','Computer'])
)
WITH directContainer, COLLECT(DISTINCT c) AS indirectContainer
WITH directContainer + indirectContainer AS AllContainers
UNWIND AllContainers AS n
RETURN n
"""
return self.query(query, params)
def get_containers(self, domain_sid):
"""
Get all containers of a domain
"""
params = {"domain_sid": domain_sid}
query = """
MATCH (n)
WHERE n.domainsid = $domain_sid
AND ANY(label IN labels(n) WHERE label IN ['Container','OU', 'Domain'])
RETURN DISTINCT n
"""
return self.query(query, params)
def get_not_empty_containers(self, domain_sid):
"""
Get all not empty containers
"""
params = {"domain_sid": domain_sid}
query = """
MATCH (n)-[r:Contains]->(l)
WHERE n.domainsid = $domain_sid
AND ANY(label IN labels(n) WHERE label IN ['Container','OU', 'Domain'])
AND ANY(label IN labels(l) WHERE label IN ['Computer','User'])
RETURN DISTINCT n
"""
return self.query(query, params)
def add_edges(self, domain_sid, container_id, trustee_sid, edge):
"""
Add relationship between a trustee and machines from a container
"""
params = {
"edge": edge,
"container_id": container_id,
"trustee_sid": trustee_sid,
"domain_sid": domain_sid,
}
query = """
MATCH (t)
WHERE toUpper(t.objectid) ENDS WITH toUpper($trustee_sid) AND toUpper(t.domainsid) = toUpper($domain_sid)
WITH t
MATCH (o {objectid: $container_id})-[r:Contains]->(c:Computer)
WITH t,c
CALL apoc.merge.relationship(t, $edge, {gpohound:true} ,{}, c) YIELD rel WITH t,c
RETURN t,c
"""
return self.query(query, params)
def add_extra_property(self, container_id, property_key, property_value):
"""
Add property to a machine in a container
"""
params = {
"container_id": container_id,
"property_key": property_key,
"property_value": property_value,
}
query = """
MATCH (o {objectid: $container_id})-[r:Contains]->(c:Computer)
WITH c
CALL apoc.create.setProperty(c, $property_key, $property_value) YIELD node as n
RETURN n
"""
return self.query(query, params)
```
The content has been capped at 50000 tokens, and files over NaN bytes have been omitted. The user could consider applying other filters to refine the result. The better and more specific the context, the better the LLM can follow instructions. If the context seems verbose, the user can refine the filter using uithub. Thank you for using https://uithub.com - Perfect LLM context for any GitHub repo.