/
web.go
256 lines (222 loc) · 5.89 KB
/
web.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
package fortigate
import (
"crypto/tls"
"encoding/json"
"fmt"
"net/http"
"net/http/cookiejar"
"net/url"
"strings"
"gopkg.in/jmcvetta/napping.v3"
)
const (
CsrfToken = "ccsrftoken"
CsrfTokenHeader = "X-Csrftoken"
)
var apiVersion string
type WebClient struct {
URL string
User string
Password string
ApiKey string
Log bool
napping *napping.Session
}
type Result struct {
HTTPMethod string `json:"http_method,omitempty"`
Revision string `json:"revision,omitempty"`
Status string `json:"status,omitempty"`
HTTPStatus int `json:"http_status,omitempty"`
Vdom string `json:"vdom,omitempty"`
Path string `json:"path,omitempty"`
Name string `json:"name,omitempty"`
Serial string `json:"serial,omitempty"`
Version string `json:"version,omitempty"`
Build int `json:"build,omitempty"`
Action string `json:"action,omitempty"`
}
func NewWebClient(clientConfig WebClient) (c *WebClient, err error) {
if clientConfig.URL == "" {
return nil, fmt.Errorf("URL is required")
}
transport := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: transport}
session := &napping.Session{
Client: client,
Log: clientConfig.Log,
}
c = &WebClient{
URL: strings.TrimRight(clientConfig.URL, "/"),
User: clientConfig.User,
Password: clientConfig.Password,
ApiKey: clientConfig.ApiKey,
napping: session,
}
if clientConfig.ApiKey != "" {
c.napping.Header = &http.Header{
"Authorization": []string{"Bearer " + clientConfig.ApiKey},
}
} else if clientConfig.User != "" && clientConfig.Password != "" {
err = c.authenticate()
if err != nil {
return
}
} else {
return nil, fmt.Errorf("either an API key or a user/password is required")
}
var results Result
_, err = c.do(http.MethodGet, "firewall/address/all", nil, nil, &results)
if err != nil {
err = fmt.Errorf("connection established, but failed to get API version: %s", err.Error())
return
}
apiVersion = results.Version
if apiVersion == "" {
err = fmt.Errorf("connection established, but failed to get API version: version is empty")
return
}
return
}
func (c *WebClient) authenticate() error {
jar, err := cookiejar.New(&cookiejar.Options{})
if err != nil {
return fmt.Errorf("could not create cookie jar for fortigate web client: %s", err.Error())
}
c.napping.Client.Jar = jar
resp, err := c.napping.Client.PostForm(c.URL+"/logincheck", url.Values{"username": {c.User}, "secretkey": {c.Password}})
if err != nil {
return fmt.Errorf("could not log in user '%s' at '%s': %s", c.User, c.URL, err.Error())
}
for _, cookie := range resp.Cookies() {
if cookie.Name == CsrfToken {
if cookie.Value == "0%260" {
return fmt.Errorf("could not log in as user '%s' at '%s'", c.User, c.URL)
} else {
c.napping.Header = &http.Header{CsrfTokenHeader: []string{cookie.Value}}
}
}
}
return nil
}
func (c *WebClient) do(method string, path string, p *url.Values, payload interface{}, result2 interface{}) (resp *napping.Response, err error) {
var result interface{}
var errMsg interface{}
path = c.URL + "/api/v2/cmdb/" + path
switch method {
case http.MethodGet:
result = result2
resp, err = c.napping.Get(path, p, result, errMsg)
case http.MethodDelete:
resp, err = c.napping.Delete(path, p, result, errMsg)
case http.MethodPost:
resp, err = c.napping.Post(path, payload, result, errMsg)
case http.MethodPut:
resp, err = c.napping.Put(path, payload, result, errMsg)
}
if err != nil {
return
}
if resp.HttpResponse().StatusCode == 401 {
err = c.authenticate()
if err != nil {
return
}
switch method {
case http.MethodGet:
result = result2
resp, err = c.napping.Get(path, p, result, errMsg)
case http.MethodDelete:
resp, err = c.napping.Delete(path, p, result, errMsg)
case http.MethodPost:
resp, err = c.napping.Post(path, payload, result, errMsg)
case http.MethodPut:
resp, err = c.napping.Put(path, payload, result, errMsg)
}
if err != nil {
return
}
if resp.HttpResponse().StatusCode == 401 {
return nil, fmt.Errorf("authentication failed")
}
}
if resp.HttpResponse().StatusCode == 200 {
if rres, ok := result.(*Result); ok {
if rres.HTTPStatus != 200 {
if rerrmsg, ok := errMsg.(*Result); ok {
if rerrmsg.HTTPStatus == 404 {
err = fmt.Errorf("not found")
} else if rerrmsg.HTTPStatus == 401 {
err = fmt.Errorf("unauthorized")
} else {
err = fmt.Errorf(rerrmsg.Status)
}
}
}
}
} else if resp.HttpResponse().StatusCode == 404 {
err = fmt.Errorf("not found")
} else {
err = fmt.Errorf("http status %s", resp.HttpResponse().Status)
}
return
}
// Special cases
func (v *VIP) UnmarshalJSON(data []byte) error {
switch apiVersion {
case "v5.4.6":
type VIPAlias VIP
temp := struct {
Monitor string `json:"monitor"`
*VIPAlias
}{
VIPAlias: (*VIPAlias)(v),
}
if err := json.Unmarshal(data, &temp); err != nil {
return err
}
v.Monitor = []VIPMonitor{}
for _, m := range strings.Split(temp.Monitor, " ") {
v.Monitor = append(v.Monitor, VIPMonitor{Name: strings.Replace(m, `"`, "", -1)})
}
return nil
default:
type VIPAlias VIP
temp := struct {
*VIPAlias
}{
VIPAlias: (*VIPAlias)(v),
}
if err := json.Unmarshal(data, &temp); err != nil {
return err
}
return nil
}
}
func (v *VIP) MarshalJSON() ([]byte, error) {
switch apiVersion {
case "v5.6.3", "v5.6.4":
type VIPAlias VIP
return json.Marshal(&struct {
*VIPAlias
}{
VIPAlias: (*VIPAlias)(v),
})
case "v5.4.6":
type VIPAlias VIP
var ms []string
for _, m := range v.Monitor {
ms = append(ms, `"`+m.Name+`"`)
}
return json.Marshal(&struct {
*VIPAlias
Monitor string `json:"monitor"`
}{
VIPAlias: (*VIPAlias)(v),
Monitor: strings.Join(ms, " "),
})
default:
return []byte{}, fmt.Errorf("unknown or undefined api version %s", apiVersion)
}
}