forked from scottdware/go-bigip
-
Notifications
You must be signed in to change notification settings - Fork 36
/
bigip.go
738 lines (658 loc) · 19.1 KB
/
bigip.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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
/*
Original work Copyright © 2015 Scott Ware
Modifications Copyright 2019 F5 Networks Inc
Licensed under the Apache License, Version 2.0 (the "License");
You may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
*/
// Package bigip interacts with F5 BIG-IP systems using the REST API.
package bigip
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"reflect"
"strings"
"time"
)
var defaultConfigOptions = &ConfigOptions{
APICallTimeout: 60 * time.Second,
// Define new configuration options; are these user-override-able at the provider level or does that take more work?
TokenTimeout: 1200 * time.Second,
APICallRetries: 10,
}
type ConfigOptions struct {
APICallTimeout time.Duration
TokenTimeout time.Duration
APICallRetries int
}
type Config struct {
Address string
Port string
Username string
Password string
Token string
CertVerifyDisable bool
TrustedCertificate string
LoginReference string `json:"loginProviderName"`
ConfigOptions *ConfigOptions
}
// BigIP is a container for our session state.
type BigIP struct {
Host string
User string
Password string
Token string // if set, will be used instead of User/Password
Transport *http.Transport
// UserAgent is an optional field that specifies the caller of this request.
UserAgent string
Teem bool
ConfigOptions *ConfigOptions
Transaction string
}
// APIRequest builds our request before sending it to the server.
type APIRequest struct {
Method string
URL string
Body string
ContentType string
}
// Upload contains information about a file upload status
type Upload struct {
RemainingByteCount int64 `json:"remainingByteCount"`
UsedChunks map[string]int `json:"usedChunks"`
TotalByteCount int64 `json:"totalByteCount"`
LocalFilePath string `json:"localFilePath"`
TemporaryFilePath string `json:"temporaryFilePath"`
Generation int `json:"generation"`
LastUpdateMicros int `json:"lastUpdateMicros"`
}
// RequestError contains information about any error we get from a request.
type RequestError struct {
Code int `json:"code,omitempty"`
Message string `json:"message,omitempty"`
ErrorStack []string `json:"errorStack,omitempty"`
}
type BigIPSetting struct {
BetaOptions struct {
PerAppDeploymentAllowed bool `json:"perAppDeploymentAllowed,omitempty"`
} `json:"betaOptions,omitempty"`
}
// Error returns the error message.
func (r *RequestError) Error() error {
if r.Message != "" {
return errors.New(r.Message)
}
return nil
}
// NewSession sets up our connection to the BIG-IP system.
// func NewSession(host, port, user, passwd string, configOptions *ConfigOptions) *BigIP {
func NewSession(bigipConfig *Config) *BigIP {
var urlString string
if !strings.HasPrefix(bigipConfig.Address, "http") {
urlString = fmt.Sprintf("https://%s", bigipConfig.Address)
} else {
urlString = bigipConfig.Address
}
if bigipConfig.Port != "" {
urlString = urlString + ":" + bigipConfig.Port
}
if bigipConfig.ConfigOptions == nil {
bigipConfig.ConfigOptions = defaultConfigOptions
}
return &BigIP{
Host: urlString,
User: bigipConfig.Username,
Password: bigipConfig.Password,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: bigipConfig.CertVerifyDisable,
},
},
ConfigOptions: bigipConfig.ConfigOptions,
}
}
// NewTokenSession sets up our connection to the BIG-IP system, and
// instructs the session to use token authentication instead of Basic
// Auth. This is required when using an external authentication
// provider, such as Radius or Active Directory. loginProviderName is
// probably "tmos" but your environment may vary.
func NewTokenSession(bigipConfig *Config) (b *BigIP, err error) {
type authReq struct {
Username string `json:"username"`
Password string `json:"password"`
LoginProviderName string `json:"loginProviderName"`
}
type authResp struct {
Token struct {
Token string
}
Timeout struct {
Timeout int64
}
}
type timeoutReq struct {
Timeout int64 `json:"timeout"`
}
// type timeoutResp struct {
// Timeout struct {
// Timeout int64
// }
// }
auth := authReq{
bigipConfig.Username,
bigipConfig.Password,
bigipConfig.LoginReference,
}
marshalJSONauth, err := json.Marshal(auth)
if err != nil {
return
}
req := &APIRequest{
Method: "post",
URL: "mgmt/shared/authn/login",
Body: string(marshalJSONauth),
ContentType: "application/json",
}
b = NewSession(bigipConfig)
if !bigipConfig.CertVerifyDisable {
rootCAs, _ := x509.SystemCertPool()
if rootCAs == nil {
rootCAs = x509.NewCertPool()
}
certPEM, err := os.ReadFile(bigipConfig.TrustedCertificate)
if err != nil {
return b, fmt.Errorf("provide Valid Trusted certificate path :%+v", err)
// log.Printf("[DEBUG]read cert PEM/crt file error:%+v", err)
}
// TODO: Make sure appMgr sets certificates in bigipInfo
// certs := certPEM)
// Append our certs to the system pool
if ok := rootCAs.AppendCertsFromPEM(certPEM); !ok {
fmt.Println("[DEBUG] No certs appended, using only system certs")
}
b.Transport.TLSClientConfig.RootCAs = rootCAs
}
resp, err := b.APICall(req)
if err != nil {
return
}
if resp == nil {
err = fmt.Errorf("unable to acquire authentication token")
return
}
var aresp authResp
err = json.Unmarshal(resp, &aresp)
if err != nil {
return
}
if aresp.Token.Token == "" {
err = fmt.Errorf("unable to acquire authentication token")
return
}
b.Token = aresp.Token.Token
//Once we have obtained a token, we should actually apply the configured timeout to it
if time.Duration(aresp.Timeout.Timeout)*time.Second != bigipConfig.ConfigOptions.TokenTimeout { // The inital value is the max timespan
timeout := timeoutReq{
int64(bigipConfig.ConfigOptions.TokenTimeout.Seconds()),
}
marshalJSONtimeout, errToken := json.Marshal(timeout)
if errToken != nil {
return b, errToken
}
timeoutReq := &APIRequest{
Method: "patch",
URL: ("mgmt/shared/authz/tokens/" + b.Token),
Body: string(marshalJSONtimeout),
ContentType: "application/json",
}
resp, errToken := b.APICall(timeoutReq)
if errToken != nil {
return b, errToken
}
if resp == nil {
errToken = fmt.Errorf("unable to update token timeout")
return b, errToken
}
var tresp map[string]interface{}
errToken = json.Unmarshal(resp, &tresp)
if errToken != nil {
return b, errToken
}
if time.Duration(int64(tresp["timeout"].(float64)))*time.Second != bigipConfig.ConfigOptions.TokenTimeout {
err = fmt.Errorf("failed to update token lifespan")
return
}
}
return
}
// APICall is used to Validate BIG-IP with SelfIPs list
func (client *BigIP) ValidateConnection() error {
t, err := client.SelfIPs()
if err != nil {
return err
}
if t == nil {
return nil
}
return nil
}
// APICall is used to query the BIG-IP web API.
func (b *BigIP) APICall(options *APIRequest) ([]byte, error) {
var req *http.Request
var format string
if strings.Contains(options.URL, "mgmt/") {
format = "%s/%s"
} else {
format = "%s/mgmt/tm/%s"
}
urlString := fmt.Sprintf(format, b.Host, options.URL)
maxRetries := b.ConfigOptions.APICallRetries
for i := 0; i < maxRetries; i++ {
body := bytes.NewReader([]byte(options.Body))
req, _ = http.NewRequest(strings.ToUpper(options.Method), urlString, body)
b.Transport.Proxy = func(reqNew *http.Request) (*url.URL, error) {
return http.ProxyFromEnvironment(reqNew)
}
client := &http.Client{
Transport: b.Transport,
Timeout: b.ConfigOptions.APICallTimeout,
}
if b.Token != "" {
req.Header.Set("X-F5-Auth-Token", b.Token)
} else if options.URL != "mgmt/shared/authn/login" {
req.SetBasicAuth(b.User, b.Password)
}
if len(b.Transaction) > 0 {
req.Header.Set("X-F5-REST-Coordination-Id", b.Transaction)
}
if len(options.ContentType) > 0 {
req.Header.Set("Content-Type", options.ContentType)
}
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
data, _ := io.ReadAll(res.Body)
contentType := ""
if ctHeaders, ok := res.Header["Content-Type"]; ok && len(ctHeaders) > 0 {
contentType = ctHeaders[0]
}
if res.StatusCode >= 400 {
if strings.Contains(contentType, "application/json") {
var reqError RequestError
err = json.Unmarshal(data, &reqError)
if err != nil {
return nil, err
}
// With how some of the requests come back from AS3, we sometimes have a nested error, so check the entire message for the "active asynchronous task" error
if res.StatusCode == 503 || reqError.Code == 503 || strings.Contains(strings.ToLower(reqError.Message), strings.ToLower("there is an active asynchronous task executing")) {
time.Sleep(10 * time.Second)
continue
}
return data, b.checkError(data)
} else {
return data, fmt.Errorf("HTTP %d :: %s", res.StatusCode, string(data[:]))
}
//return data, errors.New(fmt.Sprintf("HTTP %d :: %s", res.StatusCode, string(data[:])))
}
return data, nil
}
return nil, fmt.Errorf("service unavailable after %d attempts", maxRetries)
}
func (b *BigIP) iControlPath(parts []string) string {
var buffer bytes.Buffer
for i, p := range parts {
buffer.WriteString(strings.Replace(p, "/", "~", -1))
if i < len(parts)-1 {
buffer.WriteString("/")
}
}
return buffer.String()
}
// Generic delete
func (b *BigIP) delete(path ...string) error {
req := &APIRequest{
Method: "delete",
URL: b.iControlPath(path),
}
_, callErr := b.APICall(req)
return callErr
}
// Generic delete
func (b *BigIP) deleteReq(path ...string) ([]byte, error) {
req := &APIRequest{
Method: "delete",
URL: b.iControlPath(path),
}
resp, callErr := b.APICall(req)
return resp, callErr
}
func (b *BigIP) deleteReqBody(body interface{}, path ...string) ([]byte, error) {
marshalJSON, err := jsonMarshal(body)
if err != nil {
return nil, err
}
req := &APIRequest{
Method: "delete",
URL: b.iControlPath(path),
Body: strings.TrimRight(string(marshalJSON), "\n"),
ContentType: "application/json",
}
resp, callErr := b.APICall(req)
return resp, callErr
}
func (b *BigIP) post(body interface{}, path ...string) error {
marshalJSON, err := jsonMarshal(body)
if err != nil {
return err
}
req := &APIRequest{
Method: "post",
URL: b.iControlPath(path),
Body: strings.TrimRight(string(marshalJSON), "\n"),
ContentType: "application/json",
}
_, callErr := b.APICall(req)
return callErr
}
func (b *BigIP) postReq(body interface{}, path ...string) ([]byte, error) {
marshalJSON, err := jsonMarshal(body)
if err != nil {
return nil, err
}
req := &APIRequest{
Method: "post",
URL: b.iControlPath(path),
Body: strings.TrimRight(string(marshalJSON), "\n"),
ContentType: "application/json",
}
resp, callErr := b.APICall(req)
return resp, callErr
}
func (b *BigIP) postAS3Req(body interface{}, path ...string) ([]byte, error) {
req := &APIRequest{
Method: "post",
URL: b.iControlPath(path),
Body: body.(string),
ContentType: "application/json",
}
resp, callErr := b.APICall(req)
return resp, callErr
}
func (b *BigIP) put(body interface{}, path ...string) error {
marshalJSON, err := jsonMarshal(body)
if err != nil {
return err
}
req := &APIRequest{
Method: "put",
URL: b.iControlPath(path),
Body: strings.TrimRight(string(marshalJSON), "\n"),
ContentType: "application/json",
}
_, callErr := b.APICall(req)
return callErr
}
func (b *BigIP) putReq(body interface{}, path ...string) ([]byte, error) {
marshalJSON, err := jsonMarshal(body)
if err != nil {
return nil, err
}
req := &APIRequest{
Method: "put",
URL: b.iControlPath(path),
Body: strings.TrimRight(string(marshalJSON), "\n"),
ContentType: "application/json",
}
resp, callErr := b.APICall(req)
return resp, callErr
}
func (b *BigIP) patch(body interface{}, path ...string) error {
marshalJSON, err := jsonMarshal(body)
if err != nil {
return err
}
req := &APIRequest{
Method: "patch",
URL: b.iControlPath(path),
Body: string(marshalJSON),
ContentType: "application/json",
}
_, callErr := b.APICall(req)
return callErr
}
func (b *BigIP) fastPatch(body interface{}, path ...string) ([]byte, error) {
marshalJSON, err := jsonMarshal(body)
if err != nil {
return nil, err
}
req := &APIRequest{
Method: "patch",
URL: b.iControlPath(path),
Body: string(marshalJSON),
ContentType: "application/json",
}
resp, callErr := b.APICall(req)
return resp, callErr
}
// Upload a file read from a Reader
func (b *BigIP) Upload(r io.Reader, size int64, path ...string) (*Upload, error) {
options := &APIRequest{
Method: "post",
URL: b.iControlPath(path),
ContentType: "application/octet-stream",
}
var format string
if strings.Contains(options.URL, "mgmt/") {
format = "%s/%s"
} else {
format = "%s/mgmt/%s"
}
urlString := fmt.Sprintf(format, b.Host, options.URL)
chunkSize := 512 * 1024
var start, end int64
for {
// Read next chunk
chunk := make([]byte, chunkSize)
n, err := r.Read(chunk)
if err != nil {
return nil, err
}
end = start + int64(n)
// Resize buffer size to number of bytes read
if n < chunkSize {
chunk = chunk[:n]
}
body := bytes.NewReader(chunk)
req, _ := http.NewRequest(strings.ToUpper(options.Method), urlString, body)
if b.Token != "" {
req.Header.Set("X-F5-Auth-Token", b.Token)
} else {
req.SetBasicAuth(b.User, b.Password)
}
req.Header.Add("Content-Type", options.ContentType)
req.Header.Add("Content-Range", fmt.Sprintf("%d-%d/%d", start, end-1, size))
b.Transport.Proxy = func(reqNew *http.Request) (*url.URL, error) {
return http.ProxyFromEnvironment(reqNew)
}
client := &http.Client{
Transport: b.Transport,
Timeout: b.ConfigOptions.APICallTimeout,
}
// Try to upload chunk
res, err := client.Do(req)
if err != nil {
return nil, err
}
data, _ := io.ReadAll(res.Body)
if res.StatusCode >= 400 {
if res.Header.Get("Content-Type") == "application/json" {
return nil, b.checkError(data)
}
return nil, fmt.Errorf("HTTP %d :: %s", res.StatusCode, string(data[:]))
}
defer res.Body.Close()
var upload Upload
err = json.Unmarshal(data, &upload)
if err != nil {
return nil, err
}
start = end
if start >= size {
// Final chunk was uploaded
return &upload, err
}
}
}
func (b *BigIP) getSetting(path ...string) (error, []byte) {
req := &APIRequest{
Method: "get",
URL: b.iControlPath(path),
ContentType: "application/json",
}
resp, err := b.APICall(req)
return err, resp
// if err != nil {
// var reqError RequestError
// json.Unmarshal(resp, &reqError)
// if reqError.Code == 404 {
// return err, nil
// }
// return err, nil
// }
// var setting BigIPSetting
// err = json.Unmarshal(resp, &setting)
// if err != nil {
// return err, nil
// }
// return nil, &setting
}
// Get a urlString and populate an entity. If the entity does not exist (404) then the
// passed entity will be untouched and false will be returned as the second parameter.
// You can use this to distinguish between a missing entity or an actual error.
func (b *BigIP) getForEntity(e interface{}, path ...string) (error, bool) {
req := &APIRequest{
Method: "get",
URL: b.iControlPath(path),
ContentType: "application/json",
}
resp, err := b.APICall(req)
if err != nil {
var reqError RequestError
json.Unmarshal(resp, &reqError)
if reqError.Code == 404 {
return err, false
}
return err, false
}
err = json.Unmarshal(resp, e)
if err != nil {
return err, false
}
return nil, true
}
func (b *BigIP) getForEntityNew(e interface{}, path ...string) (error, bool) {
req := &APIRequest{
Method: "get",
URL: b.iControlPath(path),
ContentType: "application/json",
}
resp, err := b.APICall(req)
if err != nil {
var reqError RequestError
json.Unmarshal(resp, &reqError)
return err, false
}
err = json.Unmarshal(resp, e)
if err != nil {
return err, false
}
return nil, true
}
// checkError handles any errors we get from our API requests. It returns either the
// message of the error, if any, or nil.
func (b *BigIP) checkError(resp []byte) error {
if len(resp) == 0 {
return nil
}
var reqError RequestError
err := json.Unmarshal(resp, &reqError)
if err != nil {
return errors.New(fmt.Sprintf("%s\n%s", err.Error(), string(resp[:])))
}
err = reqError.Error()
if err != nil {
return err
}
return nil
}
// jsonMarshal specifies an encoder with 'SetEscapeHTML' set to 'false' so that <, >, and & are not escaped. https://golang.org/pkg/encoding/json/#Marshal
// https://stackoverflow.com/questions/28595664/how-to-stop-json-marshal-from-escaping-and
func jsonMarshal(t interface{}) ([]byte, error) {
buffer := &bytes.Buffer{}
encoder := json.NewEncoder(buffer)
encoder.SetEscapeHTML(false)
err := encoder.Encode(t)
return buffer.Bytes(), err
}
// Helper to copy between transfer objects and model objects to hide the myriad of boolean representations
// in the iControlREST api. DTO fields can be tagged with bool:"yes|enabled|true" to set what true and false
// marshal to.
func marshal(to, from interface{}) error {
toVal := reflect.ValueOf(to).Elem()
fromVal := reflect.ValueOf(from).Elem()
toType := toVal.Type()
for i := 0; i < toVal.NumField(); i++ {
toField := toVal.Field(i)
toFieldType := toType.Field(i)
fromField := fromVal.FieldByName(toFieldType.Name)
if fromField.Interface() != nil && fromField.Kind() == toField.Kind() {
toField.Set(fromField)
} else if toField.Kind() == reflect.Bool && fromField.Kind() == reflect.String {
switch fromField.Interface() {
case "yes", "enabled", "true":
toField.SetBool(true)
break
case "no", "disabled", "false", "":
toField.SetBool(false)
break
default:
return fmt.Errorf("Unknown boolean conversion for %s: %s", toFieldType.Name, fromField.Interface())
}
} else if fromField.Kind() == reflect.Bool && toField.Kind() == reflect.String {
tag := toFieldType.Tag.Get("bool")
switch tag {
case "yes":
toField.SetString(toBoolString(fromField.Interface().(bool), "yes", "no"))
break
case "enabled":
toField.SetString(toBoolString(fromField.Interface().(bool), "enabled", "disabled"))
break
case "true":
toField.SetString(toBoolString(fromField.Interface().(bool), "true", "false"))
break
}
} else {
return fmt.Errorf("Unknown type conversion %s -> %s", fromField.Kind(), toField.Kind())
}
}
return nil
}
func toBoolString(b bool, trueStr, falseStr string) string {
if b {
return trueStr
}
return falseStr
}