forked from RedTeamPentesting/adauth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoptions.go
342 lines (280 loc) · 8.57 KB
/
options.go
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
package adauth
import (
"context"
"crypto/rsa"
"encoding/hex"
"fmt"
"io"
"net"
"os"
"strconv"
"strings"
"github.com/RedTeamPentesting/adauth/othername"
"github.com/spf13/pflag"
"software.sslmate.com/src/go-pkcs12"
)
// Options holds command line options that are used to determine authentication
// credentials and target.
type Options struct {
// Username (with domain) in one of the following formats:
// `UPN`, `domain\user`, `domain/user` or `user`
User string
Password string
NTHash string
AESKey string
CCache string
DomainController string
ForceKerberos bool
PFXFileName string
PFXPassword string
credential *Credential
flagset *pflag.FlagSet
Debug func(fmt string, a ...any)
Resolver Resolver
}
// RegisterFlags registers authentication flags to a pflag.FlagSet such as the
// default flagset `pflag.CommandLine`.
func (opts *Options) RegisterFlags(flagset *pflag.FlagSet) {
defaultCCACHEFile := os.Getenv("KRB5CCNAME")
ccacheHint := ""
if defaultCCACHEFile == "" {
ccacheHint = " (defaults to $KRB5CCNAME, currently unset)"
}
flagset.StringVarP(&opts.User, "user", "u", "", "Username ('`user@domain`', 'domain\\user', 'domain/user' or 'user')")
flagset.StringVarP(&opts.Password, "password", "p", "", "Password")
flagset.StringVarP(&opts.NTHash, "nt-hash", "H", "", "NT `hash` ('NT', ':NT' or 'LM:NT')")
flagset.StringVar(&opts.AESKey, "aes-key", "", "Kerberos AES `hex key`")
flagset.StringVar(&opts.PFXFileName, "pfx", "", "Client certificate and private key as PFX `file`")
flagset.StringVar(&opts.PFXPassword, "pfx-password", "", "Password for PFX file")
flagset.StringVar(&opts.CCache, "ccache", defaultCCACHEFile, "Kerberos CCache `file` name"+ccacheHint)
flagset.StringVar(&opts.DomainController, "dc", "", "Domain controller")
flagset.BoolVarP(&opts.ForceKerberos, "kerberos", "k", false, "Use Kerberos authentication")
opts.flagset = flagset
}
func (opts *Options) debug(format string, a ...any) {
if opts.Debug != nil {
opts.Debug(format, a...)
}
}
func portForProtocol(protocol string) string {
switch strings.ToLower(protocol) {
case "ldap":
return "389"
case "ldaps":
return "636"
case "http":
return "80"
case "https":
return "443"
case "smb":
return "445"
case "rdp":
return "3389"
case "kerberos":
return "88"
default:
return ""
}
}
func addPortForProtocolIfMissing(protocol string, addr string) string {
host, port, err := net.SplitHostPort(addr)
if err != nil || port != "" {
return addr
}
port = portForProtocol(protocol)
if port == "" {
return addr
}
return net.JoinHostPort(host, port)
}
// WithDCTarget returns credentials and the domain controller for the
// corresponding domain as the target.
func (opts *Options) WithDCTarget(ctx context.Context, protocol string) (*Credential, *Target, error) {
if opts.DomainController != "" {
return opts.WithTarget(ctx, protocol, addPortForProtocolIfMissing(protocol, opts.DomainController))
}
cred, err := opts.preliminaryCredential()
if err != nil {
return nil, nil, err
}
if cred.Domain == "" {
return nil, nil, fmt.Errorf("domain unknown")
}
resolver := ensureResolver(opts.Resolver, opts.debug)
var dcAddr string
host, port, err := resolver.LookupFirstService(context.Background(), protocol, cred.Domain)
if err != nil {
lookupSRVErr := fmt.Errorf("could not lookup %q service of domain %q: %w", protocol, cred.Domain, err)
dcAddr, err = resolver.LookupDCByDomain(context.Background(), cred.Domain)
if err != nil {
return nil, nil, fmt.Errorf("could not find DC: %w and %w", lookupSRVErr, err)
}
port := portForProtocol(protocol)
if port != "" {
dcAddr = net.JoinHostPort(dcAddr, port)
}
opts.debug("using DC %s based on domain lookup for %s", dcAddr, cred.Domain)
} else {
dcAddr = net.JoinHostPort(host, strconv.Itoa(port))
opts.debug("using DC %s based on SRV lookup for domain %s", dcAddr, cred.Domain)
}
return cred, newTarget(
protocol, dcAddr, opts.ForceKerberos || cred.mustUseKerberos(), opts.CCache, opts.Resolver), nil
}
// WithTarget returns credentials and the specified target.
func (opts *Options) WithTarget(ctx context.Context, protocol string, target string) (*Credential, *Target, error) {
if protocol == "" {
protocol = "host"
}
cred, err := opts.preliminaryCredential()
if err != nil {
return nil, nil, err
}
t := newTarget(protocol, target, opts.ForceKerberos || cred.mustUseKerberos(), opts.CCache, opts.Resolver)
if cred.Domain == "" {
hostname, err := t.Hostname(ctx)
if err != nil {
return nil, nil, fmt.Errorf("lookup target hostname to determine domain: %w", err)
}
parts := strings.SplitN(hostname, ".", 2)
if len(parts) == 2 {
switch {
case strings.Contains(parts[1], "."):
cred.Domain = parts[1]
default:
cred.Domain = hostname
}
}
}
return cred, t, nil
}
// Username returns the user's name. Username may return an empty string.
func (opts *Options) Username() string {
cred, err := opts.preliminaryCredential()
if err != nil {
return ""
}
return cred.Username
}
// UPN returns the user's domain. Domain may return an empty string.
func (opts *Options) Domain() string {
cred, err := opts.preliminaryCredential()
if err != nil {
return ""
}
return cred.Domain
}
// UPN returns the user's universal principal name. UPN may return an empty
// string.
func (opts *Options) UPN() string {
cred, err := opts.preliminaryCredential()
if err != nil {
return ""
}
return cred.UPN()
}
// NoTarget returns the user credentials without supplementing it with
// information from a target.
func (opts *Options) NoTarget() (*Credential, error) {
return opts.preliminaryCredential()
}
func (opts *Options) preliminaryCredential() (*Credential, error) {
if opts.credential != nil {
return opts.credential, nil
}
domain, username := splitUserIntoDomainAndUsername(opts.User)
cleanedNTHash := cleanNTHash(opts.NTHash)
var ntHash string
if cleanedNTHash != "" {
ntHashBytes, err := hex.DecodeString(cleanedNTHash)
if err != nil {
return nil, fmt.Errorf("invalid NT hash: parse hex: %w", err)
} else if len(ntHashBytes) != 16 {
return nil, fmt.Errorf("invalid NT hash: %d bytes instead of 16", len(ntHashBytes))
}
ntHash = cleanedNTHash
}
var aesKey string
if opts.AESKey != "" {
aesKeyBytes, err := hex.DecodeString(opts.AESKey)
if err != nil {
return nil, fmt.Errorf("invalid AES key: parse hex: %w", err)
} else if len(aesKeyBytes) != 16 && len(aesKeyBytes) != 32 {
return nil, fmt.Errorf("invalid AES key: %d bytes instead of 16 or 32", len(aesKeyBytes))
}
aesKey = opts.AESKey
}
var ccache string
if opts.CCache != "" {
s, err := os.Stat(opts.CCache)
if err == nil && !s.IsDir() {
ccache = opts.CCache
}
}
cred := &Credential{
Username: username,
Password: opts.Password,
Domain: domain,
NTHash: cleanNTHash(ntHash),
AESKey: aesKey,
CCache: ccache,
dc: opts.DomainController,
PasswordIsEmtpyString: opts.Password == "" && (opts.flagset != nil && opts.flagset.Changed("password")),
CCacheIsFromEnv: opts.CCache != "" && (opts.flagset != nil && !opts.flagset.Changed("ccache")),
Resolver: opts.Resolver,
}
if opts.PFXFileName != "" {
pfxData, err := os.ReadFile(opts.PFXFileName)
if err != nil {
return nil, fmt.Errorf("read PFX: %w", err)
}
key, cert, caCerts, err := pkcs12.DecodeChain(pfxData, opts.PFXPassword)
if err != nil {
return nil, fmt.Errorf("decode PFX: %w", err)
}
rsaKey, ok := key.(*rsa.PrivateKey)
if !ok {
return nil, fmt.Errorf("PFX key is not an RSA private key but %T", rsaKey)
}
cred.ClientCert = cert
cred.ClientCertKey = rsaKey
cred.CACerts = caCerts
}
//nolint:nestif
if cred.ClientCert != nil {
user, domain, err := othername.UserAndDomain(cred.ClientCert)
if err == nil {
if cred.Username == "" {
cred.Username = user
}
if cred.Domain == "" {
cred.Domain = domain
}
}
}
opts.credential = cred
return cred, nil
}
// NewDebugFunc creates a debug output handler.
func NewDebugFunc(enabled *bool, writer io.Writer, colored bool) func(string, ...any) {
return func(format string, a ...any) {
if enabled == nil || !*enabled {
return
}
format = strings.TrimRight(format, "\n")
if colored {
format = "\033[2m" + format + "\033[0m"
}
_, _ = fmt.Fprintf(writer, format+"\n", a...)
}
}
func cleanNTHash(h string) string {
if !strings.Contains(h, ":") {
return h
}
parts := strings.Split(h, ":")
if len(parts) != 2 {
return h
}
return parts[1]
}