-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession.go
More file actions
66 lines (54 loc) · 1.68 KB
/
Copy pathsession.go
File metadata and controls
66 lines (54 loc) · 1.68 KB
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
package main
import (
"context"
"fmt"
"io"
"net/http"
"regexp"
)
var gckPattern = regexp.MustCompile(`g_ck\s*=\s*'([a-f0-9]+)'`)
// Session holds the authentication state for a ServiceNow instance.
type Session struct {
Target string
Token string
Cookies []*http.Cookie
}
// Bootstrap creates an unauthenticated session against a ServiceNow instance.
// It fetches /login.do to obtain the g_ck CSRF token and session cookies.
func Bootstrap(ctx context.Context, target string, client *http.Client) (*Session, error) {
url := fmt.Sprintf("https://%s/login.do", target)
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return nil, fmt.Errorf("creating request: %w", err)
}
setHeaders(req)
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("fetching /login.do: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fmt.Errorf("/login.do returned %d", resp.StatusCode)
}
body, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
if err != nil {
return nil, fmt.Errorf("reading response body: %w", err)
}
match := gckPattern.FindSubmatch(body)
if match == nil {
return nil, fmt.Errorf("g_ck token not found in /login.do response (%d bytes)", len(body))
}
return &Session{
Target: target,
Token: string(match[1]),
Cookies: resp.Cookies(),
}, nil
}
func setHeaders(req *http.Request) {
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36")
if vendorHeader != "" {
req.Header.Set("X-Vendor", vendorHeader)
}
}
// vendorHeader is set via -vendor flag for engagement tracking.
var vendorHeader string