-
Notifications
You must be signed in to change notification settings - Fork 254
Expand file tree
/
Copy pathSharphound.cs
More file actions
285 lines (242 loc) · 13.2 KB
/
Sharphound.cs
File metadata and controls
285 lines (242 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
// ---------------------------------------------------- //
// ______ __ __ __ //
// / __/ / ___ ________ / // /_ __ _____ ___/ / //
// _\ \/ _ \/ _ `/ __/ _ \/ _ / _ \/ // / _ \/ _ / //
// /___/_//_/\_,_/_/ / .__/_//_/\___/\_,_/_//_/\_,_/ //
// /_/ //
// app type : console //
// dotnet ver. : 462 //
// client ver : 3? //
// license : open....? //
//------------------------------------------------------//
// creational_pattern : Inherit from System.CommandLine //
// structural_pattern : Chain Of Responsibility //
// behavioral_pattern : inherit from SharpHound3 //
// ---------------------------------------------------- //
using System;
using System.DirectoryServices.Protocols;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using CommandLine;
using Microsoft.Extensions.Logging;
using Microsoft.Win32;
using Sharphound.Client;
using SharpHoundCommonLib;
using SharpHoundCommonLib.Enums;
using SharpHoundCommonLib.Models;
using SharpHoundCommonLib.Services;
using SharpHoundCommonLib.Static;
namespace Sharphound
{
#region Reference Implementations
#endregion
#region Console Entrypoint
public class Program {
private static MetricsFlushTimer _flushTimer;
public static async Task Main(string[] args) {
var logger = new BasicLogger((int)LogLevel.Information);
logger.LogInformation("This version of SharpHound is compatible with the 5.0.0 Release of BloodHound");
try {
logger.LogInformation("SharpHound Version: {Version}", Assembly.GetExecutingAssembly().GetName().Version);
logger.LogInformation("SharpHound Common Version: {Version}", Assembly.GetAssembly(typeof(CommonLib)).GetName().Version);
// Checks the release version available on the machine.
var releaseVersion = (int) Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full", "Release", 0);
if (releaseVersion == 0) releaseVersion = (int) Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full", "Release", 0);
// The value 461808 corresponds to .Net 4.7.2
if (releaseVersion < 461808)
{
logger.LogError("The .Net Runtime is not compatible with SharpHound. Please update to .Net 4.7.2.");
return;
}
var parser = new Parser(with => {
with.CaseInsensitiveEnumValues = true;
with.CaseSensitive = false;
with.HelpWriter = Console.Error;
});
var options = parser.ParseArguments<Options>(args);
await options.WithParsedAsync(async options =>
{
if (!options.ResolveCollectionMethods(logger, out var resolved, out var dconly)) return;
logger = new BasicLogger(options.Verbosity);
var flags = new Flags
{
Loop = options.Loop,
DumpComputerStatus = options.TrackComputerCalls,
NoRegistryLoggedOn = options.SkipRegistryLoggedOn,
ExcludeDomainControllers = options.ExcludeDCs,
SkipPortScan = options.SkipPortCheck,
SkipPasswordAgeCheck = options.SkipPasswordCheck,
DisableKerberosSigning = options.DisableSigning,
SecureLDAP = options.ForceSecureLDAP,
InvalidateCache = options.RebuildCache,
NoZip = options.NoZip,
NoOutput = false,
Stealth = options.Stealth,
RandomizeFilenames = options.RandomFileNames,
MemCache = options.MemCache,
CollectAllProperties = options.CollectAllProperties,
DCOnly = dconly,
PrettyPrint = options.PrettyPrint,
SearchForest = options.SearchForest,
RecurseDomains = options.RecurseDomains,
DoLocalAdminSessionEnum = options.DoLocalAdminSessionEnum,
ParititonLdapQueries = options.PartitionLdapQueries,
Metrics = options.Metrics,
};
var ldapOptions = new LdapConfig
{
Port = options.LDAPPort,
SSLPort = options.LDAPSSLPort,
DisableSigning = options.DisableSigning,
ForceSSL = options.ForceSecureLDAP,
AuthType = AuthType.Negotiate,
DisableCertVerification = options.DisableCertVerification
};
if (options.DomainController != null) ldapOptions.Server = options.DomainController;
if (options.LDAPCredentialJsonPath != null) {
string json = File.ReadAllText(options.LDAPCredentialJsonPath);
Credentials ldapCreds = JsonConvert.DeserializeObject<Credentials>(json);
ldapOptions.Username = ldapCreds.Username;
ldapOptions.Password = ldapCreds.Password;
}
if (options.LDAPEnvUsername != null) {
if (options.LDAPEnvPassword == null) {
logger.LogError("You must specify LDAPEnvPassword if using the LDAPEnvUsername options");
return;
}
string EnvUsername = Environment.GetEnvironmentVariable(options.LDAPEnvUsername);
string EnvPassword = Environment.GetEnvironmentVariable(options.LDAPEnvPassword);
ldapOptions.Username = EnvUsername;
ldapOptions.Password = EnvPassword;
}
if (options.LDAPUsername != null) {
if (options.LDAPPassword == null) {
logger.LogError("You must specify LDAPPassword if using the LDAPUsername options");
return;
}
ldapOptions.Username = options.LDAPUsername;
ldapOptions.Password = options.LDAPPassword;
}
// Check to make sure both Local Admin Session Enum options are set if either is set
if (options.LocalAdminPassword != null && options.LocalAdminUsername == null ||
options.LocalAdminUsername != null && options.LocalAdminPassword == null)
{
logger.LogError(
"You must specify both LocalAdminUsername and LocalAdminPassword if using these options!");
return;
}
// Check to make sure doLocalAdminSessionEnum is set when specifying localadmin and password
if (options.LocalAdminPassword != null || options.LocalAdminUsername != null)
{
if (options.DoLocalAdminSessionEnum == false)
{
logger.LogError(
"You must use the --doLocalAdminSessionEnum switch in combination with --LocalAdminUsername and --LocalAdminPassword!");
return;
}
}
// Check to make sure LocalAdminUsername and LocalAdminPassword are set when using doLocalAdminSessionEnum
if (options.DoLocalAdminSessionEnum == true)
{
if (options.LocalAdminPassword == null || options.LocalAdminUsername == null)
{
logger.LogError(
"You must specify both LocalAdminUsername and LocalAdminPassword if using the --doLocalAdminSessionEnum option!");
return;
}
}
if (flags.Metrics) {
var metricsRegistry = new MetricRegistry();
metricsRegistry.RegisterDefaultMetrics();
metricsRegistry.Seal();
var fileSinkOptions = new FileMetricSinkOptions {
FlushInterval = TimeSpan.FromSeconds(5),
};
var metricsWriter = new MetricWriter();
var metricsFileName = string.IsNullOrEmpty(options.OutputPrefix) ? "metrics.log" : $"{options.OutputPrefix}_metrics.log";
var metricsFilePath = System.IO.Path.Combine(options.OutputDirectory, metricsFileName);
var fileSink = new FileMetricSink(
metricsRegistry.Definitions,
filePath: metricsFilePath,
metricsWriter,
fileSinkOptions);
var metricsRouter = new MetricRouter(
metricsRegistry.Definitions,
[fileSink],
new DefaultLabelValuesCache());
Metrics.Factory = new MetricFactory(metricsRouter);
_flushTimer = new MetricsFlushTimer(
flush: metricsRouter.Flush,
interval: fileSinkOptions.FlushInterval);
}
await StartCollection(options, logger, resolved, flags, ldapOptions);
});
} catch (Exception ex) {
logger.LogError($"Error running SharpHound: {ex.Message}\n{ex.StackTrace}");
_flushTimer?.Dispose();
}
}
private static async Task StartCollection(Options options, BasicLogger logger, CollectionMethod resolved, Flags flags, LdapConfig ldapOptions)
{
IContext context = new BaseContext(logger, ldapOptions, flags)
{
DomainName = options.Domain,
CacheFileName = options.CacheName,
ZipFilename = options.ZipFilename,
SearchBase = options.DistinguishedName,
StatusInterval = options.StatusInterval,
RealDNSName = options.RealDNSName,
ComputerFile = options.ComputerFile,
OutputPrefix = options.OutputPrefix,
OutputDirectory = options.OutputDirectory,
Jitter = options.Jitter,
Throttle = options.Throttle,
LdapFilter = options.LdapFilter,
PortScanTimeout = options.PortCheckTimeout,
ResolvedCollectionMethods = resolved,
Threads = options.Threads,
LoopDuration = options.LoopDuration,
LoopInterval = options.LoopInterval,
ZipPassword = options.ZipPassword,
IsFaulted = false,
LocalAdminUsername = options.LocalAdminUsername,
LocalAdminPassword = options.LocalAdminPassword
};
var cancellationTokenSource = new CancellationTokenSource();
context.CancellationTokenSource = cancellationTokenSource;
// Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs eventArgs)
// {
// eventArgs.Cancel = true;
// cancellationTokenSource.Cancel();
// };
// Create new chain links
Links<IContext> links = new SharpLinks();
// Run our chain
context = links.Initialize(context, ldapOptions);
if (context.Flags.IsFaulted)
return;
context = await links.TestConnection(context);
if (context.Flags.IsFaulted)
return;
context = links.SetSessionUserName(options.OverrideUserName, context);
context = links.InitCommonLib(context);
context = await links.GetDomainsForEnumeration(context);
if (context.Flags.IsFaulted)
return;
context = links.StartBaseCollectionTask(context);
context = await links.AwaitBaseRunCompletion(context);
context = links.StartLoopTimer(context);
context = links.StartLoop(context);
context = await links.AwaitLoopCompletion(context);
context = links.SaveCacheFile(context);
links.Finish(context);
_flushTimer?.Dispose();
}
// Accessor function for the PS1 to work, do not change or remove
public static void InvokeSharpHound(string[] args) {
Main(args).Wait();
}
}
#endregion
}