GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — codexa-scanner/http_scope.go at main · hidecard/codexa-scanner

Expand file tree

/

http_scope.go

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
520 lines (487 loc) · 16 KB
/

http_scope.go

Copy path

File metadata and controls

520 lines (487 loc) · 16 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
package main
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"net/netip"
"net/url"
"sort"
"strconv"
"strings"
"sync"
"time"
)
const (
maxHTTPRedirects = 5
httpDNSLookupTimeout = 5 * time.Second
defaultHTTPUserAgent = "Codexa-Scanner/1.1 (passive authorized security assessment)"
defaultHTTPDialTimeout = 5 * time.Second
defaultHTTPTimeout = 10 * time.Second
)
type HTTPRequestProfile struct {
UserAgent string `json:"userAgent"`
TimeoutSeconds int `json:"timeoutSeconds"`
CustomHeaders map[string]string `json:"customHeaders,omitempty"`
ProxyURL string `json:"proxyUrl,omitempty"`
}
// sensitiveHeaderNames lists request header names whose values must never be
// stored or persisted in the clear. Values are redacted at profile-resolution
// time so downstream code (analyzeURL, history, exports) never sees secrets.
var sensitiveHeaderNames = map[string]bool{
"authorization": true,
"cookie": true,
"cookie2": true,
"x-api-key": true,
"apikey": true,
"x-csrf-token": true,
"csrf-token": true,
"x-xsrf-token": true,
"proxy-authorization": true,
}
func headerNameLooksValid(name string) bool {
if name == "" {
return false
}
for _, r := range name {
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '-' {
continue
}
return false
}
return true
}
func resolveHTTPRequestProfile(profile HTTPRequestProfile) HTTPRequestProfile {
ua := strings.TrimSpace(profile.UserAgent)
if ua == "" {
ua = defaultHTTPUserAgent
}
// keep User-Agent bounded/safe for headers
ua = strings.Map(func(r rune) rune {
if r == '\r' || r == '\n' {
return -1
}
return r
}, ua)
if len(ua) > 200 {
ua = ua[:200]
}
t := profile.TimeoutSeconds
switch t {
case 0:
t = 10
case 5, 10, 20, 30:
default:
if t < 3 {
t = 3
}
if t > 60 {
t = 60
}
}
headers := make(map[string]string, len(profile.CustomHeaders))
for name, value := range profile.CustomHeaders {
lower := strings.ToLower(strings.TrimSpace(name))
if !headerNameLooksValid(lower) {
continue
}
// Reject hop-by-hop / unsafe headers that the transport controls itself.
switch lower {
case "host", "content-length", "transfer-encoding", "connection",
"keep-alive", "proxy-authenticate", "proxy-authorization", "te",
"trailer", "upgrade":
continue
}
v := strings.Map(func(r rune) rune {
if r == '\r' || r == '\n' {
return -1
}
return r
}, value)
if len(v) > 512 {
v = v[:512]
}
if sensitiveHeaderNames[lower] {
headers[lower] = redactHeaderPreview(v)
} else {
headers[lower] = v
}
}
// Resolve and validate proxy URL (opt-in only; must be explicit non-empty string)
proxyURL := strings.TrimSpace(profile.ProxyURL)
if proxyURL != "" {
parsed, err := url.Parse(proxyURL)
if err != nil || parsed.Scheme == "" || parsed.Host == "" {
proxyURL = "" // invalid proxy URL -> ignore (treat as no proxy)
} else {
scheme := strings.ToLower(parsed.Scheme)
if scheme != "http" && scheme != "https" && scheme != "socks5" && scheme != "socks5h" {
proxyURL = "" // unsupported scheme -> ignore
}
// Disallow embedded credentials in proxy URL; use header if needed.
if parsed.User != nil {
proxyURL = ""
}
}
}
return HTTPRequestProfile{UserAgent: ua, TimeoutSeconds: t, CustomHeaders: headers, ProxyURL: proxyURL}
}
// redactHeaderPreview shows a short prefix/suffix with the middle masked so
// authenticated session context remains visible enough to confirm a header was
// sent while never persisting a usable credential.
func redactHeaderPreview(value string) string {
if len(value) <= 8 {
return "[REDACTED]"
}
return value[:4] + "****" + value[len(value)-4:]
}
type redirectTraceTransport struct {
base http.RoundTripper
mu sync.Mutex
hops []RedirectHop
}
func (t *redirectTraceTransport) RoundTrip(req *http.Request) (*http.Response, error) {
resp, err := t.base.RoundTrip(req)
if err != nil || resp == nil || req.URL == nil || resp.StatusCode < http.StatusMultipleChoices || resp.StatusCode >= http.StatusBadRequest {
return resp, err
}
location, locationErr := resp.Location()
if locationErr != nil || location == nil {
return resp, err
}
target := req.URL.ResolveReference(location)
t.mu.Lock()
t.hops = append(t.hops, RedirectHop{From: req.URL.String(), To: target.String(), StatusCode: resp.StatusCode})
t.mu.Unlock()
return resp, err
}
func (t *redirectTraceTransport) CloseIdleConnections() {
if closer, ok := t.base.(interface{ CloseIdleConnections() }); ok {
closer.CloseIdleConnections()
}
}
func snapshotRedirectHops(client *http.Client) []RedirectHop {
if client == nil {
return []RedirectHop{}
}
trace, ok := client.Transport.(*redirectTraceTransport)
if !ok || trace == nil {
return []RedirectHop{}
}
trace.mu.Lock()
defer trace.mu.Unlock()
return append([]RedirectHop{}, trace.hops...)
}
var (
errHTTPRedirectOutOfScope = errors.New("redirect is outside the selected target scope")
errHTTPRedirectDowngrade = errors.New("HTTPS-to-HTTP redirects are not allowed")
errHTTPTooManyRedirects = errors.New("stopped after five redirects")
errHTTPPrivateAddress = errors.New("target resolves to a private or loopback address")
errHTTPSpecialAddress = errors.New("target resolves to a special-use or non-routable address")
errHTTPDNSResolution = errors.New("target DNS resolution failed")
errHTTPNoDNSAnswers = errors.New("target DNS lookup returned no addresses")
)
var (
httpGlobalIPv6Prefix = netip.MustParsePrefix("2000::/3")
httpSpecialUsePrefixes = []netip.Prefix{
netip.MustParsePrefix("0.0.0.0/8"),
netip.MustParsePrefix("100.64.0.0/10"),
netip.MustParsePrefix("192.0.0.0/24"),
netip.MustParsePrefix("192.0.2.0/24"),
netip.MustParsePrefix("192.88.99.0/24"),
netip.MustParsePrefix("198.18.0.0/15"),
netip.MustParsePrefix("198.51.100.0/24"),
netip.MustParsePrefix("203.0.113.0/24"),
netip.MustParsePrefix("224.0.0.0/4"),
netip.MustParsePrefix("240.0.0.0/4"),
netip.MustParsePrefix("64:ff9b::/96"),
netip.MustParsePrefix("64:ff9b:1::/48"),
netip.MustParsePrefix("2001::/23"),
netip.MustParsePrefix("2001:db8::/32"),
netip.MustParsePrefix("2002::/16"),
netip.MustParsePrefix("3fff::/20"),
}
)
type httpIPLookup interface {
LookupNetIP(context.Context, string, string) ([]netip.Addr, error)
}
type pinnedHTTPResolver struct {
lookup httpIPLookup
allowPrivate bool
mu sync.Mutex
addresses map[string]netip.Addr
}
func newPinnedHTTPResolver(lookup httpIPLookup, allowPrivate bool) *pinnedHTTPResolver {
return &pinnedHTTPResolver{
lookup: lookup,
allowPrivate: allowPrivate,
addresses: make(map[string]netip.Addr),
}
}
func (r *pinnedHTTPResolver) resolve(ctx context.Context, host string) (netip.Addr, error) {
canonical, err := normalizeHTTPHostname(host)
if err != nil {
return netip.Addr{}, fmt.Errorf("%w: %v", errHTTPSpecialAddress, err)
}
if ip, err := netip.ParseAddr(canonical); err == nil {
return validateHTTPAddress(ip, r.allowPrivate)
}
r.mu.Lock()
defer r.mu.Unlock()
if ip, ok := r.addresses[canonical]; ok {
return ip, nil
}
lookupCtx, cancel := context.WithTimeout(ctx, httpDNSLookupTimeout)
defer cancel()
queryHost := canonical
if !strings.HasSuffix(queryHost, ".") {
queryHost += "."
}
answers, err := r.lookup.LookupNetIP(lookupCtx, "ip", queryHost)
if err != nil {
return netip.Addr{}, fmt.Errorf("%w: %v", errHTTPDNSResolution, err)
}
selected, err := selectPinnedHTTPAddress(answers, r.allowPrivate)
if err != nil {
return netip.Addr{}, err
}
r.addresses[canonical] = selected
return selected, nil
}
func selectPinnedHTTPAddress(answers []netip.Addr, allowPrivate bool) (netip.Addr, error) {
if len(answers) == 0 {
return netip.Addr{}, errHTTPNoDNSAnswers
}
valid := make([]netip.Addr, 0, len(answers))
for _, answer := range answers {
ip, err := validateHTTPAddress(answer, allowPrivate)
if err != nil {
// Reject mixed public/private answer sets instead of selecting only the
// convenient answer; the complete DNS response is part of the policy check.
return netip.Addr{}, err
}
valid = append(valid, ip)
}
sort.Slice(valid, func(i, j int) bool {
left4, right4 := valid[i].Is4(), valid[j].Is4()
if left4 != right4 {
return left4
}
return valid[i].Compare(valid[j]) < 0
})
return valid[0], nil
}
func validateHTTPAddress(ip netip.Addr, allowPrivate bool) (netip.Addr, error) {
if !ip.IsValid() {
return netip.Addr{}, errHTTPSpecialAddress
}
if ip.Zone() != "" {
return netip.Addr{}, errHTTPSpecialAddress
}
ip = ip.Unmap()
if ip.IsUnspecified() || ip.IsMulticast() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() {
return netip.Addr{}, errHTTPSpecialAddress
}
for _, prefix := range httpSpecialUsePrefixes {
if prefix.Contains(ip) {
return netip.Addr{}, errHTTPSpecialAddress
}
}
if ip.IsPrivate() || ip.IsLoopback() {
if allowPrivate {
return ip, nil
}
return netip.Addr{}, errHTTPPrivateAddress
}
if !ip.IsGlobalUnicast() {
return netip.Addr{}, errHTTPSpecialAddress
}
if ip.Is6() && !httpGlobalIPv6Prefix.Contains(ip) {
return netip.Addr{}, errHTTPSpecialAddress
}
return ip, nil
}
func normalizeHTTPHostname(host string) (string, error) {
normalized, err := normalizePortScanTarget(host)
if err != nil {
return "", err
}
if ip, err := netip.ParseAddr(normalized); err == nil {
return ip.String(), nil
}
return strings.TrimSuffix(strings.ToLower(normalized), "."), nil
}
func analysisURLForDisplay(target string) string {
inputURL := strings.TrimSpace(target)
if !strings.Contains(inputURL, "://") {
inputURL = "https://" + inputURL
}
return inputURL
}
func parseHTTPAnalysisURL(target string) (string, *url.URL, string, error) {
inputURL := analysisURLForDisplay(target)
parsed, err := url.Parse(inputURL)
if err != nil || parsed.Hostname() == "" || parsed.User != nil {
return inputURL, nil, "", errors.New("enter a valid http:// or https:// URL without embedded credentials")
}
parsed.Scheme = strings.ToLower(parsed.Scheme)
if parsed.Scheme != "http" && parsed.Scheme != "https" {
return inputURL, nil, "", errors.New("enter a valid http:// or https:// URL without embedded credentials")
}
host, err := normalizeHTTPHostname(parsed.Hostname())
if err != nil {
return inputURL, nil, "", errors.New("enter a valid http:// or https:// URL with a valid IP address or hostname")
}
if _, err := effectiveHTTPPort(parsed); err != nil {
return inputURL, nil, "", errors.New("URL port must be between 1 and 65535")
}
return inputURL, parsed, host, nil
}
func effectiveHTTPPort(parsed *url.URL) (string, error) {
port := parsed.Port()
if port == "" {
if strings.EqualFold(parsed.Scheme, "http") {
return "80", nil
}
if strings.EqualFold(parsed.Scheme, "https") {
return "443", nil
}
return "", errHTTPRedirectOutOfScope
}
value, err := strconv.Atoi(port)
if err != nil || value < 1 || value > 65535 {
return "", fmt.Errorf("invalid port")
}
return strconv.Itoa(value), nil
}
type httpTargetScope struct {
host string
ports map[string]struct{}
}
func newHTTPTargetScope(parsed *url.URL, host string) (httpTargetScope, error) {
port, err := effectiveHTTPPort(parsed)
if err != nil {
return httpTargetScope{}, err
}
ports := map[string]struct{}{port: {}}
if parsed.Scheme == "http" && port == "80" {
ports["443"] = struct{}{}
}
if parsed.Scheme == "https" && port == "443" {
ports["80"] = struct{}{}
}
return httpTargetScope{host: host, ports: ports}, nil
}
func (s httpTargetScope) allows(parsed *url.URL) bool {
if parsed == nil || parsed.User != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") {
return false
}
host, err := normalizeHTTPHostname(parsed.Hostname())
if err != nil || host != s.host {
return false
}
port, err := effectiveHTTPPort(parsed)
if err != nil {
return false
}
_, ok := s.ports[port]
return ok
}
func validateHTTPRedirect(request *http.Request, via []*http.Request, scope httpTargetScope) error {
if len(via) > maxHTTPRedirects {
return errHTTPTooManyRedirects
}
if request == nil || request.URL == nil || len(via) == 0 || request.URL.User != nil || !scope.allows(request.URL) {
return errHTTPRedirectOutOfScope
}
if strings.EqualFold(via[0].URL.Scheme, "https") && strings.EqualFold(request.URL.Scheme, "http") {
return errHTTPRedirectDowngrade
}
return nil
}
func newScopedHTTPClient(target string, allowPrivate bool, lookup httpIPLookup) (*http.Client, error) {
return newScopedHTTPClientWithProfile(target, allowPrivate, lookup, HTTPRequestProfile{})
}
func newScopedHTTPClientWithProfile(target string, allowPrivate bool, lookup httpIPLookup, profile HTTPRequestProfile) (*http.Client, error) {
_, parsed, host, err := parseHTTPAnalysisURL(target)
if err != nil {
return nil, err
}
scope, err := newHTTPTargetScope(parsed, host)
if err != nil {
return nil, err
}
prof := resolveHTTPRequestProfile(profile)
dialTimeout := defaultHTTPDialTimeout
if time.Duration(prof.TimeoutSeconds)*time.Second < dialTimeout {
dialTimeout = time.Duration(prof.TimeoutSeconds) * time.Second
}
pinned := newPinnedHTTPResolver(lookup, allowPrivate)
dialer := &net.Dialer{Timeout: dialTimeout, KeepAlive: 30 * time.Second}
transport := &http.Transport{
// An ambient proxy could resolve the hostname elsewhere and bypass our pins.
// Only use explicitly configured proxy from profile (opt-in).
Proxy: func(req *http.Request) (*url.URL, error) {
if prof.ProxyURL == "" {
return nil, nil
}
// Return the pre-validated proxy URL for all requests through this transport.
return url.Parse(prof.ProxyURL)
},
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
requestHost, requestPort, err := net.SplitHostPort(address)
if err != nil {
return nil, fmt.Errorf("%w: invalid destination", errHTTPRedirectOutOfScope)
}
canonicalHost, err := normalizeHTTPHostname(requestHost)
if err != nil || canonicalHost != scope.host {
return nil, fmt.Errorf("%w: host is not in scope", errHTTPRedirectOutOfScope)
}
portNumber, err := strconv.Atoi(requestPort)
if err != nil || portNumber < 1 || portNumber > 65535 {
return nil, fmt.Errorf("%w: invalid port", errHTTPRedirectOutOfScope)
}
requestPort = strconv.Itoa(portNumber)
if _, allowed := scope.ports[requestPort]; !allowed {
return nil, fmt.Errorf("%w: port is not in scope", errHTTPRedirectOutOfScope)
}
ip, err := pinned.resolve(ctx, requestHost)
if err != nil {
return nil, err
}
return dialer.DialContext(ctx, network, net.JoinHostPort(ip.String(), requestPort))
},
}
traceTransport := &redirectTraceTransport{base: transport, hops: []RedirectHop{}}
return &http.Client{
Timeout: time.Duration(prof.TimeoutSeconds) * time.Second,
Transport: traceTransport,
CheckRedirect: func(request *http.Request, via []*http.Request) error {
return validateHTTPRedirect(request, via, scope)
},
}, nil
}
func (p HTTPRequestProfile) resolvedUserAgent() string {
return resolveHTTPRequestProfile(p).UserAgent
}
func httpAnalysisErrorMessage(err error) string {
switch {
case errors.Is(err, errHTTPRedirectOutOfScope):
return "Redirect blocked: destination is outside this URL's hostname and allowed port scope."
case errors.Is(err, errHTTPRedirectDowngrade):
return "Redirect blocked: HTTPS-to-HTTP downgrade is not allowed."
case errors.Is(err, errHTTPTooManyRedirects):
return "Redirect blocked after five hops."
case errors.Is(err, errHTTPPrivateAddress):
return "Target resolves to a private or loopback address. Enable the private/lab option only for an authorized target."
case errors.Is(err, errHTTPSpecialAddress):
return "Target resolves to a link-local, multicast, reserved, or otherwise disallowed special-use address."
case errors.Is(err, errHTTPDNSResolution):
return "Target DNS resolution failed. Verify the hostname and try again."
case errors.Is(err, errHTTPNoDNSAnswers):
return "Target DNS lookup returned no usable addresses."
default:
return "Connection failed, timed out, or TLS certificate verification failed. No insecure TLS bypass was used."
}
}
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.