-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathhttp.go
321 lines (279 loc) · 8.81 KB
/
http.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
package http
import (
"bytes"
"crypto/tls"
"encoding/base64"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"reflect"
"regexp"
"strconv"
"strings"
"soarca/logger"
"soarca/models/cacao"
)
var (
component = reflect.TypeOf(HttpRequest{}).PkgPath()
log *logger.Log
)
type HttpOptions struct {
Target *cacao.AgentTarget
Command *cacao.Command
Auth *cacao.AuthenticationInformation
}
type IHttpOptions interface {
ExtractUrl() (string, error)
}
type IHttpRequest interface {
Request(httpOptions HttpOptions) ([]byte, error)
}
type HttpRequest struct {
skipCertificateValidation bool
}
// https://gist.githubusercontent.com/ahmetozer/ffa4cd0b319aff32ea9ed0068c8b81cf/raw/fc8742e6e087451e954bf0da214794a620356a4d/IPv4-IPv6-domain-regex.go
const (
ipv6Regex = `^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$`
ipv4Regex = `^(((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4})`
domainRegex = `^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$`
)
func (httpRequest *HttpRequest) SkipCertificateValidation(skip bool) {
httpRequest.skipCertificateValidation = skip
}
func (httpRequest *HttpRequest) Request(httpOptions HttpOptions) ([]byte, error) {
log = logger.Logger(component, logger.Info, "", logger.Json)
request, err := httpOptions.setupRequest()
if err != nil {
return []byte{}, err
}
transport := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: httpRequest.skipCertificateValidation},
}
client := &http.Client{Transport: transport}
log.Trace(request)
response, err := client.Do(request)
if err != nil {
log.Error(err)
return []byte{}, err
}
defer response.Body.Close()
return httpOptions.handleResponse(response)
}
func (httpOptions *HttpOptions) setupRequest() (*http.Request, error) {
parsedUrl, err := httpOptions.ExtractUrl()
if err != nil {
log.Error(err)
return nil, err
}
method, err := GetMethodFrom(httpOptions.Command)
if err != nil {
log.Error(err)
return nil, err
}
requestBuffer := bytes.NewBufferString("")
if httpOptions.Command.Content != "" {
log.Debug("using the content field")
requestBuffer = bytes.NewBufferString(httpOptions.Command.Content)
} else if httpOptions.Command.ContentB64 != "" {
log.Debug("using base64 content")
byteString, err := base64.StdEncoding.DecodeString(httpOptions.Command.ContentB64)
if err != nil {
log.Error("error decoding base64", err)
} else {
log.Trace(string(byteString))
requestBuffer = bytes.NewBufferString(string(byteString))
}
}
log.Trace("request buffer is: ", requestBuffer)
request, err := http.NewRequest(method, parsedUrl, requestBuffer)
if err != nil {
log.Error(err)
return nil, err
}
httpOptions.addHeaderTo(request)
err = httpOptions.addAuthTo(request)
if err != nil {
log.Error(err)
return nil, err
}
return request, nil
}
func (httpRequest *HttpOptions) handleResponse(response *http.Response) ([]byte, error) {
responseBytes, err := io.ReadAll(response.Body)
if err != nil {
log.Error(err)
return []byte{}, err
}
sc := response.StatusCode
log.Trace(fmt.Sprint(sc))
log.Trace(string(responseBytes))
if sc < 200 || sc > 299 {
return []byte{}, errors.New(string(responseBytes))
}
return responseBytes, nil
}
func verifyAuthInfoMatchesAgentTarget(
target *cacao.AgentTarget, authInfo *cacao.AuthenticationInformation,
) error {
if target.AuthInfoIdentifier == "" || authInfo.ID == "" {
return errors.New("target target.AuthInfoIndentifier or authInfo.ID is empty")
}
if !(target.AuthInfoIdentifier == authInfo.ID) {
return errors.New("target auth info Id does not match auth info object's")
}
return nil
}
func (httpOptions *HttpOptions) addHeaderTo(request *http.Request) {
for headerKey, headerValues := range httpOptions.Command.Headers {
for _, headerValue := range headerValues {
request.Header.Add(headerKey, headerValue)
}
}
}
func (httpOptions *HttpOptions) addAuthTo(request *http.Request) error {
if httpOptions.Auth == nil {
return nil
}
if (cacao.AuthenticationInformation{}) == *httpOptions.Auth {
return nil
}
if err := verifyAuthInfoMatchesAgentTarget(httpOptions.Target, httpOptions.Auth); err != nil {
return errors.New("auth info does not match target Id")
}
authInfoType := httpOptions.Auth.Type
switch authInfoType {
case cacao.AuthInfoHTTPBasicType:
request.SetBasicAuth(httpOptions.Auth.Username, httpOptions.Auth.Password)
case cacao.AuthInfoOAuth2Type:
bearer := fmt.Sprintf("Bearer %s", httpOptions.Auth.Token)
request.Header.Add("Authorization", bearer)
case "":
// It means that AuthN information is not set
return nil
default:
return errors.New("unsupported authentication type: " + authInfoType)
}
return nil
}
func (httpOptions *HttpOptions) ExtractUrl() (string, error) {
if httpOptions.Command == nil || httpOptions.Target == nil {
return "", errors.New("not enough http options supplied, nil found")
}
path, err := GetPathFrom(httpOptions.Command)
if err != nil {
log.Error(err)
return "", err
}
target := httpOptions.Target
if len(target.Address) == 0 {
return "", errors.New("cacao.AgentTarget does not contain enough information to build a proper query path")
}
if target.Port != "" {
if err := validatePort(target.Port); err != nil {
return "", err
}
}
if len(target.Address["url"]) > 0 {
if target.Address["url"][0] != "" {
return parsePathBasedUrl(target.Address["url"][0])
}
}
return buildSchemeAndHostname(path, target)
}
func buildSchemeAndHostname(path string, target *cacao.AgentTarget) (string, error) {
var hostname string
scheme := setDefaultScheme(target)
hostname, err := extractHostname(scheme, target)
if err != nil {
return "", err
}
parsedUrl := &url.URL{
Scheme: scheme,
Host: fmt.Sprintf("%s:%s", hostname, target.Port),
Path: path,
}
return parsedUrl.String(), nil
}
func setDefaultScheme(target *cacao.AgentTarget) string {
if target.Port == "" {
target.Port = "80"
}
// Set the default scheme to HTTPS
scheme := "https"
if target.Port == "80" || target.Port == "8080" {
scheme = "http"
}
return scheme
}
func extractHostname(scheme string, target *cacao.AgentTarget) (string, error) {
var address string
if len(target.Address["dname"]) > 0 {
match, _ := regexp.MatchString(domainRegex, target.Address["dname"][0])
if !match {
return "", errors.New("failed regex rule for domain name")
}
address = target.Address["dname"][0]
} else if len(target.Address["ipv4"]) > 0 {
match, _ := regexp.MatchString(ipv4Regex, target.Address["ipv4"][0])
if !match {
return "", errors.New("failed regex rule for domain name")
}
address = target.Address["ipv4"][0]
} else if len(target.Address["url"]) > 0 {
match, _ := regexp.MatchString(ipv4Regex, target.Address["url"][0])
if !match {
return "", errors.New("failed regex rule for domain name")
}
address = target.Address["url"][0]
} else {
return "", errors.New("unsupported target address type")
}
return address, nil
}
func parsePathBasedUrl(httpUrl string) (string, error) {
parsedUrl, err := url.ParseRequestURI(httpUrl)
if err != nil {
return "", err
}
if parsedUrl.Hostname() == "" {
return "", errors.New("no domain name")
}
return parsedUrl.String(), nil
}
func validatePort(port string) error {
portNum, err := strconv.Atoi(port)
if err != nil {
return errors.New("could not parse string to port number")
}
if portNum < 1 || portNum > 65535 {
return errors.New("port must be in the range 1-65535")
}
return nil
}
func GetMethodFrom(command *cacao.Command) (string, error) {
return extractCommandFieldByIndex(command, 0)
}
func GetPathFrom(command *cacao.Command) (string, error) {
return extractCommandFieldByIndex(command, 1)
}
func GetVersionFrom(command *cacao.Command) (string, error) {
return extractCommandFieldByIndex(command, 2)
}
func extractCommandFieldByIndex(command *cacao.Command, index int) (string, error) {
if command == nil {
return "", errors.New("command pointer is empty")
}
if index < 0 || index > 2 {
return "", errors.New("invalid index")
}
parts := strings.Fields(command.Command)
if len(parts) != 3 {
return "", errors.New("invalid request format")
}
if parts[0] == "" || parts[1] == "" || parts[2] == "" {
return "", errors.New("method, path, or HTTP version is empty")
}
return parts[index], nil
}