-
Notifications
You must be signed in to change notification settings - Fork 70
/
client.go
291 lines (269 loc) · 9.12 KB
/
client.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
// 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 rest
//go:generate go run github.com/golang/mock/mockgen -destination=./mocks/client.go -package=mocks . RestClient
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"math"
"net/http"
"net/url"
"strconv"
"sync"
"time"
"github.com/bloodhoundad/azurehound/client/config"
"github.com/bloodhoundad/azurehound/constants"
)
type RestClient interface {
Authenticate() error
Delete(ctx context.Context, path string, body interface{}, params, headers map[string]string) (*http.Response, error)
Get(ctx context.Context, path string, params, headers map[string]string) (*http.Response, error)
Patch(ctx context.Context, path string, body interface{}, params, headers map[string]string) (*http.Response, error)
Post(ctx context.Context, path string, body interface{}, params, headers map[string]string) (*http.Response, error)
Put(ctx context.Context, path string, body interface{}, params, headers map[string]string) (*http.Response, error)
Send(req *http.Request) (*http.Response, error)
}
func NewRestClient(apiUrl string, config config.Config) (RestClient, error) {
if auth, err := url.Parse(config.AuthorityUrl()); err != nil {
return nil, err
} else if api, err := url.Parse(apiUrl); err != nil {
return nil, err
} else if http, err := NewHTTPClient(config.ProxyUrl); err != nil {
return nil, err
} else {
client := &restClient{
*api,
*auth,
config.JWT,
config.ApplicationId,
config.ClientSecret,
config.ClientCert,
config.ClientKey,
config.ClientKeyPass,
config.Username,
config.Password,
http,
sync.RWMutex{},
config.RefreshToken,
config.Tenant,
Token{},
config.SubscriptionId,
config.MgmtGroupId,
}
return client, nil
}
}
type restClient struct {
api url.URL
authUrl url.URL
jwt string
clientId string
clientSecret string
clientCert string
clientKey string
clientKeyPass string
username string
password string
http *http.Client
mutex sync.RWMutex
refreshToken string
tenant string
token Token
subId []string
mgmtGroupId []string
}
func (s *restClient) Authenticate() error {
var (
path = url.URL{Path: fmt.Sprintf("/%s/oauth2/v2.0/token", s.tenant)}
endpoint = s.authUrl.ResolveReference(&path)
defaultScope = url.URL{Path: "/.default"}
scope = s.api.ResolveReference(&defaultScope)
body = url.Values{}
)
if s.clientId == "" {
body.Add("client_id", constants.AzPowerShellClientID)
} else {
body.Add("client_id", s.clientId)
}
body.Add("scope", scope.ResolveReference(&defaultScope).String())
if s.refreshToken != "" {
body.Add("grant_type", "refresh_token")
body.Add("refresh_token", s.refreshToken)
body.Set("client_id", constants.AzPowerShellClientID)
} else if s.clientSecret != "" {
body.Add("grant_type", "client_credentials")
body.Add("client_secret", s.clientSecret)
} else if s.clientCert != "" && s.clientKey != "" {
if clientAssertion, err := NewClientAssertion(endpoint.String(), s.clientId, s.clientCert, s.clientKey, s.clientKeyPass); err != nil {
return err
} else {
body.Add("grant_type", "client_credentials")
body.Add("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer")
body.Add("client_assertion", clientAssertion)
}
} else if s.username != "" && s.password != "" {
body.Add("grant_type", "password")
body.Add("username", s.username)
body.Add("password", s.password)
body.Set("client_id", constants.AzPowerShellClientID)
} else {
return fmt.Errorf("unable to authenticate. no valid credential provided")
}
if req, err := NewRequest(context.Background(), "POST", endpoint, body, nil, nil); err != nil {
return err
} else if res, err := s.send(req); err != nil {
return err
} else {
defer res.Body.Close()
s.mutex.Lock()
defer s.mutex.Unlock()
if err := json.NewDecoder(res.Body).Decode(&s.token); err != nil {
return err
} else {
return nil
}
}
}
func (s *restClient) Delete(ctx context.Context, path string, body interface{}, params, headers map[string]string) (*http.Response, error) {
endpoint := s.api.ResolveReference(&url.URL{Path: path})
if req, err := NewRequest(ctx, http.MethodDelete, endpoint, body, params, headers); err != nil {
return nil, err
} else {
return s.Send(req)
}
}
func (s *restClient) Get(ctx context.Context, path string, params, headers map[string]string) (*http.Response, error) {
endpoint := s.api.ResolveReference(&url.URL{Path: path})
if req, err := NewRequest(ctx, http.MethodGet, endpoint, nil, params, headers); err != nil {
return nil, err
} else {
return s.Send(req)
}
}
func (s *restClient) Patch(ctx context.Context, path string, body interface{}, params, headers map[string]string) (*http.Response, error) {
endpoint := s.api.ResolveReference(&url.URL{Path: path})
if req, err := NewRequest(ctx, http.MethodPatch, endpoint, body, params, headers); err != nil {
return nil, err
} else {
return s.Send(req)
}
}
func (s *restClient) Post(ctx context.Context, path string, body interface{}, params, headers map[string]string) (*http.Response, error) {
endpoint := s.api.ResolveReference(&url.URL{Path: path})
if req, err := NewRequest(ctx, http.MethodPost, endpoint, body, params, headers); err != nil {
return nil, err
} else {
return s.Send(req)
}
}
func (s *restClient) Put(ctx context.Context, path string, body interface{}, params, headers map[string]string) (*http.Response, error) {
endpoint := s.api.ResolveReference(&url.URL{Path: path})
if req, err := NewRequest(ctx, http.MethodPost, endpoint, body, params, headers); err != nil {
return nil, err
} else {
return s.Send(req)
}
}
func (s *restClient) Send(req *http.Request) (*http.Response, error) {
if s.jwt != "" {
if aud, err := ParseAud(s.jwt); err != nil {
return nil, err
} else if aud != s.api.String() {
return nil, fmt.Errorf("invalid audience")
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", s.jwt))
} else {
if s.token.IsExpired() {
if err := s.Authenticate(); err != nil {
return nil, err
}
}
req.Header.Set("Authorization", s.token.String())
}
return s.send(req)
}
func copyBody(req *http.Request) ([]byte, error) {
var (
body []byte
err error
)
if req.Body != nil {
body, err = io.ReadAll(req.Body)
if body != nil {
req.Body = io.NopCloser(bytes.NewBuffer(body))
}
}
return body, err
}
func (s *restClient) send(req *http.Request) (*http.Response, error) {
// copy the bytes in case we need to retry the request
if body, err := copyBody(req); err != nil {
return nil, err
} else {
var (
res *http.Response
err error
maxRetries = 3
)
// Try the request up to a set number of times
for retry := 0; retry < maxRetries; retry++ {
// Reusing http.Request requires rewinding the request body
// back to a working state
if body != nil && retry > 0 {
req.Body = io.NopCloser(bytes.NewBuffer(body))
}
// Try the request
if res, err = s.http.Do(req); err != nil {
// client error
return nil, err
} else if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusBadRequest {
// Error response code handling
// See official Retry guidance (https://learn.microsoft.com/en-us/azure/architecture/best-practices/retry-service-specific#retry-usage-guidance)
if res.StatusCode == http.StatusTooManyRequests {
retryAfterHeader := res.Header.Get("Retry-After")
if retryAfter, err := strconv.ParseInt(retryAfterHeader, 10, 64); err != nil {
return nil, fmt.Errorf("attempting to handle 429 but unable to parse retry-after header: %w", err)
} else {
// Wait the time indicated in the retry-after header
time.Sleep(time.Second * time.Duration(retryAfter))
continue
}
} else if res.StatusCode >= http.StatusInternalServerError {
// Wait the time calculated by the 5 second exponential backoff
backoff := math.Pow(5, float64(retry+1))
time.Sleep(time.Second * time.Duration(backoff))
continue
} else {
// Not a status code that warrants a retry
var errRes map[string]interface{}
if err := Decode(res.Body, &errRes); err != nil {
return nil, fmt.Errorf("malformed error response, status code: %d", res.StatusCode)
} else {
return nil, fmt.Errorf("%v", errRes)
}
}
} else {
// Response OK
return res, nil
}
}
return nil, fmt.Errorf("unable to complete the request after %d attempts: %w", maxRetries, err)
}
}