-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathhttphelper.go
530 lines (432 loc) · 14.1 KB
/
httphelper.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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
package protocol
import (
"bufio"
"bytes"
"crypto/tls"
_ "embed"
"fmt"
"io"
"mime/multipart"
"net"
"net/http"
"net/textproto"
"net/url"
"strconv"
"strings"
"time"
"github.com/vulncheck-oss/go-exploit/db"
"github.com/vulncheck-oss/go-exploit/output"
"github.com/vulncheck-oss/go-exploit/transform"
)
// GlobalUA is the default User-Agent for all go-exploit comms
//
//go:embed http-user-agent.txt
var GlobalUA string
// GlobalCommTimeout is the default timeout for all socket communications.
var GlobalCommTimeout = 10
// Returns a valid HTTP/HTTPS URL provided the given input.
func GenerateURL(rhost string, rport int, ssl bool, uri string) string {
url := ""
if ssl {
url += "https://"
} else {
url += "http://"
}
// is the address v6?
ip := net.ParseIP(rhost)
if ip != nil && ip.To4() == nil {
rhost = "[" + rhost + "]"
}
url += rhost
url += ":"
url += strconv.Itoa(rport)
url += uri
return url
}
// Using the variable amount of paths, return a URI without any extra '/'.
func BuildURI(paths ...string) string {
uri := "/"
for _, path := range paths {
if !strings.HasSuffix(uri, "/") && !strings.HasPrefix(path, "/") {
uri += "/"
}
uri += path
}
return uri
}
// BasicAuth takes a username and password and returns a string suitable for an Authorization header.
func BasicAuth(username, password string) string {
return "Basic " + transform.EncodeBase64(username+":"+password)
}
func parseCookies(headers []string) string {
cookies := make([]string, len(headers))
for i, cookie := range headers {
cookies[i] = strings.Split(cookie, ";")[0]
}
return strings.Join(cookies, "; ")
}
// ParseCookies parses an HTTP response and returns a string suitable for a Cookie header.
func ParseCookies(resp *http.Response) string {
return parseCookies(resp.Header.Values("Set-Cookie"))
}
// Go doesn't always like sending our exploit URI so use this raw version. SSL not implemented.
func DoRawHTTPRequest(rhost string, rport int, uri string, verb string) bool {
// connect
conn, success := TCPConnect(rhost, rport)
if !success {
return false
}
// is the address v6?
ip := net.ParseIP(rhost)
if ip != nil && ip.To4() == nil {
rhost = "[" + rhost + "]"
}
httpRequest := verb + " " + uri + " HTTP/1.1\r\n"
httpRequest += "Host: " + rhost + ":" + strconv.Itoa(rport) + "\r\n"
if len(GlobalUA) != 0 {
httpRequest += "User-Agent: " + GlobalUA + "\r\n"
}
httpRequest += "Accept: */*\r\n"
httpRequest += "\r\n"
success = TCPWrite(conn, []byte(httpRequest))
if !success {
return false
}
// don't currently care about the response. Read a byte and move on'
_, success = TCPReadAmount(conn, 1)
return success
}
// Cache the respsone in the database for later reuse.
func cacheResponse(req *http.Request, resp *http.Response) {
parsedURL, _ := url.Parse(req.URL.String())
port, err := strconv.Atoi(parsedURL.Port())
if err != nil {
output.PrintFrameworkError(err.Error())
return
}
respBuffer := &bytes.Buffer{}
err = resp.Write(respBuffer)
if err != nil {
output.PrintfFrameworkError("Resp write error: %s", err.Error())
return
}
db.CacheHTTPResponse(parsedURL.Hostname(), port, parsedURL.Path, respBuffer.Bytes())
}
// Look up matching URI in the HTTP cache and return it if found.
func cacheLookup(uri string) (*http.Response, string, bool) {
parsedURL, _ := url.Parse(uri)
port, err := strconv.Atoi(parsedURL.Port())
if err != nil {
output.PrintFrameworkError(err.Error())
return nil, "", false
}
cachedResp, ok := db.GetHTTPResponse(parsedURL.Hostname(), port, parsedURL.Path)
if !ok {
// didn't get any cache data. no big deal.
return nil, "", false
}
resp, err := http.ReadResponse(bufio.NewReader(strings.NewReader(cachedResp)), nil)
if err != nil {
output.PrintFrameworkError(err.Error())
return nil, "", false
}
defer resp.Body.Close()
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
// seen this fail when, for example, Shodan messes with chunking
output.PrintFrameworkError(err.Error())
return nil, "", false
}
if bytes.HasPrefix(bodyBytes, []byte("\x1f\x8b\x08")) {
// if the data in the cache is still compressed, decompress it
bodyBytes, ok = transform.Inflate(bodyBytes)
if !ok {
return nil, "", false
}
}
output.PrintfFrameworkTrace("HTTP cache hit: %s", uri)
bodyString := string(bodyBytes)
return resp, bodyString, true
}
// Provided an HTTP client and a req, this function triggers the HTTP request and converts
// the response body to a string.
func DoRequest(client *http.Client, req *http.Request) (*http.Response, string, bool) {
resp, err := client.Do(req)
if err != nil {
output.PrintfFrameworkError("HTTP request error: %s", err)
return resp, "", false
}
defer resp.Body.Close()
bodyBytes, _ := io.ReadAll(resp.Body)
return resp, string(bodyBytes), true
}
// Turns `net/http` []*Cookie into a string for adding to the Cookie header.
func CookieString(cookies []*http.Cookie) string {
cookieString := ""
for c, cookie := range cookies {
if c == 0 {
cookieString += cookie.Name + "=" + cookie.Value + ";"
} else {
cookieString += " " + cookie.Name + "=" + cookie.Value + ";"
}
}
return cookieString
}
// converts a map of strings into a single string in application/x-www-urlencoded format (but does not encode the params!)
func CreateRequestParams(params map[string]string) string {
data := ""
for key, element := range params {
if len(data) > 0 {
data += "&"
}
data += (key + "=" + element)
}
return data
}
// CreateRequestParamsEncoded is the encoded version of CreateRequestParams.
func CreateRequestParamsEncoded(params map[string]string) string {
paramsCopy := make(map[string]string)
for k, v := range params {
paramsCopy[k] = url.QueryEscape(v)
}
return CreateRequestParams(paramsCopy)
}
// Provided a map of headers, this function loops through them and sets them in the http request.
func SetRequestHeaders(req *http.Request, headers map[string]string) {
for key, value := range headers {
if key == "Host" {
// host can't be set directly
req.Host = value
} else {
// don't use the Set function because the module might modify key. Set the header directly.
req.Header[key] = []string{value}
}
}
}
// Creates the HTTP client, generates the HTTP request, and sets the default user-agent.
func CreateRequest(verb string, url string, payload string, followRedirect bool) (*http.Client, *http.Request, bool) {
var client *http.Client
if !followRedirect {
client = &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: time.Duration(GlobalCommTimeout) * time.Second,
}).Dial,
TLSClientConfig: (&tls.Config{
InsecureSkipVerify: true,
// We have no control over the SSL versions supported on the remote target. Be permissive for more targets.
MinVersion: tls.VersionSSL30,
}),
},
Timeout: time.Duration(GlobalCommTimeout) * time.Second,
CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
return http.ErrUseLastResponse
},
}
} else {
client = &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: time.Duration(GlobalCommTimeout) * time.Second,
}).Dial,
TLSClientConfig: (&tls.Config{
InsecureSkipVerify: true,
// We have no control over the SSL versions supported on the remote target. Be permissive for more targets.
MinVersion: tls.VersionSSL30,
}),
},
Timeout: time.Duration(GlobalCommTimeout) * time.Second,
}
}
req, err := http.NewRequest(verb, url, strings.NewReader(payload))
if err != nil {
output.PrintfFrameworkError("HTTP request creation error: %s", err)
return nil, nil, false
}
// set headers on the request
req.Header.Set("User-Agent", GlobalUA)
return client, req, true
}
// Generic send HTTP request and receive response.
func HTTPSendAndRecv(verb string, url string, payload string) (*http.Response, string, bool) {
client, req, ok := CreateRequest(verb, url, payload, true)
if !ok {
return nil, "", false
}
return DoRequest(client, req)
}
func HTTPGetCache(url string) (*http.Response, string, bool) {
// first see if we have it cached somewhere
if db.GlobalSQLHandle != nil {
resp, body, ok := cacheLookup(url)
if ok {
return resp, body, true
}
}
client, req, ok := CreateRequest("GET", url, "", true)
if !ok {
return nil, "", false
}
resp, err := client.Do(req)
if err != nil {
output.PrintfFrameworkError("HTTP request error: %s", err)
return resp, "", false
}
defer resp.Body.Close()
bodyBytes, _ := io.ReadAll(resp.Body)
bodyString := string(bodyBytes)
if db.GlobalSQLHandle != nil {
// shove the body back in to be re-read for storage
resp.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
cacheResponse(req, resp)
}
return resp, bodyString, true
}
// Send an HTTP request but do not follow the 302 redirect.
func HTTPSendAndRecvNoRedirect(verb string, url string, payload string) (*http.Response, string, bool) {
client, req, ok := CreateRequest(verb, url, payload, true)
if !ok {
return nil, "", false
}
// ignore the redirect
client.CheckRedirect = func(_ *http.Request, _ []*http.Request) error {
return http.ErrUseLastResponse
}
return DoRequest(client, req)
}
// Send an HTTP request, with the provided parameters in the params map stored in the body.
// Return the response and response body.
//
// Note that this function *will not* attempt to url encode the params.
func HTTPSendAndRecvURLEncoded(verb string, url string, params map[string]string) (*http.Response, string, bool) {
payload := CreateRequestParams(params)
client, req, ok := CreateRequest(verb, url, payload, true)
if !ok {
return nil, "", false
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return DoRequest(client, req)
}
// Send an HTTP request, with the provided parameters in the params map URL encoded in the body.
// Return the response and response body.
//
// Note that this function *will* attempt to url encode the params.
func HTTPSendAndRecvURLEncodedParams(verb string, url string, params map[string]string) (*http.Response, string, bool) {
payload := CreateRequestParamsEncoded(params)
client, req, ok := CreateRequest(verb, url, payload, true)
if !ok {
return nil, "", false
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return DoRequest(client, req)
}
// Send an HTTP request, with the provided parameters in the params map stored in the body, and
// with extra headers specified in the headers map. Return the response and response body.
//
// Note that this function *will not* attempt to url encode the params.
func HTTPSendAndRecvURLEncodedAndHeaders(verb string, url string, params map[string]string,
headers map[string]string,
) (*http.Response, string, bool) {
payload := CreateRequestParams(params)
client, req, ok := CreateRequest(verb, url, payload, true)
if !ok {
return nil, "", false
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
SetRequestHeaders(req, headers)
return DoRequest(client, req)
}
// Send an HTTP request, with the provided parameters in the params map URL encoded in the body, and
// with extra headers specified in the headers map. Return the response and response body.
//
// Note that this function *will* attempt to url encode the params.
func HTTPSendAndRecvURLEncodedParamsAndHeaders(verb string, url string, params map[string]string,
headers map[string]string,
) (*http.Response, string, bool) {
payload := CreateRequestParamsEncoded(params)
client, req, ok := CreateRequest(verb, url, payload, true)
if !ok {
return nil, "", false
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
SetRequestHeaders(req, headers)
return DoRequest(client, req)
}
// Send an HTTP request with extra headers specified in the headers map. Return the response and response body.
func HTTPSendAndRecvWithHeaders(verb string, url string, payload string, headers map[string]string) (*http.Response, string, bool) {
client, req, ok := CreateRequest(verb, url, payload, true)
if !ok {
return nil, "", false
}
SetRequestHeaders(req, headers)
return DoRequest(client, req)
}
// this naming scheme is a little out of control.
func HTTPSendAndRecvWithHeadersNoRedirect(verb string, url string, payload string,
headers map[string]string,
) (*http.Response, string, bool) {
client, req, ok := CreateRequest(verb, url, payload, true)
if !ok {
return nil, "", false
}
// ignore the redirect
client.CheckRedirect = func(_ *http.Request, _ []*http.Request) error {
return http.ErrUseLastResponse
}
SetRequestHeaders(req, headers)
return DoRequest(client, req)
}
func MultipartCreateForm() (*strings.Builder, *multipart.Writer) {
form := &strings.Builder{}
w := multipart.NewWriter(form)
return form, w
}
func MultipartAddField(writer *multipart.Writer, name string, value string) bool {
fw, err := writer.CreateFormField(name)
if err != nil {
return false
}
_, err = io.Copy(fw, strings.NewReader(value))
return err == nil
}
func MultipartAddPart(writer *multipart.Writer, headers map[string]string, body string) bool {
h := make(textproto.MIMEHeader)
for k, v := range headers {
h.Set(k, v)
}
fw, err := writer.CreatePart(h)
if err != nil {
return false
}
_, err = io.Copy(fw, strings.NewReader(body))
return err == nil
}
func MultipartAddFile(writer *multipart.Writer, name, filename, ctype, value string) bool {
// CreateFormFile doesn't expose Content-Type
return MultipartAddPart(writer, map[string]string{
"Content-Disposition": fmt.Sprintf(`form-data; name="%s"; filename="%s"`, name, filename),
"Content-Type": ctype,
}, value)
}
// Provided an HTTP request, find the Set-Cookie headers, and extract
// the value of the specified cookie. Example:.
func GetSetCookieValue(resp *http.Response, name string) (string, bool) {
cookies, ok := resp.Header["Set-Cookie"]
if !ok {
output.PrintError("Missing Set-Cookie header")
return "", false
}
for _, entry := range cookies {
if strings.HasPrefix(entry, name+"=") {
end := len(entry)
index := strings.Index(entry, ";")
if index != -1 {
end = index
}
return entry[len(name+"="):end], true
}
}
return "", false
}