Giter Site home page Giter Site logo

sharphound3's People

Contributors

cnotin avatar nikallass avatar rmaksimov avatar rvazarkar avatar sploutchy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sharphound3's Issues

Session Information Missing in Latest Version

Hi everyone

I hope this is the correct place to drop this question / issue. A colleague and me discovered some strange behavior when collection user sessions. In the end, it looks like the intentional behavior of SharpHound but I still decided to open this issue.

Infrastructure Setup

  • Deployed in Azure
  • AD Domain Joined
  • Clients: Windows 10, Version 1909, all updates installed
  • Server: Windows Server 2019, Version 1809, all updates installed
  • User: The user which executed SharpHound was logged in on the Client and is a regular low-privileged domain user (no local/domain admin privileges).

Technical Description

SharpHound was started from the client.

When using the latest version of SharpHound (from the BloodHound GitHub repository), no sessions on the WS1 server were found:

image

When using an oder version of SharpHound, the following sessions on the WS1 were found:
image

The same happened with other sessions on other machines.

To exclude timing issues from the tests, both the new and old version were run 5 times to collection sessions. We could reproduce the behavior. The old version always found more sessions than the latest version. The following screenshot compares the collected sessions from the new and old version:

image

An analysis using Wireshark showed that the newer version performed less requests from the client to the server. The following traffic was only seen in the old version:

image

This session information is collected using the LoggedOn collection method:

image

The reason is commit ee437a5 by @rvazarkar which removed the call to the GetLoggedOnUsersRegistry function from the LoggedOnTasks. The commit message from @rvazarkar also mentions the change with "Remove registry logged on".

The LoggedOn collection method does add the "session" edge in BloodHound. The offical documentation only recommends to use the Sessions collection method and not both (https://bloodhound.readthedocs.io/en/latest/data-collection/sharphound.html#the-session-loop-collection-method):

image

Question

  • Apparently, the GetLoggedOnUsersRegistry finds sessions which are otherwise not found. Is there a reason this function call was removed?
  • Is there a reason why not performing the LoggedOn collection method when collection sessions in a loop (--loop) is recommended in the documentation?

Thansk for your answer,

Mänu

Edit: If you stumbled upon this issue and want to collect session information using LoggedOn via Remote Registry, you can build your own one or try this version here: https://github.com/CompassSecurity/SharpHound3/releases/tag/3-registry

LAPS collection not working

Hi,
the laps edge collection does not work in an environment I'm in.
We started the collection from a PowerShell script as follows
Start-Process $SharphoundBin -ArgumentList "-c all --outputdirectory "$BloodhoundOutDir" --loop true --loopduration 02:00:00 --loopinterval 00:10:00" -RedirectStandardOutput sharphound_log.txt

2020-08-06
laps1
laps2
laps3
laps4

EncryptZip Password

Hi,
I used the encryptZip flag for a long loop over the sessions but can't get my hand on this randomly generated password. Was it supposed to be outputted by the powershell script, because I did not see anything.

Can you give me some information regarding this flag?

Thanks in advance for your help,
Baptiste

Exception Thrown "An item with the same key has already been added"

Aloha folks

I'm attempting to collect data with the latest version of Sharphound (both the .exe and .ps1) and I'm receiving the exception noted in the title: System.ArgumentException: An item with the same key has already been added.

Environment is a Windows Server 2016 forest with 3 single-domain trees:
Forest Root: foo.net
Tree 2: foobar.net
Tree 3: foobarfoo.net

Ingestor (both .exe and .ps1) was executed from a workstation and a server, both fully whitelisted by AV/EDR, with the following command line:
SharpHound.exe --collectionmethod all,gpolocalgroup --collectallproperties --prettyjson --domain foobar.net --throttle 100 --invalidatecache

I tried a number of other options, including running --collectionmethod dconly or removing --collectionmethod entirely, removing --collectallproperties, --throttle, without --invalidatecache, verbose, and against all 3 of the domains in the forest, with and without the admin token, in powershell or at the command prompt, with close to the same results. The ingestor processes for a bit, generates a few JSON files and populates them with a number of entries, then dies with the exception noted without completing the JSON files or generating the .zip. Verbose did not provide anything that helped me identify the issue.

Stack trace as received at the command prompt is attached:
bloodhound_ERROR.txt

Thanks, and aloha!

Joel

Unhandled exception crashes using Sharphound.exe

Hello!

While executing Sharphound.exe =, occasionally I get the following crash and the collection stops:

Application: SharpHound.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.DirectoryServices.Protocols.DirectoryOperationException

Server stack trace: 
   at System.DirectoryServices.Protocols.LdapConnection.ConstructResponse(Int32 messageId, LdapOperation operation, ResultAll resultType, TimeSpan requestTimeOut, Boolean exceptionOnTimeOut)
   at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
   at System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(IMessage msg, IMessageSink replySink)
   at System.DirectoryServices.Protocols.LdapConnection.EndSendRequest(System.IAsyncResult)
   at SharpHound3.DirectorySearch+<>c__DisplayClass11_0.<RangedRetrievalAsync>b__0(System.IAsyncResult)
   at System.Threading.Tasks.TaskFactory`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].FromAsyncCoreLogic(System.IAsyncResult, System.Func`2<System.IAsyncResult,System.__Canon>, System.Action`1<System.IAsyncResult>, System.Threading.Tasks.Task`1<System.__Canon>, Boolean)
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
   at SharpHound3.DirectorySearch+<RangedRetrievalAsync>d__11.MoveNext()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
   at SharpHound3.Tasks.GroupEnumerationTasks+<GetGroupMembership>d__3.MoveNext()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
   at SharpHound3.Tasks.GroupEnumerationTasks+<ProcessGroupMembership>d__1.MoveNext()

Exception Info: System.AggregateException

Exception Info: System.AggregateException

Exception Info: System.AggregateException

Exception Info: System.AggregateException

Exception Info: System.AggregateException

Exception Info: System.AggregateException

Exception Info: System.AggregateException

Exception Info: System.AggregateException

Exception Info: System.AggregateException
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(System.Threading.Tasks.Task)
   at SharpHound3.SharpHound+<Main>d__0.MoveNext()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
   at SharpHound3.SharpHound.<Main>(System.String[])

I thought of reporting it considering it is an unhandled exception case.

GPOLocalGroup not returning data without including All

Good morning,

While working through Rastamouse's CRTO course, it was identified that running GPOLocalGroup alone as a Sharphound query was not returning full GPOLocalGroup data. Him and I worked through the issue for some time before realizing that GPOLocalGroup wasn't querying the appropriate data from the execution.

The following was ran in domain user context - sharphound.exe -c gpolocalgroup
image

And the contents of the json file below -

{"groups":[{"Properties":{"name":"ENTERPRISE DOMAIN [email protected]","domain":"CYBERBOTIC.IO"},"Members":[{"MemberId":"S-1-5-21-3865823697-1816233505-1834004910-1000","MemberType":"Computer"}],"ObjectIdentifier":"CYBERBOTIC.IO-S-1-5-9","Aces":[]},{"Properties":{"name":"[email protected]","domain":"CYBERBOTIC.IO"},"Members":[{"MemberId":"S-1-5-21-3865823697-1816233505-1834004910-515","MemberType":"Group"},{"MemberId":"S-1-5-21-3865823697-1816233505-1834004910-513","MemberType":"Group"}],"ObjectIdentifier":"CYBERBOTIC.IO-S-1-1-0","Aces":[]},{"Properties":{"name":"AUTHENTICATED [email protected]","domain":"CYBERBOTIC.IO"},"Members":[{"MemberId":"S-1-5-21-3865823697-1816233505-1834004910-515","MemberType":"Group"},{"MemberId":"S-1-5-21-3865823697-1816233505-1834004910-513","MemberType":"Group"}],"ObjectIdentifier":"CYBERBOTIC.IO-S-1-5-11","Aces":[]}],"meta":{"count":3,"type":"groups","version":3}}

Running with the all flag appended ran from a domain context, the results were appropriate and as follows -

sharphound.exe -c all gpolocalgroup

Resolved Collection Methods: Group, Sessions, LoggedOn, Trusts, ACL, ObjectProps, LocalGroups, SPNTargets, Container, GPOLocalGroup [+] Creating Schema map for domain CYBERBOTIC.IO using path CN=Schema,CN=Configuration,DC=cyberbotic,DC=io [+] Cache File not Found: 0 Objects in cache [+] Pre-populating Domain Controller SIDS Status: 0 objects finished (+0) -- Using 34 MB RAM Status: 197 objects finished (+197 6.793103)/s -- Using 46 MB RAM Status: 198 objects finished (+1 6)/s -- Using 50 MB RAM Enumeration finished in 00:00:33.3755922 Compressing data to .\20210331180317_BloodHound.zip You can upload this file directly to the UI SharpHound Enumeration Completed at 18:04 on 31/03/2021! Happy Graphing!

This execution included the appropriate GPOLocalGroup data as expected, but required the All flag to do so.

In the end, I'm not sure if it's intended that the GPOLocalGroup flag require the All flag as well. I appreciate you looking in to this.

Thank you!

Collection hangs on certain hosts due to GetLoggedOnUsersRegistry()

My SharpHound collection hangs on the final steps in certain cases (it lasted many hours). I was able to finish it by killing some SMB connections that seemed to be stuck. It immediately finished its scan.
Here is the kind of stuff I saw in loop in Wireshark:
image

It seems that the host responds, but always the same in loop and SharpHound loops forever accordingly...
I was wondering to see what would use "winreg" and I guess it's due to GetLoggedOnUsersRegistry() in the Logged On task.

My suggestion would be to implement a timeout in the form of a watchdog that would automatically kill these task after a certain amount of time without progress.

--LDAPFilter/--searchbase usage

Copying and pasting what I wrote in the BH slack.

Hey, so this is a bit of a continuation of when you were helping me with --LDAPFilter and --ComputerFile the other day. Sorry in advance for the essay.

So, using --ComputerFile ended up not being a viable option for us. When we do hostnames, it just ends up not working for whatever reason. It is probably a DNS issue on our end though. We have similar issues on our real customer network. With WFH being the norm currently, DNS has been on the fritz with all the VPNing and we do not have a good way of getting IPs of our targets from a Red Team perspective.

Either way, it is not a good long-term solution since eventually it won’t be scalable considering the size of our network.

So, I went back to --LDAPFilter since I needed a way to filter my targets by OU still. I attached a picture of what’s in the docs which is an example of pretty much what I wanted to.

From the Docs:
ldapfilter_doc

However, I spent a long time trying to get it to work before I realize what was going on.

In SharpHound v2, you guys had the option to filter by OU and then removed it for the more generic --LDAPFilter in v3. However, the way you guys filter is with --LDAPFilter basically like doing dsquery * -filter [FILTER].

When you use --LDAPFilter, it just attaches it to the end of the filter. However, you can’t filter by OUs like that. You have to do something like the following.

run dsquery * "OU=New York,DC=Contoso,DC=local" -filter (objectclass=computer) -attr dnshostname distinguishedname adspath -limit 0 -l

I attached two more pictures so you can see it in action. The first picture is basically replicating the example in my lab where I want to get everything in "OU=WorkStations,DC=gaia,DC=local" which has 2 objects. It finds 0 objects.

1

However, a filter like the following (dnshostname=GAIA) should work considering how filtering is done and in this case should return all computer objects in my domain (3 objects), which it does (ignore the filter output, we added that to help debug).

2

So, I don’t like to bring up issues without seeing if solutions already exist and they do! You guys have a --searchbase as an option which can limit it to an OU. However, this is another case where it’s visible in sharpHound if you view the help options, but it’s not in your new wiki nor in github which I checked just in case.

In other words, if we wanted to filter by the OU OU=WorkStations,DC=gaia,DC=local in our lab, you have the following options (the other options in the attached picture don’t affect the point I’m making). Side note, it did not like parenthesis with --searchbase. Assuming it is just how the code is written and adds to the filter. Didn’t check the source code for that though and it’s not a concern either way.

sharpHound --searchbase "OU=WorkStations,DC=gaia,DC=local"

3

This will grab everything in that OU including the OU object. In my lab environment, that means the 2 computers and the OU itself. Aka, 3 objects which can be seen in 3.png.
The other option is the following:

sharpHound --searchbase "OU=WorkStations,DC=gaia,DC=local" --LDAPFilter "objectclass=computer"

4

Basically, the same as the previous, but the --LDAPFilter just limits it to computers. Aka, this time you still scan the 2 computers but skip enumerating the OU object itself. Don’t see why you wouldn’t grab the OU object as well, but just throwing this out there. Either way, picture 4.png is a visual example.

Anyway, I just wanted to bring it to your attention for the sake of the docs and maybe it’ll help anyone else who might be in a similar situation.

Contact AD objects belong to a group included in results

Contact AD objects are included in the data, even though they are not security principals and cannot be used in any attack path. Contacts can be members of groups, and I think group ingestion is where the problem occurs during ingestion. This is what the contact object looks like in the UI (the question mark):

image

[Suggestion] Remove "ComputerId" attribute from "Sessions" in computers.csv as it is redundant

A computer object in computers.json looks like this:

{
  "Properties": {
[...]
    "objectid": "S-1-5-21-xxxx-999",
[...]
  "Sessions": [
    {
      "UserId": "S-1-5-21-xxxxxx-123",
      "ComputerId": "S-1-5-21-xxxx-999"
    },
    {
      "UserId": "S-1-5-21-xxxxxx-456",
      "ComputerId": "S-1-5-21-xxxx-999"
    },
[...]

The ComputerId attribute is repeated for each session and it is redundant with the objectid of the computer which we already know (except if I missed a specific case?). I suggest removing it then to have a smaller file :)

Error CS1061 'NameServer' does not contain a definition for 'Endpoint'....

Hello, im getting this error trying to compile the latest version of sharphound:

Error CS1061 'NameServer' does not contain a definition for 'Endpoint' and no accessible extension method 'Endpoint' accepting a first argument of type 'NameServer' could be found (are you missing a using directive or an assembly reference?) SharpHound3 C:\temp\sharphound3\SharpHound3\Helpers.cs 224 Active

any suggestion ? using the following version of Vstudio 2019

Microsoft Visual Studio Community 2019 (2)
Version 16.5.4
VisualStudio.16.Release/16.5.4+30011.22
Microsoft .NET Framework
Version 4.8.03752

Installed Version: Community

Visual C++ 2019 00435-60000-00000-AA438
Microsoft Visual C++ 2019

ASP.NET and Web Tools 2019 16.5.236.49856
ASP.NET and Web Tools 2019

Azure App Service Tools v3.0.0 16.5.236.49856
Azure App Service Tools v3.0.0

C# Tools 3.5.0-beta4-20153-05+20b9af913f1b8ce0a62f72bea9e75e4aa3cf6b0e
C# components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.

Common Azure Tools 1.10
Provides common services for use by Azure Mobile Services and Microsoft Azure Tools.

Cookiecutter 16.5.20041.1
Provides tools for finding, instantiating and customizing templates in cookiecutter format.

IntelliCode Extension 1.0
IntelliCode Visual Studio Extension Detailed Info

Microsoft Azure Tools 2.9
Microsoft Azure Tools for Microsoft Visual Studio 2019 - v2.9.30207.1

Microsoft JVM Debugger 1.0
Provides support for connecting the Visual Studio debugger to JDWP compatible Java Virtual Machines

Microsoft MI-Based Debugger 1.0
Provides support for connecting Visual Studio to MI compatible debuggers

Microsoft Visual C++ Wizards 1.0
Microsoft Visual C++ Wizards

Microsoft Visual Studio VC Package 1.0
Microsoft Visual Studio VC Package

NuGet Package Manager 5.5.0
NuGet Package Manager in Visual Studio. For more information about NuGet, visit https://docs.nuget.org/

ProjectServicesPackage Extension 1.0
ProjectServicesPackage Visual Studio Extension Detailed Info

Python 16.5.20041.1
Provides IntelliSense, projects, templates, debugging, interactive windows, and other support for Python developers.

Python - Conda support 16.5.20041.1
Conda support for Python projects.

Python - Django support 16.5.20041.1
Provides templates and integration for the Django web framework.

Python - IronPython support 16.5.20041.1
Provides templates and integration for IronPython-based projects.

Python - Profiling support 16.5.20041.1
Profiling support for Python projects.

Test Adapter for Boost.Test 1.0
Enables Visual Studio's testing tools with unit tests written for Boost.Test. The use terms and Third Party Notices are available in the extension installation directory.

Test Adapter for Google Test 1.0
Enables Visual Studio's testing tools with unit tests written for Google Test. The use terms and Third Party Notices are available in the extension installation directory.

TypeScript Tools 16.0.20225.2001
TypeScript Tools for Microsoft Visual Studio

Visual Basic Tools 3.5.0-beta4-20153-05+20b9af913f1b8ce0a62f72bea9e75e4aa3cf6b0e
Visual Basic components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.

Visual F# Tools 10.8.0.0 for F# 4.7 16.5.0-beta.20181.6+85af456066acd4e76d2bc7821b44a325e46f2fca
Microsoft Visual F# Tools 10.8.0.0 for F# 4.7

Visual Studio Code Debug Adapter Host Package 1.0
Interop layer for hosting Visual Studio Code debug adapters in Visual Studio

Visual Studio Tools for CMake 1.0
Visual Studio Tools for CMake

thanks

Large domains

What to do with large domains? I have JSON with users 2+GB and SharpHound crashed with OOM.
Maybe there is some nice way to filter out useless things in advance?

[question] Authentication artifacts

Hi there,

Just wondering if there are any artifacts on the system remaining after the RPC calls on the remote systems. Since SharpHound is going to use an authenticated session on each system reachable within the domain I would like to know if it leaves critical information on the system after the authentication.

If I understood the Windows authentication process correctly there is a chance, that Wdigest.dll (or other cacheable authentication routines) is used during the process. If the remote system has not turned off credential caching or simply does not support it yet because of an outdated OS the used credentials would be available for maybe a real attacker to gather/steal later on.

Do you have any insights on this topic? I searched through some Microsoft docs and other sources but was not able to answer this question.

Thank you for your awesome work!

False positive CanRDP relationship from GPOLocalGroup option (Cause: Group Policy "Security Filtering"?)

Firstly, thank you for such a great tool.

I recently noticed that BloodHound was telling me that the "Domain Users" group could RDP to some servers. This was incorrect. The Remote Desktop Users group was in fact empty. The options I used were:

sharphound.exe --domaincontroller mydc -c DCOnly

The information had come from a Group Policy linked to a server OU. Security Filtering had been used in the Group Policy Management tool (click the Group Policy link | Scope | Security Filtering).

Often Security Filtering is set to Authenticated Users, in which case I believe the policy applies to all computers in the OU. In my case Security Filtering was set to some specific computer accounts, meaning the policy only applied to those computers. My best guess is that SharpHound is not taking account of Security Filtering and is applying policy information to all computers in the OU.

I ran SharpHound with sufficient privileges to be able to read all the group policy files.

The policy settings that indicated Domain Users could RDP to hosts was the usual Computer Configuration > Policies > Windows Settings > Security Settings > Restricted Groups. This information was in turn stored in a GptTmpl.inf file on sysvol in the usual place. NTFS read permissions were granted on GptTmpl.inf to the computer accounts listed in Security Filtering. NTFS read permission had not been granted to other servers in the OU for this file. (I assume everything in the paragraph is normal and expected. I just wanted to be clear).

To recreate this problem try:

  1. Create a Server OU containing 2 servers: SERVER1 and SERVER2
  2. Link a policy into the Server OU that grants Domain Users membership of Remote Desktop Users
  3. Configure Security Filtering on the policy so that it applies only to SERVER1$
  4. Check local Remote Desktop Users group members are as expected (empty for Server2; Domain Users for Server1)
  5. Run SharpHound and BloodHound. Check that BloodHound reports that Domain Users can RDP to both Server1 and Server2. You may have to run BloodHound with high privileges to be able to read the GptTmpl.inf file from sysvol (e.g. Domain Admin privs).

Data about local group memberships other than Remote Desktop Users are probably affected too.

Potential memory leak in SharpHound/ResolutionHelpers

I think there is a problem with this coding pattern :

var netWkstaTask = Task.Run(() => NetWkstaGetInfo(hostname, 100, out wkstaData));
if (await Task.WhenAny(Task.Delay(5000), netWkstaTask) != netWkstaTask)
                return (false, new WorkstationInfo100());

If I understand what it is doing, it waits 5 secords or when the native API completes, whichever comes first. If the timeout came first, it exits early from the function. The question is what happened to the task making the native API call? and in particular the out param wkstaData. It would seem the timeout case always leaks the memory because nothing calls NetApiBufferFree on it. I am not sure there is a safe way to call these kind of APIs where the caller is expected to do the memory management.

        private static async Task<(bool success, WorkstationInfo100 info)> CallNetWkstaGetInfo(string hostname)
        {
            if (!Helpers.CheckPort(hostname, 445))
                return (false, new WorkstationInfo100());

            var wkstaData = IntPtr.Zero;
            var netWkstaTask = Task.Run(() => NetWkstaGetInfo(hostname, 100, out wkstaData));
            if (await Task.WhenAny(Task.Delay(5000), netWkstaTask) != netWkstaTask)
                return (false, new WorkstationInfo100());
! Does this leak wkstaData?

            if (netWkstaTask.Result != 0)
                return (false, new WorkstationInfo100());

            try
            {
                var wkstaInfo = Marshal.PtrToStructure<WorkstationInfo100>(wkstaData);
                return (true, wkstaInfo);
            }
            finally
            {
                if (wkstaData != IntPtr.Zero)
                    NetApiBufferFree(wkstaData);
            }
        }

return (false, new WorkstationInfo100());

Issue 2

Here is another case. If the timeout happens, it returns early. The finally block runs and it calls NetApiBufferFree(ptrInfo) but is there any guarantee that the NetSessionEnum task has completed when this finally block runs?

        private static async Task<List<Session>> GetNetSessions(Computer computer)
        {
            var resumeHandle = IntPtr.Zero;
            var sessionInfoType = typeof(SESSION_INFO_10);

            var entriesRead = 0;
            var ptrInfo = IntPtr.Zero;

            var sessionList = new List<Session>();

            try
            {
                var task = Task.Run(() => NetSessionEnum(computer.APIName, null, null, 10,
                    out ptrInfo, -1, out entriesRead, out _, ref resumeHandle));

                //10 second timeout
                if (await Task.WhenAny(task, Task.Delay(10000)) != task)
                {
                    if (Options.Instance.DumpComputerStatus)
                        OutputTasks.AddComputerStatus(new ComputerStatus
                        {
                            ComputerName = computer.DisplayName,
                            Status = "Timeout",
                            Task = "NetSessionEnum"
                        });
                    return sessionList;
! Early return triggers finally block
                }
...

                return sessionList;
            }
            finally
            {
                if (ptrInfo != IntPtr.Zero)
                    NetApiBufferFree(ptrInfo);
! Is it ensured that the NetSessionEnum task completes before this check? 
! Otherwise the task could complete later and nothing will free the memory.
            }
        }

if (await Task.WhenAny(task, Task.Delay(10000)) != task)

I am not an expert in these async tasks constructs when calling unmanaged code but I am not sure how this is safe.

NullReferenceException at SharpHound3.Tasks.NetSessionTasks.<GetNetSessions>

After running Sharphound in the same environment for many months, something has changed. We now get this when running a collection against our largest domain:

v4.0.2 and 4.0.3 binaries both exhibit the issue. Verbose logging hasn't yielded any clues.

SharpHound.exe --outputdirectory \Bloodhound\JSON --nozip --CollectionMethod All
----------------------------------------------
Initializing SharpHound at 17:01 on 2021-10-06
----------------------------------------------

Resolved Collection Methods: Group, Sessions, LoggedOn, Trusts, ACL, ObjectProps, LocalGroups, SPNTargets, Container
 . .. . 

Status: 11092 objects finished (+252 36.97333)/s -- Using 176 MB RAM
Status: 11101 objects finished (+9 33.63939)/s -- Using 175 MB RAM
Status: 11101 objects finished (+0 30.83611)/s -- Using 175 MB RAM
Status: 11101 objects finished (+0 28.4641)/s -- Using 175 MB RAM
Status: 11101 objects finished (+0 26.43095)/s -- Using 175 MB RAM
Status: 11101 objects finished (+0 24.66889)/s -- Using 175 MB RAM

Unhandled Exception: System.AggregateException: One or more errors occurred. ---> System.AggregateException: One or more errors occurred. ---> System.AggregateException: One or more errors occurred. ---> System.NullReferenceException: Object reference not set to an instance of an object.
   at SharpHound3.Tasks.NetSessionTasks.<GetNetSessions>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at SharpHound3.Tasks.NetSessionTasks.<ProcessNetSessions>d__0.MoveNext()
   --- End of inner exception stack trace ---

SharpHound crashed with OutOfMemoryException

Currently using Bloodhound to scan the AD environment at work and it continues to crash with an error of "OutOfMemoryException" at around the ~8:30hr mark. The host has 128gb ram which I don't understand why the error is occurring. I have attempted to do throttling to see if that would help and not really sure what else to do. any guidance would help. Executing Sharphound with the all flag: SharpHound.exe -c all

image

Build error

Targeting .NET Framework 4.5 as said in the README.

Error Output:

Build started...
1>------ Build started: Project: SharpHound3, Configuration: Debug Any CPU ------
1>C:\Users\B*\tools\SharpHound3\SharpHound3\ResolutionHelpers.cs(203,40,203,78): error CS0308: The non-generic method 'Marshal.PtrToStructure(IntPtr, object)' cannot be used with type arguments
1>C:\Users\B*\tools\SharpHound3\SharpHound3\ResolutionHelpers.cs(235,40,235,78): error CS0308: The non-generic method 'Marshal.PtrToStructure(IntPtr, object)' cannot be used with type arguments
1>C:\Users\B*\tools\SharpHound3\SharpHound3\DirectorySearch.cs(173,38,173,39): warning CS0168: The variable 'e' is declared but never used
1>C:\Users\B*\tools\SharpHound3\SharpHound3\ResolutionHelpers.cs(549,41,549,75): error CS0308: The non-generic method 'Marshal.PtrToStructure(IntPtr, object)' cannot be used with type arguments
1>C:\Users\B*\tools\SharpHound3\SharpHound3\ResolutionHelpers.cs(654,27,654,36): warning CS0649: Field 'ResolutionHelpers.WorkstationInfo100.lan_group' is never assigned to, and will always have its default value null
1>C:\Users\B*\tools\SharpHound3\SharpHound3\ResolutionHelpers.cs(652,27,652,40): warning CS0649: Field 'ResolutionHelpers.WorkstationInfo100.computer_name' is never assigned to, and will always have its default value null
1>C:\Users\B*\tools\SharpHound3\SharpHound3\ResolutionHelpers.cs(656,24,656,33): warning CS0649: Field 'ResolutionHelpers.WorkstationInfo100.ver_minor' is never assigned to, and will always have its default value 0
1>C:\Users\B*\tools\SharpHound3\SharpHound3\ResolutionHelpers.cs(650,24,650,35): warning CS0649: Field 'ResolutionHelpers.WorkstationInfo100.platform_id' is never assigned to, and will always have its default value 0
1>C:\Users\B*\tools\SharpHound3\SharpHound3\ResolutionHelpers.cs(655,24,655,33): warning CS0649: Field 'ResolutionHelpers.WorkstationInfo100.ver_major' is never assigned to, and will always have its default value 0
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Potential memory leak due to not implementing IDisposable correctly in LocalGroupTasks

I am not an expert on this but from my reading, if you need to free unmanaged resources, you can implement IDisposable. LocalGroupTasks.cs has a helper class that tries to do this, but it looks to have two bugs.

Bug 1: Failure to inherit from IDisposable.

OBJECT_ATTRIBUTES implements Dispose() but does not inherit from IDisposable. Without this, Dispose may never be called.

Note the definition here: (https://www.pinvoke.net/default.aspx/Structures/OBJECT_ATTRIBUTES.html)

-        internal struct OBJECT_ATTRIBUTES
+       internal struct OBJECT_ATTRIBUTES : IDisposable
        {
            public int Length;
            public IntPtr RootDirectory;
            public uint Attributes;
            public IntPtr SecurityDescriptor;
            public IntPtr QualityOfService;
            private IntPtr _objectName;
            public UNICODE_STRING ObjectName;

            public void Dispose()
            {
                if (_objectName == IntPtr.Zero)
                    return;

                Marshal.DestroyStructure(_objectName, typeof(UNICODE_STRING));
                Marshal.FreeHGlobal(_objectName);
                _objectName = IntPtr.Zero;
            }
        }

internal struct OBJECT_ATTRIBUTES

Bug 2: Need to call Dispose() explicitly

The documentation on implementing Dispose says that you should call it explicitly or wrap the object in a using block--as the GC is not guaranteed to call it. The easiest thing here is to call Dispose in the finally block.

            finally
            {
                //Free memory from handles acquired during the process
                if (serverHandle != IntPtr.Zero)
                    SamCloseHandle(serverHandle);
                if (domainHandle != IntPtr.Zero)
                    SamCloseHandle(domainHandle);
                if (aliasHandle != IntPtr.Zero)
                    SamCloseHandle(aliasHandle);
+                if (objectAttributes != null)
+                    objectAttributes.Dispose();

                if (members != IntPtr.Zero)
                    SamFreeMemory(members);
            }

SamCloseHandle(aliasHandle);

[Feature request] Collect "whenCreated" attribute

We have a workflow where we lookup users that have never logged on, but the account is still active. Something like this:
MATCH (n:User) WHERE n.lastlogontimestamp=-1.0 AND n.enabled=TRUE RETURN n

It would be nice to have the ability to view the "whenCreated" attribute of the user. Our logic is, if they have never logged in and their account is old, we should look into disabling/removing that account.

Even if this attribute wasn't available in BloodHound's UI, if it was in the collected JSON, that would be helpful, as we could use Neo4j directly.

https://docs.microsoft.com/en-us/windows/win32/adschema/a-whencreated

Thanks!

SessionLoop not working

Hi,

I'm using the latest version of both bloodhound and Sharphound and I'm able to import the regular data but I can't seem to import session Loop data. Here is the error message:

image

Anything I can do?

[Feature Request] Display status information while collecting data

Hi,
it would be great if Sharphound would show a status bar or other progression information while collecting data.
Especially in large environments it can take some time and you don't know if something went wrong and Sharphound just hangs or it is still collecting data.

Following our discussion in Slack something along the lines of ldapsearch can be used:

$ ./ldapsearch --port 1389 --bindDN "cn=Directory Manager" --bindPassword password --baseDN ou=people,dc=example,dc=com --searchScope base "(objectclass=*)"
numsubordinates

Regards Alex

Version 2 data not compatible with bloodhound 3

I first run this command in CMD: C:> SharpHound.exe --CollectionMethod Session --Loop

Then I upload the collected data into the Bloodhound GUI in Linux.

An error message occurred: (version 2 data not compatible with bloodhound 3),
The imported files are not usable and the query don't work

I am using the following versions:
Using sharphound 3.0
Latest neo4j 3.5.3
Latest bloodhound GUI 3.0.4

How to solve this issue?

Documentation

Hi, If possible write documentation about how compile the ingestor with Visual Code. What reqeuirements are needed to compile stand alone executable ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.