-
Notifications
You must be signed in to change notification settings - Fork 193
/
routing.go
1609 lines (1491 loc) · 52.4 KB
/
routing.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
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-
* Copyright (c) 2016-2021, 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 controller
import (
"fmt"
routeapi "github.com/openshift/api/route/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"encoding/json"
"net/url"
"sort"
"strconv"
"strings"
"sync"
cisapiv1 "github.com/F5Networks/k8s-bigip-ctlr/v3/config/apis/cis/v1"
log "github.com/F5Networks/k8s-bigip-ctlr/v3/pkg/vlogger"
)
// prepareVirtualServerRules prepares LTM Policy rules for VirtualServer
func (ctlr *Controller) prepareVirtualServerRules(
vs *cisapiv1.VirtualServer,
rsCfg *ResourceConfig,
) *Rules {
rlMap := make(ruleMap)
wildcards := make(ruleMap)
var redirects []*Rule
appRoot := "/"
if vs.Spec.RewriteAppRoot != "" {
ruleName := formatVirtualServerRuleName(vs.Spec.Host, vs.Spec.HostGroup, "redirectto", vs.Spec.RewriteAppRoot)
rl, err := createRedirectRule(vs.Spec.Host+appRoot, vs.Spec.RewriteAppRoot, ruleName, rsCfg.Virtual.AllowSourceRange)
if nil != err {
log.Errorf("Error configuring redirect rule: %v", err)
return nil
}
redirects = append(redirects, rl)
}
for _, pl := range vs.Spec.Pools {
// Service cannot be empty
if pl.Service == "" {
continue
}
// If not using WAF from policy CR, use Pool Based WAF from VS
wafPolicy := ""
if rsCfg.Virtual.WAF == "" {
wafPolicy = pl.WAF
}
uri := vs.Spec.Host + pl.Path
path := pl.Path
if pl.Path == "/" {
uri = vs.Spec.Host + vs.Spec.RewriteAppRoot
path = vs.Spec.RewriteAppRoot
}
poolBackends := ctlr.GetPoolBackends(&pl)
skipPool := false
if (pl.AlternateBackends != nil && len(pl.AlternateBackends) > 0) || ctlr.haModeType == Ratio {
skipPool = true
}
for _, backend := range poolBackends {
poolName := ctlr.framePoolNameForVs(
vs.ObjectMeta.Namespace,
pl,
vs.Spec.Host,
backend,
)
ruleName := formatVirtualServerRuleName(vs.Spec.Host, vs.Spec.HostGroup, path, poolName)
var err error
rl, err := createRule(uri, poolName, ruleName, rsCfg.Virtual.AllowSourceRange, wafPolicy, skipPool)
if nil != err {
log.Errorf("Error configuring rule: %v", err)
return nil
}
if pl.HostRewrite != "" {
hostRewriteActions, err := getHostRewriteActions(
pl.HostRewrite,
len(rl.Actions),
)
if nil != err {
log.Errorf("Error configuring rule: %v", err)
return nil
}
rl.Actions = append(rl.Actions, hostRewriteActions...)
}
if pl.Rewrite != "" {
rewriteActions, err := getRewriteActions(
path,
pl.Rewrite,
len(rl.Actions),
)
if nil != err {
log.Errorf("Error configuring rule: %v", err)
return nil
}
rl.Actions = append(rl.Actions, rewriteActions...)
}
if pl.Path == "/" {
redirects = append(redirects, rl)
} else if true == strings.HasPrefix(uri, "*.") {
wildcards[uri] = rl
} else {
rlMap[uri] = rl
}
}
}
if vs.Spec.RewriteAppRoot != "" && len(redirects) != 2 {
log.Error("AppRoot path not found for rewriting")
return nil
}
if rlMap[vs.Spec.Host] == nil && len(redirects) == 2 {
rl := &Rule{
Name: formatVirtualServerRuleName(vs.Spec.Host, vs.Spec.HostGroup, "", redirects[1].Actions[0].Pool),
FullURI: vs.Spec.Host,
Actions: redirects[1].Actions,
Conditions: []*condition{
redirects[1].Conditions[0],
},
}
redirects = append(redirects, rl)
}
var wg sync.WaitGroup
wg.Add(2)
sortrules := func(r ruleMap, rls *Rules, ordinal int) {
for _, v := range r {
*rls = append(*rls, v)
}
//sort.Sort(sort.Reverse(*rls))
for _, v := range *rls {
v.Ordinal = ordinal
ordinal++
}
wg.Done()
}
rls := Rules{}
go sortrules(rlMap, &rls, 0)
w := Rules{}
go sortrules(wildcards, &w, len(rlMap))
wg.Wait()
rls = append(rls, w...)
sort.Sort(rls)
rls = append(redirects, rls...)
return &rls
}
// format the rule name for VirtualServer
func formatVirtualServerRuleName(hostname, hostGroup, path, pool string) string {
var rule string
host := hostname
//if wildcard vs
if strings.HasPrefix(host, "*") {
host = strings.Replace(host, "*", "wildcard", 1)
}
if hostGroup != "" {
host = hostGroup
}
if path == "" {
rule = fmt.Sprintf("vs_%s_%s", host, pool)
} else {
// Remove the first slash, then replace any subsequent slashes with '_'
path = strings.TrimPrefix(path, "/")
path = strings.Replace(path, "/", "_", -1)
rule = fmt.Sprintf("vs_%s_%s_%s", host, path, pool)
}
rule = AS3NameFormatter(rule)
return rule
}
// Create LTM policy rules
func createRule(uri, poolName, ruleName string, allowSourceRange []string, wafPolicy string, skipPool bool) (*Rule, error) {
_u := "scheme://" + uri
_u = strings.TrimSuffix(_u, "/")
u, err := url.Parse(_u)
if nil != err {
return nil, err
}
var actions []*action
var conditions []*condition
var cond *condition
if true == strings.HasPrefix(uri, "*.") {
cond = &condition{
EndsWith: true,
Host: true,
HTTPHost: true,
Name: "0",
Index: 0,
Values: []string{strings.TrimPrefix(u.Host, "*")},
}
} else if u.Host != "" {
cond = &condition{
Equals: true,
Host: true,
HTTPHost: true,
Name: "0",
Index: 0,
Values: []string{u.Host},
}
}
if cond != nil {
cond.Request = true
conditions = append(conditions, cond)
}
if 0 != len(u.EscapedPath()) {
conditions = append(conditions, createPathSegmentConditions(u)...)
}
if len(allowSourceRange) > 0 {
cond = &condition{
Tcp: true,
Address: true,
Values: allowSourceRange,
}
conditions = append(conditions, cond)
}
// for a/b enabled resource pool will be skipped
var a action
if !skipPool {
a = action{
Forward: true,
Name: "0",
Pool: poolName,
Request: true,
}
actions = append(actions, &a)
} else if wafPolicy == "" {
// add dummy action
a = action{
Log: true,
Message: "a/b pool",
Name: "0",
Request: true,
}
actions = append(actions, &a)
}
// Add WAF rule
if wafPolicy != "" {
wafAction := &action{
WAF: true,
Policy: wafPolicy,
Request: true,
}
actions = append(actions, wafAction)
}
rl := Rule{
Name: ruleName,
FullURI: uri,
Actions: actions,
Conditions: conditions,
}
log.Debugf("Configured rule: %v", rl)
return &rl, nil
}
func createPathSegmentConditions(u *url.URL) []*condition {
var c []*condition
path := strings.TrimPrefix(u.EscapedPath(), "/")
segments := strings.Split(path, "/")
// Incase of a No-Host Virtual Server Custom Resource with path as "/"
// Example: vs.Spec.Host = "" && vs.Spec.Pools[0].path = "/"
// Create an empty condition(no condition). This will forward the traffic
// to pool(referred at path "/") when no other conditions are matched.
if segments[0] == "" {
return c
}
for i, v := range segments {
c = append(c, &condition{
Equals: true,
HTTPURI: true,
PathSegment: true,
Name: strconv.Itoa(i + 1),
Index: i + 1,
Request: true,
Values: []string{v},
})
}
return c
}
func createPolicy(rls Rules, policyName, partition string) *Policy {
plcy := Policy{
Controls: []string{PolicyControlForward},
Legacy: true,
Name: policyName,
Partition: partition,
Requires: []string{"http"},
Rules: Rules{},
Strategy: "/Common/first-match",
}
plcy.AddRules(&rls)
log.Debugf("Configured policy: %v", plcy)
return &plcy
}
func getRewriteActions(path, rwPath string, actionNameIndex int) ([]*action, error) {
if rwPath == "" {
return nil, fmt.Errorf("Empty Path")
}
var actions []*action
if rwPath != "" {
if path != "" {
actions = append(actions, &action{
Name: fmt.Sprintf("%d", actionNameIndex),
HTTPURI: true,
Path: path,
Replace: true,
Request: true,
Value: ParseRewriteAction(path, rwPath),
})
} else {
actions = append(actions, &action{
Name: fmt.Sprintf("%d", actionNameIndex),
HTTPURI: true,
Replace: true,
Request: true,
Value: rwPath,
})
}
}
return actions, nil
}
func getHostRewriteActions(rwHost string, actionNameIndex int) ([]*action, error) {
if rwHost == "" {
return nil, fmt.Errorf("empty host")
}
return []*action{{
Name: fmt.Sprintf("%d", actionNameIndex),
HTTPHost: true,
Replace: true,
Request: true,
Value: rwHost,
}}, nil
}
func createRedirectRule(source, target, ruleName string, allowSourceRange []string) (*Rule, error) {
_u := "scheme://" + source
_u = strings.TrimSuffix(_u, "/")
u, err := url.Parse(_u)
if nil != err {
return nil, err
}
redirectAction := action{
Name: "0",
HttpReply: true,
Location: target,
Redirect: true,
Request: true,
}
var conds []*condition
if true == strings.HasPrefix(source, "*.") {
conds = append(conds, &condition{
EndsWith: true,
Host: true,
HTTPHost: true,
Name: "0",
Index: 0,
Request: true,
Values: []string{strings.TrimPrefix(u.Host, "*")},
})
} else if u.Host != "" {
conds = append(conds, &condition{
Equals: true,
Host: true,
HTTPHost: true,
Name: "0",
Index: 0,
Request: true,
Values: []string{u.Host},
})
}
rootCondition := &condition{
Name: "0",
Equals: true,
HTTPURI: true,
Index: 0,
Path: true,
Request: true,
Values: []string{"/"},
}
conds = append(conds, rootCondition)
if len(allowSourceRange) > 0 {
conds = append(conds, &condition{
Tcp: true,
Address: true,
Values: allowSourceRange,
})
}
rl := Rule{
Name: ruleName,
FullURI: source,
Ordinal: 0,
Actions: []*action{&redirectAction},
Conditions: conds,
}
log.Debugf("Configured rule: %v", rl)
return &rl, nil
}
func (rules Rules) Len() int {
return len(rules)
}
func (rules Rules) Less(i, j int) bool {
ruleI := rules[i]
ruleJ := rules[j]
// Strategy 1: Rule with Highest number of conditions
l1 := len(ruleI.Conditions)
l2 := len(ruleJ.Conditions)
if l1 != l2 {
return l1 > l2
}
// Strategy 2: Rule with highest priority sequence of condition types
// TODO
pathExists := func(rule *Rule) bool {
for _, cnd := range rule.Conditions {
if cnd.Path {
return true
}
}
return false
}
if pathExists(ruleI) {
return true
}
if pathExists(ruleJ) {
return true
}
// Strategy 3: "equal" match type takes more priority than others
// such as "starts-with", "ends-with", "contains"
// TODO: And "start-with" and "ends-with" takes same priority and take
// more priority than "contains"
getConditionCounters := func(rule *Rule) (int, int) {
var (
eqCount int
endCount int
)
for _, cnd := range rule.Conditions {
if cnd.Equals {
eqCount++
}
if cnd.EndsWith {
endCount++
}
}
return eqCount, endCount
}
eqCountI, endCountI := getConditionCounters(ruleI)
eqCountJ, endCountJ := getConditionCounters(ruleJ)
if eqCountI != eqCountJ {
return eqCountI > eqCountJ
}
if endCountI != endCountJ {
return endCountI > endCountJ
}
if ruleI.Ordinal != ruleJ.Ordinal {
// Strategy 4: Lowest Ordinal
return ruleI.Ordinal < ruleJ.Ordinal
}
// Strategy 5: Lexicographic Order
return ruleI.Name < ruleJ.Name
}
func (rules Rules) Swap(i, j int) {
rules[i], rules[j] = rules[j], rules[i]
}
// httpRedirectIRuleNoHost redirects traffic to BIG-IP https vs
// for hostLess CRDs.
func httpRedirectIRuleNoHost(port int32) string {
// The key in the data group is the host name or * to match all.
// The data is a list of paths for the host delimited by '|' or '/' for all.
iRuleCode := fmt.Sprintf(`
when HTTP_REQUEST {
HTTP::redirect https://[getfield [HTTP::host] ":" 1]:%d[HTTP::uri]
}`, port)
return iRuleCode
}
// httpRedirectIRule redirects traffic to BIG-IP https vs
// except for the hostLess CRDs.
func httpRedirectIRule(port int32, rsVSName string, partition string) string {
// The key in the data group is the host name or * to match all.
// The data is a list of paths for the host delimited by '|' or '/' for all.
dgName := "/" + partition + "/" + rsVSName + "/" + rsVSName + "_https_redirect_dg"
iRuleCode := fmt.Sprintf(`
when HTTP_REQUEST {
# check if there is an entry in data-groups to accept requests from all domains.
# */ represents [* -> Any host / -> default path]
set allHosts [class match -value "*/" equals %[1]s]
if {$allHosts != ""} {
HTTP::redirect https://[getfield [HTTP::host] ":" 1]:443[HTTP::uri]
return
}
set host [HTTP::host]
set path [HTTP::path]
# Check for the combination of host and path.
append host $path
# Find the number of "/" in the hostpath
set rc 0
foreach x [split $host {}] {
if {$x eq "/"} {
incr rc
}
}
# Compares the hostpath with the entries in https_redirect_dg
for {set i $rc} {$i >= 0} {incr i -1} {
set paths [class match -value $host equals %[1]s]
# Check if host has wildcard match to https_redirect_dg
if {$paths == ""} {
if { [class match $host ends_with %[1]s] } {
set paths [class match -value $host ends_with %[1]s]
}
}
# Check if host with combination of "/" matches https_redirect_dg
if {$paths == ""} {
set hosts ""
append hosts $host "/"
set paths [class match -value $hosts equals %[1]s]
if {$paths == ""} {
# Check if host with combination of "/" has wildcard
# match with https_redirect_dg
if { [class match $hosts ends_with %[1]s] } {
set paths [class match -value $hosts ends_with %[1]s]
}
}
}
# Trim the uri to last slash
if {$paths == ""} {
set host [
string range $host 0 [
expr {[string last "/" $host]-1}
]
]
}
else {
break
}
}
if {$paths != ""} {
set redir 0
set prefix ""
foreach s [split $paths "|"] {
# See if the request path starts with the prefix
append prefix "^" $s "($|/*)"
if {[HTTP::path] matches_regex $prefix} {
set redir 1
break
}
}
if {$redir == 1} {
HTTP::redirect https://[getfield [HTTP::host] ":" 1]:%[2]d[HTTP::uri]
}
}
}`, dgName, port)
return iRuleCode
}
func (ctlr *Controller) getPathBasedABDeployIRule(rsVSName string, partition string, multiPoolPersistence MultiPoolPersistence) string {
dgPath := strings.Join([]string{partition, rsVSName}, "/")
iRule := fmt.Sprintf(`proc select_ab_pool {path default_pool } {
set last_slash [string length $path]
set ab_class "/%[1]s/%[2]s_ab_deployment_dg"
while {$last_slash >= 0} {
if {[class match $path equals $ab_class]} then {
break
}
set last_slash [string last "/" $path $last_slash]
incr last_slash -1
set path [string range $path 0 $last_slash]
}
if {$last_slash >= 0} {
set ab_rule [class match -value $path equals $ab_class]
if {$ab_rule != ""} then {
set weight_selection [expr {rand()}]
set service_rules [split $ab_rule ";"]
set active_pool ""
foreach service_rule $service_rules {
set fields [split $service_rule ","]
set pool_name [lindex $fields 0]
if { [active_members $pool_name] >= 1 } {
set active_pool $pool_name
}
set weight [expr {double([lindex $fields 1])}]
if {$weight_selection <= $weight} then {
#check if active pool members are available
if { [active_members $pool_name] >= 1 } {
return $pool_name
} else {
# select other pool with active members
if {$active_pool!= ""} then {
return $active_pool
}
}
}
}
}
# If we had a match, but all weights were 0 then
# retrun a 503 (Service Unavailable)
HTTP::respond 503
}
return $default_pool
}`, dgPath, rsVSName)
persistenceType := getPersistenceType(multiPoolPersistence.Method)
if persistenceType != "" {
iRule += fmt.Sprintf(`
when HTTP_REQUEST priority 200 {
set path [string tolower [HTTP::host]][HTTP::path]
set persist_key "[IP::client_addr]:$path"
set persist_record [linsert [persist lookup %v [list $persist_key any pool] ] 1 member]
if {$persist_record ne "member"} then {
pool [lindex $persist_record 0] member [lindex $persist_record 2] [lindex $persist_record 3]
event disable
} else {
set selected_pool [call select_ab_pool $path ""]
if {$selected_pool != ""} then {
pool $selected_pool
persist %v $persist_key %v
event disable
}
}
}`, persistenceType, persistenceType, multiPoolPersistence.TimeOut)
} else {
iRule += fmt.Sprintf(`
when HTTP_REQUEST priority 200 {
set path [string tolower [HTTP::host]][HTTP::path]
set selected_pool [call select_ab_pool $path ""]
if {$selected_pool != ""} then {
pool $selected_pool
event disable
}
}`)
}
return iRule
}
func getPersistenceType(key string) string {
if key == "" {
return key
}
// supported persistence types
// the keys should be in sync with the supported values of multiPoolPersistence in policy
// any change to the multiPoolPersistence def should be reflected here
persisMap := map[string]string{
"uieSourceAddress": "uie",
"hashSourceAddress": "hash",
}
if val, ok := persisMap[key]; ok {
return val
} else {
return ""
}
}
func (ctlr *Controller) getTLSIRule(rsVSName string, partition string, allowSourceRange []string, multiPoolPersistence MultiPoolPersistence) string {
dgPath := strings.Join([]string{partition, rsVSName}, "/")
iRule := fmt.Sprintf(`
when CLIENT_DATA {
# Byte 0 is the content type.
# Bytes 1-2 are the TLS version.
# Bytes 3-4 are the TLS payload length.
# Bytes 5-$tls_payload_len are the TLS payload.
binary scan [TCP::payload] cSS tls_content_type tls_version tls_payload_len
if { ! [ expr { [info exists tls_content_type] && [string is integer -strict $tls_content_type] } ] } { reject ; event disable all; return; }
if { ! [ expr { [info exists tls_version] && [string is integer -strict $tls_version] } ] } { reject ; event disable all; return; }
switch -exact $tls_version {
"769" -
"770" -
"771" {
# Content type of 22 indicates the TLS payload contains a handshake.
if { $tls_content_type == 22 } {
# Byte 5 (the first byte of the handshake) indicates the handshake
# record type, and a value of 1 signifies that the handshake record is
# a ClientHello.
binary scan [TCP::payload] @5c tls_handshake_record_type
if { ! [ expr { [info exists tls_handshake_record_type] && [string is integer -strict $tls_handshake_record_type] } ] } { reject ; event disable all; return; }
if { $tls_handshake_record_type == 1 } {
# Bytes 6-8 are the handshake length (which we ignore).
# Bytes 9-10 are the TLS version (which we ignore).
# Bytes 11-42 are random data (which we ignore).
# Byte 43 is the session ID length. Following this are three
# variable-length fields which we shall skip over.
set record_offset 43
# Skip the session ID.
binary scan [TCP::payload] @${record_offset}c tls_session_id_len
if { ! [ expr { [info exists tls_session_id_len] && [string is integer -strict $tls_session_id_len] } ] } { reject ; event disable all; return; }
incr record_offset [expr {1 + $tls_session_id_len}]
# Skip the cipher_suites field.
binary scan [TCP::payload] @${record_offset}S tls_cipher_suites_len
if { ! [ expr { [info exists tls_cipher_suites_len] && [string is integer -strict $tls_cipher_suites_len] } ] } { reject ; event disable all; return; }
incr record_offset [expr {2 + $tls_cipher_suites_len}]
# Skip the compression_methods field.
binary scan [TCP::payload] @${record_offset}c tls_compression_methods_len
if { ! [ expr { [info exists tls_compression_methods_len] && [string is integer -strict $tls_compression_methods_len] } ] } { reject ; event disable all; return; }
incr record_offset [expr {1 + $tls_compression_methods_len}]
# Get the number of extensions, and store the extensions.
binary scan [TCP::payload] @${record_offset}S tls_extensions_len
if { ! [ expr { [info exists tls_extensions_len] && [string is integer -strict $tls_extensions_len] } ] } { reject ; event disable all; return; }
incr record_offset 2
binary scan [TCP::payload] @${record_offset}a* tls_extensions
if { ! [info exists tls_extensions] } { reject ; event disable all; return; }
for { set extension_start 0 }
{ $tls_extensions_len - $extension_start == abs($tls_extensions_len - $extension_start) }
{ incr extension_start 4 } {
# Bytes 0-1 of the extension are the extension type.
# Bytes 2-3 of the extension are the extension length.
binary scan $tls_extensions @${extension_start}SS extension_type extension_len
if { ! [ expr { [info exists extension_type] && [string is integer -strict $extension_type] } ] } { reject ; event disable all; return; }
if { ! [ expr { [info exists extension_len] && [string is integer -strict $extension_len] } ] } { reject ; event disable all; return; }
# Extension type 00 is the ServerName extension.
if { $extension_type == "00" } {
# Bytes 4-5 of the extension are the SNI length (we ignore this).
# Byte 6 of the extension is the SNI type.
set sni_type_offset [expr {$extension_start + 6}]
binary scan $tls_extensions @${sni_type_offset}S sni_type
if { ! [ expr { [info exists sni_type] && [string is integer -strict $sni_type] } ] } { reject ; event disable all; return; }
# Type 0 is host_name.
if { $sni_type == "0" } {
# Bytes 7-8 of the extension are the SNI data (host_name)
# length.
set sni_len_offset [expr {$extension_start + 7}]
binary scan $tls_extensions @${sni_len_offset}S sni_len
if { ! [ expr { [info exists sni_len] && [string is integer -strict $sni_len] } ] } { reject ; event disable all; return; }
# Bytes 9-$sni_len are the SNI data (host_name).
set sni_start [expr {$extension_start + 9}]
binary scan $tls_extensions @${sni_start}A${sni_len} tls_servername
}
}
incr extension_start $extension_len
}
if { [info exists tls_servername] } {
set servername_lower [string tolower $tls_servername]
set domain_length [llength [split $servername_lower "."]]
set domain_wc [domain $servername_lower [expr {$domain_length - 1}] ]
# Set wc_host with the wildcard domain
set wc_host ".$domain_wc"
set passthru_class "/%[1]s/%[2]s_ssl_passthrough_servername_dg"
if { [class exists $passthru_class] } {
SSL::disable serverside
set dflt_pool_passthrough ""
# Disable Serverside SSL for Passthrough Class
set dflt_pool_passthrough [class match -value $servername_lower equals $passthru_class]
# If no match, try wildcard domain
if { $dflt_pool_passthrough == "" } {
if { [class match $wc_host equals $passthru_class] } {
set dflt_pool_passthrough [class match -value $wc_host equals $passthru_class]
}
}
if { not ($dflt_pool_passthrough equals "") } {
SSL::disable
HTTP::disable
}
set ab_class "/%[1]s/%[2]s_ab_deployment_dg"
if { not [class exists $ab_class] } {
if { $dflt_pool_passthrough == "" } then {
log local0.debug "Failed to find pool for $servername_lower $"
} else {
pool $dflt_pool_passthrough
}
} else {
set selected_pool [call select_ab_pool $servername_lower $dflt_pool_passthrough ""]
if { $selected_pool == "" } then {
log local0.debug "Failed to find pool for $servername_lower"
} else {
pool $selected_pool
}
}
}
}
}
}
}
}
TCP::release
}
when CLIENTSSL_HANDSHAKE {
SSL::collect
}
when CLIENTSSL_DATA {
if { [llength [split [SSL::payload]]] < 1 }{
reject ; event disable all; return;
}
set sslpath [lindex [split [SSL::payload]] 1]
set domainpath $sslpath
set routepath ""
set wc_routepath ""
if { [info exists tls_servername] } {
set servername_lower [string tolower $tls_servername]
set domain_length [llength [split $servername_lower "."]]
set domain_wc [domain $servername_lower [expr {$domain_length - 1}] ]
set wc_host ".$domain_wc"
# Set routepath as combination of servername and url path
append routepath $servername_lower $sslpath
append wc_routepath $wc_host $sslpath
set routepath [string tolower $routepath]
set wc_routepath [string tolower $wc_routepath]
set sslpath $routepath
# Find the number of "/" in the routepath
set rc 0
foreach x [split $routepath {}] {
if {$x eq "/"} {
incr rc
}
}
# Disable serverside ssl and enable only for reencrypt routes
SSL::disable serverside
set reencrypt_class "/%[1]s/%[2]s_ssl_reencrypt_servername_dg"
set edge_class "/%[1]s/%[2]s_ssl_edge_servername_dg"
if { [class exists $reencrypt_class] || [class exists $edge_class] } {
# Compares the routepath with the entries in ssl_reencrypt_servername_dg and
# ssl_edge_servername_dg.
for {set i $rc} {$i >= 0} {incr i -1} {
if { [class exists $reencrypt_class] } {
set reen_pool [class match -value $routepath equals $reencrypt_class]
# Check for wildcard domain
if { $reen_pool equals "" } {
if { [class match $wc_routepath equals $reencrypt_class] } {
set reen_pool [class match -value $wc_routepath equals $reencrypt_class]
}
}
if { not ($reen_pool equals "") } {
set dflt_pool $reen_pool
SSL::enable serverside
}
}
if { [class exists $edge_class] } {
set edge_pool [class match -value $routepath equals $edge_class]
# Check for wildcard domain
if { $edge_pool equals "" } {
if { [class match $wc_routepath equals $edge_class] } {
set edge_pool [class match -value $wc_routepath equals $edge_class]
}
}
if { not ($edge_pool equals "") } {
set dflt_pool $edge_pool
}
}
if { not [info exists dflt_pool] } {
set routepath [
string range $routepath 0 [
expr {[string last "/" $routepath]-1}
]
]
set wc_routepath [
string range $wc_routepath 0 [
expr {[string last "/" $wc_routepath]-1}
]
]
}
else {
break
}
}
}
# handle the default pool for virtual server
set default_class "/%[1]s/%[2]s_default_pool_servername_dg"
if { [class exists $default_class] } {
set dflt_pool [class match -value "defaultPool" equals $default_class]
}
# Handle requests sent to unknown hosts.
# For valid hosts, Send the request to respective pool.
if { not [info exists dflt_pool] } then {
# Allowing HTTP2 traffic to be handled by policies and closing the connection for HTTP/1.1 unknown hosts.
if { not ([SSL::payload] starts_with "PRI * HTTP/2.0") } {
reject ; event disable all; return;
}
} else {
pool $dflt_pool
}
set ab_class "/%[1]s/%[2]s_ab_deployment_dg"
if { [class exists $ab_class] } {
set selected_pool [call select_ab_pool $servername_lower $dflt_pool $domainpath]
if { $selected_pool == "" } then {
log local0.debug "Unable to find pool for $servername_lower"
} else {
pool $selected_pool
}
}
}
SSL::release
}
when SERVER_CONNECTED {
set reencryptssl_class "/%[1]s/%[2]s_ssl_reencrypt_serverssl_dg"
set edgessl_class "/%[1]s/%[2]s_ssl_edge_serverssl_dg"
if { [info exists sslpath] and [class exists $reencryptssl_class] } {
# Find the nearest child path which matches the reencrypt_class
for {set i $rc} {$i >= 0} {incr i -1} {
if { [class exists $reencryptssl_class] } {
set reen [class match -value $sslpath equals $reencryptssl_class]
# check for wildcard domain match
if { $reen equals "" } {
if { [class match $wc_routepath equals $reencryptssl_class] } {
set reen [class match -value $wc_routepath equals $reencryptssl_class]
}
}
if { not ($reen equals "") } {
set sslprofile $reen
}
}
if { [class exists $edgessl_class] } {
set edge [class match -value $sslpath equals $edgessl_class]
# check for wildcard domain match
if { $edge equals "" } {
if { [class match $wc_routepath equals $edgessl_class] } {
set edge [class match -value $wc_routepath equals $edgessl_class]
}
}
if { not ($edge equals "") } {
set sslprofile $edge
}
}
if { not [info exists sslprofile] } {
set sslpath [
string range $sslpath 0 [
expr {[string last "/" $sslpath]-1}
]
]
set wc_routepaath [
string range $wc_routepath 0 [
expr {[string last "/" $wc_routepath]-1}
]
]
}