-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
219 lines (190 loc) · 5.18 KB
/
Copy pathclient.go
File metadata and controls
219 lines (190 loc) · 5.18 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
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
package fortimgr
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"fmt"
"net/http"
"net/http/cookiejar"
"os"
"strings"
"sync"
)
// Client communicates with FortiManager via the FlatUI Web UI API.
type Client struct {
address string
config clientConfig
httpClient *http.Client
cookieJar *cookiejar.Jar
csrfToken string
requestID int64
}
// NewClient creates a new FortiManager client.
// Address is the base URL (e.g. "https://fm.example.com").
// At minimum, WithCredentials must be provided.
//
// HTTP client precedence: WithHTTPClient > WithTransport > default.
// When WithHTTPClient is used, WithTransport, WithTimeout, and WithInsecureTLS
// are ignored — the caller controls the full HTTP stack.
func NewClient(address string, opts ...ClientOption) (*Client, error) {
if address == "" {
return nil, fmt.Errorf("fortimgr: address is required")
}
cfg := clientConfig{
timeout: defaultTimeout,
userAgent: defaultUserAgent,
}
for _, o := range opts {
o.apply(&cfg)
}
if cfg.username == "" || cfg.password == "" {
return nil, fmt.Errorf("fortimgr: credentials are required (use WithCredentials)")
}
if cfg.x509NegativeSerial {
setX509NegativeSerial()
}
address = strings.TrimRight(address, "/")
jar, err := cookiejar.New(nil)
if err != nil {
return nil, fmt.Errorf("fortimgr: create cookie jar: %w", err)
}
var httpClient *http.Client
switch {
case cfg.httpClient != nil:
httpClient = cfg.httpClient
httpClient.Jar = jar
case cfg.transport != nil:
httpClient = &http.Client{
Transport: cfg.transport,
Timeout: cfg.timeout,
Jar: jar,
}
default:
httpClient = &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: cfg.insecureTLS,
},
},
Timeout: cfg.timeout,
Jar: jar,
}
}
return &Client{
address: address,
config: cfg,
httpClient: httpClient,
cookieJar: jar,
}, nil
}
// Login authenticates with FortiManager and obtains a CSRF token.
func (c *Client) Login(ctx context.Context) error {
payload := map[string]any{
"url": "/gui/userauth",
"method": "login",
"params": map[string]any{
"username": c.config.username,
"secretkey": c.config.password,
"logintype": 0,
},
}
body, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("fortimgr: marshal login request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, "POST", c.address+"/cgi-bin/module/flatui_auth", bytes.NewReader(body))
if err != nil {
return fmt.Errorf("fortimgr: create login request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
if c.config.userAgent != "" {
req.Header.Set("User-Agent", c.config.userAgent)
}
resp, err := c.httpClient.Do(req)
if err != nil {
if isCertificateError(err) {
return fmt.Errorf("%w: %v", ErrCertificate, err)
}
return fmt.Errorf("fortimgr: login request: %w", err)
}
defer func() { _ = resp.Body.Close() }()
// Check the actual response headers for the CSRF token, not the cookie jar.
// Using the jar would incorrectly find stale tokens from previous sessions.
for _, cookie := range resp.Cookies() {
if cookie.Name == "HTTP_CSRF_TOKEN" {
c.csrfToken = cookie.Value
return nil
}
}
return ErrAuth
}
// Logout terminates the FortiManager session.
// The CSRF token is always cleared, even if the request fails.
func (c *Client) Logout(ctx context.Context) error {
if c.csrfToken == "" {
return nil
}
defer func() { c.csrfToken = "" }()
payload := map[string]any{
"url": "/gui/userauth",
"method": "logout",
}
body, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("fortimgr: marshal logout request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, "POST", c.address+"/cgi-bin/module/flatui_auth", bytes.NewReader(body))
if err != nil {
return fmt.Errorf("fortimgr: create logout request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-CSRFToken", c.csrfToken)
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("fortimgr: logout request: %w", err)
}
_ = resp.Body.Close()
return nil
}
// Close logs out and releases resources.
func (c *Client) Close() error {
return c.Logout(context.Background())
}
// LoggedIn returns true if the client has an active session.
func (c *Client) LoggedIn() bool {
return c.csrfToken != ""
}
var x509NegativeSerialOnce sync.Once
// setX509NegativeSerial enables Go's x509negativeserial GODEBUG flag.
// Uses sync.Once to safely handle concurrent or repeated calls.
func setX509NegativeSerial() {
x509NegativeSerialOnce.Do(func() {
current := os.Getenv("GODEBUG")
if strings.Contains(current, "x509negativeserial=1") {
return
}
if current == "" {
_ = os.Setenv("GODEBUG", "x509negativeserial=1")
} else {
_ = os.Setenv("GODEBUG", current+",x509negativeserial=1")
}
})
}
// validName checks that an ADOM or package name contains only safe characters.
func validName(name string) bool {
if name == "" {
return false
}
for _, r := range name {
switch {
case r >= 'a' && r <= 'z':
case r >= 'A' && r <= 'Z':
case r >= '0' && r <= '9':
case r == '-' || r == '_' || r == '.':
default:
return false
}
}
return true
}