-
Notifications
You must be signed in to change notification settings - Fork 70
/
utils.go
427 lines (372 loc) · 11.3 KB
/
utils.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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
// Copyright (C) 2022 Specter Ops, Inc.
//
// This file is part of AzureHound.
//
// AzureHound 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.
//
// AzureHound 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 <https://www.gnu.org/licenses/>.
package cmd
import (
"bufio"
"bytes"
"context"
"crypto/hmac"
"crypto/sha256"
"crypto/tls"
"encoding/base64"
"fmt"
"io/fs"
"io/ioutil"
"net"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"time"
"github.com/bloodhoundad/azurehound/client"
client_config "github.com/bloodhoundad/azurehound/client/config"
"github.com/bloodhoundad/azurehound/client/rest"
"github.com/bloodhoundad/azurehound/config"
"github.com/bloodhoundad/azurehound/enums"
"github.com/bloodhoundad/azurehound/logger"
"github.com/bloodhoundad/azurehound/models"
"github.com/bloodhoundad/azurehound/pipeline"
"github.com/bloodhoundad/azurehound/sinks"
"github.com/spf13/cobra"
"golang.org/x/net/proxy"
)
func exit(err error) {
log.Error(err, "encountered unrecoverable error")
log.GetSink()
os.Exit(1)
}
func persistentPreRunE(cmd *cobra.Command, args []string) error {
// need to set config flag value explicitly
if cmd != nil {
if configFlag := cmd.Flag(config.ConfigFile.Name).Value.String(); configFlag != "" {
config.ConfigFile.Set(configFlag)
}
}
config.LoadValues(cmd, config.Options())
config.SetAzureDefaults()
if logr, err := logger.GetLogger(); err != nil {
return err
} else {
log = *logr
if config.ConfigFileUsed() != "" {
log.V(1).Info(fmt.Sprintf("Config File: %v", config.ConfigFileUsed()))
}
if config.LogFile.Value() != "" {
log.V(1).Info(fmt.Sprintf("Log File: %v", config.LogFile.Value()))
}
return nil
}
}
func gracefulShutdown(stop context.CancelFunc) {
stop()
fmt.Fprintln(os.Stderr, "\nshutting down gracefully, press ctrl+c again to force")
// TODO timeout context
}
func testConnections() error {
if _, err := dial(config.AzAuthUrl.Value().(string)); err != nil {
return fmt.Errorf("unable to connect to %s: %w", config.AzAuthUrl.Value(), err)
} else if _, err := dial(config.AzGraphUrl.Value().(string)); err != nil {
return fmt.Errorf("unable to connect to %s: %w", config.AzGraphUrl.Value(), err)
} else if _, err := dial(config.AzMgmtUrl.Value().(string)); err != nil {
return fmt.Errorf("unable to connect to %s: %w", config.AzMgmtUrl.Value(), err)
} else {
return nil
}
}
type httpsDialer struct{}
func (s httpsDialer) Dial(network string, addr string) (net.Conn, error) {
return tls.Dial(network, addr, &tls.Config{})
}
func newProxyDialer(url *url.URL, forward proxy.Dialer) (proxy.Dialer, error) {
dialer := &proxyDialer{
host: url.Host,
forward: forward,
}
if url.User != nil {
dialer.user = url.User.Username()
dialer.pass, _ = url.User.Password()
}
return dialer, nil
}
type proxyDialer struct {
host string
user string
pass string
forward proxy.Dialer
}
func (s proxyDialer) Dial(network string, addr string) (net.Conn, error) {
if s.forward == nil {
return nil, fmt.Errorf("unable to connect to %s: forward dialer not set", s.host)
} else if conn, err := s.forward.Dial(network, s.host); err != nil {
return nil, fmt.Errorf("unable to connect to %s: %w", s.host, err)
} else if req, err := http.NewRequest("CONNECT", "//"+addr, nil); err != nil {
conn.Close()
return nil, fmt.Errorf("unable to connect to %s: %w", addr, err)
} else {
req.Close = false
if s.user != "" {
req.SetBasicAuth(s.user, s.pass)
}
// Write request over proxy connection
if err := req.Write(conn); err != nil {
conn.Close()
return nil, fmt.Errorf("unable to connect to %s: %w", addr, err)
}
res, err := http.ReadResponse(bufio.NewReader(conn), req)
defer func() {
if res.Body != nil {
res.Body.Close()
}
}()
if err != nil {
conn.Close()
return nil, fmt.Errorf("unable to connect to %s: %w", addr, err)
} else if res.StatusCode != 200 {
if res.Body != nil {
res.Body.Close()
}
conn.Close()
return nil, fmt.Errorf("unable to connect to %s via proxy (%s): statusCode %d", addr, s.host, res.StatusCode)
} else {
return conn, nil
}
}
}
func getDialer() (proxy.Dialer, error) {
if proxyUrl := config.Proxy.Value().(string); proxyUrl == "" {
return proxy.Direct, nil
} else if url, err := url.Parse(proxyUrl); err != nil {
return nil, err
} else if url.Scheme == "https" {
return proxy.FromURL(url, httpsDialer{})
} else {
return proxy.FromURL(url, proxy.Direct)
}
}
func init() {
proxy.RegisterDialerType("http", newProxyDialer)
proxy.RegisterDialerType("https", newProxyDialer)
}
func dial(targetUrl string) (string, error) {
log.V(2).Info("dialing...", "targetUrl", targetUrl)
if dialer, err := getDialer(); err != nil {
return "", err
} else if url, err := url.Parse(targetUrl); err != nil {
return "", err
} else {
port := url.Port()
if port == "" {
port = "443"
}
if conn, err := dialer.Dial("tcp", fmt.Sprintf("%s:%s", url.Hostname(), port)); err != nil {
return "", err
} else {
defer conn.Close()
addr := conn.LocalAddr().(*net.TCPAddr)
return addr.IP.String(), nil
}
}
}
func newAzureClient() (client.AzureClient, error) {
var (
certFile = config.AzCert.Value()
keyFile = config.AzKey.Value()
clientCert string
clientKey string
)
if file, ok := certFile.(string); ok && file != "" {
if content, err := ioutil.ReadFile(certFile.(string)); err != nil {
return nil, fmt.Errorf("unable to read provided certificate: %w", err)
} else {
clientCert = string(content)
}
}
if file, ok := keyFile.(string); ok && file != "" {
if content, err := ioutil.ReadFile(keyFile.(string)); err != nil {
return nil, fmt.Errorf("unable to read provided key file: %w", err)
} else {
clientKey = string(content)
}
}
config := client_config.Config{
ApplicationId: config.AzAppId.Value().(string),
Authority: config.AzAuthUrl.Value().(string),
ClientSecret: config.AzSecret.Value().(string),
ClientCert: clientCert,
ClientKey: clientKey,
ClientKeyPass: config.AzKeyPass.Value().(string),
Graph: config.AzGraphUrl.Value().(string),
JWT: config.JWT.Value().(string),
Management: config.AzMgmtUrl.Value().(string),
MgmtGroupId: config.AzMgmtGroupId.Value().([]string),
Password: config.AzPassword.Value().(string),
ProxyUrl: config.Proxy.Value().(string),
RefreshToken: config.RefreshToken.Value().(string),
Region: config.AzRegion.Value().(string),
SubscriptionId: config.AzSubId.Value().([]string),
Tenant: config.AzTenant.Value().(string),
Username: config.AzUsername.Value().(string),
}
return client.NewClient(config)
}
func newSigningHttpClient(signature, tokenId, token, proxyUrl string) (*http.Client, error) {
if client, err := rest.NewHTTPClient(proxyUrl); err != nil {
return nil, err
} else {
client.Transport = signingTransport{
base: client.Transport,
tokenId: tokenId,
token: token,
signature: signature,
}
return client, nil
}
}
type signingTransport struct {
base http.RoundTripper
tokenId string
token string
signature string
}
func (s signingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
clone := req.Clone(req.Context())
// token
digester := hmac.New(sha256.New, []byte(s.token))
// path
if _, err := digester.Write([]byte(req.Method + req.URL.Path)); err != nil {
return nil, err
}
// datetime
datetime := time.Now().Format(time.RFC3339)
digester = hmac.New(sha256.New, digester.Sum(nil))
if _, err := digester.Write([]byte(datetime[:13])); err != nil {
return nil, err
}
// body
body := &bytes.Buffer{}
digester = hmac.New(sha256.New, digester.Sum(nil))
if req.Body != nil {
defer req.Body.Close()
if contentLength, err := body.ReadFrom(req.Body); err != nil {
return nil, err
} else if contentLength != 0 {
req.Body = ioutil.NopCloser(bytes.NewReader(body.Bytes()))
clone.Body = ioutil.NopCloser(bytes.NewReader(body.Bytes()))
}
}
if _, err := digester.Write(body.Bytes()); err != nil {
return nil, err
}
signature := digester.Sum(nil)
clone.Header.Set("Authorization", fmt.Sprintf("%s %s", s.signature, s.tokenId))
clone.Header.Set("RequestDate", datetime)
clone.Header.Set("Signature", base64.StdEncoding.EncodeToString(signature))
return s.base.RoundTrip(clone)
}
func contains(collection []string, value string) bool {
for _, item := range collection {
if item == value {
return true
}
}
return false
}
func unique(collection []string) []string {
keys := make(map[string]bool)
list := []string{}
for _, item := range collection {
if _, found := keys[item]; !found {
keys[item] = true
list = append(list, item)
}
}
return list
}
func stat(path string) (string, fs.FileInfo, error) {
if info, err := os.Stat(path); err == nil {
return path, info, nil
} else {
p := path + ".exe"
info, err := os.Stat(p)
return p, info, err
}
}
func getExePath() (string, error) {
exe := os.Args[0]
if exePath, err := filepath.Abs(exe); err != nil {
return "", err
} else if path, info, err := stat(exePath); err != nil {
return "", err
} else if info.IsDir() {
return "", fmt.Errorf("%s is a directory", path)
} else {
return path, nil
}
}
func setupLogger() {
if logger, err := logger.GetLogger(); err != nil {
panic(err)
} else {
log = *logger
}
}
// deprecated: use azureWrapper instead
type AzureWrapper struct {
Kind enums.Kind `json:"kind"`
Data interface{} `json:"data"`
}
type azureWrapper[T any] struct {
Kind enums.Kind `json:"kind"`
Data T `json:"data"`
}
func NewAzureWrapper[T any](kind enums.Kind, data T) azureWrapper[T] {
return azureWrapper[T]{
Kind: kind,
Data: data,
}
}
func outputStream[T any](ctx context.Context, stream <-chan T) {
formatted := pipeline.FormatJson(ctx.Done(), stream)
if path := config.OutputFile.Value().(string); path != "" {
if err := sinks.WriteToFile(ctx, path, formatted); err != nil {
exit(err)
}
} else {
sinks.WriteToConsole(ctx, formatted)
}
}
func kvRoleAssignmentFilter(roleId string) func(models.KeyVaultRoleAssignment) bool {
return func(ra models.KeyVaultRoleAssignment) bool {
return path.Base(ra.RoleAssignment.Properties.RoleDefinitionId) == roleId
}
}
func vmRoleAssignmentFilter(roleId string) func(models.VirtualMachineRoleAssignment) bool {
return func(ra models.VirtualMachineRoleAssignment) bool {
return path.Base(ra.RoleAssignment.Properties.RoleDefinitionId) == roleId
}
}
func rgRoleAssignmentFilter(roleId string) func(models.ResourceGroupRoleAssignment) bool {
return func(ra models.ResourceGroupRoleAssignment) bool {
return path.Base(ra.RoleAssignment.Properties.RoleDefinitionId) == roleId
}
}
func mgmtGroupRoleAssignmentFilter(roleId string) func(models.ManagementGroupRoleAssignment) bool {
return func(ra models.ManagementGroupRoleAssignment) bool {
return path.Base(ra.RoleAssignment.Properties.RoleDefinitionId) == roleId
}
}