-
Notifications
You must be signed in to change notification settings - Fork 7.6k
/
validation.go
3934 lines (3527 loc) · 134 KB
/
validation.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 Istio Authors
//
// 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 validation
import (
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"net/netip"
"net/url"
"path"
"regexp"
"strconv"
"strings"
"time"
"github.com/hashicorp/go-multierror"
"github.com/lestrrat-go/jwx/jwk"
"google.golang.org/protobuf/types/known/durationpb"
"istio.io/api/annotation"
extensions "istio.io/api/extensions/v1alpha1"
meshconfig "istio.io/api/mesh/v1alpha1"
networking "istio.io/api/networking/v1alpha3"
networkingv1beta1 "istio.io/api/networking/v1beta1"
security_beta "istio.io/api/security/v1beta1"
telemetry "istio.io/api/telemetry/v1alpha1"
type_beta "istio.io/api/type/v1beta1"
"istio.io/istio/pilot/pkg/features"
"istio.io/istio/pilot/pkg/serviceregistry/util/label"
"istio.io/istio/pkg/config"
"istio.io/istio/pkg/config/constants"
"istio.io/istio/pkg/config/gateway"
"istio.io/istio/pkg/config/host"
"istio.io/istio/pkg/config/labels"
"istio.io/istio/pkg/config/protocol"
"istio.io/istio/pkg/config/schema/gvk"
"istio.io/istio/pkg/config/security"
"istio.io/istio/pkg/config/visibility"
"istio.io/istio/pkg/jwt"
"istio.io/istio/pkg/kube/apimirror"
"istio.io/istio/pkg/log"
"istio.io/istio/pkg/util/grpc"
netutil "istio.io/istio/pkg/util/net"
"istio.io/istio/pkg/util/protomarshal"
"istio.io/istio/pkg/util/sets"
)
// Constants for duration fields
const (
// Set some high upper bound to avoid weird configurations
// nolint: revive
connectTimeoutMax = time.Hour
// nolint: revive
connectTimeoutMin = time.Millisecond
drainTimeMax = time.Hour
// UnixAddressPrefix is the prefix used to indicate an address is for a Unix Domain socket. It is used in
// ServiceEntry.Endpoint.Address message.
UnixAddressPrefix = "unix://"
matchExact = "exact:"
matchPrefix = "prefix:"
)
const (
regionIndex int = iota
zoneIndex
subZoneIndex
kb = 1024
mb = 1024 * kb
)
var (
// envoy supported retry on header values
supportedRetryOnPolicies = map[string]bool{
// 'x-envoy-retry-on' supported policies:
// https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_filters/router_filter.html#x-envoy-retry-on
"5xx": true,
"gateway-error": true,
"reset": true,
"connect-failure": true,
"retriable-4xx": true,
"refused-stream": true,
"retriable-status-codes": true,
"retriable-headers": true,
"envoy-ratelimited": true,
// 'x-envoy-retry-grpc-on' supported policies:
// https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_filters/router_filter#x-envoy-retry-grpc-on
"cancelled": true,
"deadline-exceeded": true,
"internal": true,
"resource-exhausted": true,
"unavailable": true,
}
// golang supported methods: https://golang.org/src/net/http/method.go
supportedMethods = map[string]bool{
http.MethodGet: true,
http.MethodHead: true,
http.MethodPost: true,
http.MethodPut: true,
http.MethodPatch: true,
http.MethodDelete: true,
http.MethodConnect: true,
http.MethodOptions: true,
http.MethodTrace: true,
}
scope = log.RegisterScope("validation", "CRD validation debugging")
// EmptyValidate is a Validate that does nothing and returns no error.
EmptyValidate = RegisterValidateFunc("EmptyValidate",
func(config.Config) (Warning, error) {
return nil, nil
})
validateFuncs = make(map[string]ValidateFunc)
)
type Warning error
// Validation holds errors and warnings. They can be joined with additional errors by called AppendValidation
type Validation struct {
Err error
Warning Warning
}
type AnalysisAwareError struct {
Type string
Msg string
Parameters []any
}
// OverlappingMatchValidationForHTTPRoute holds necessary information from virtualservice
// to do such overlapping match validation
type OverlappingMatchValidationForHTTPRoute struct {
RouteStr string
MatchStr string
Prefix string
MatchPort uint32
MatchMethod string
MatchAuthority string
MatchHeaders map[string]string
MatchQueryParams map[string]string
MatchNonHeaders map[string]string
}
var _ error = Validation{}
// WrapError turns an error into a Validation
func WrapError(e error) Validation {
return Validation{Err: e}
}
// WrapWarning turns an error into a Validation as a warning
func WrapWarning(e error) Validation {
return Validation{Warning: e}
}
// Warningf formats according to a format specifier and returns the string as a
// value that satisfies error. Like Errorf, but for warnings.
func Warningf(format string, a ...any) Validation {
return WrapWarning(fmt.Errorf(format, a...))
}
func (v Validation) Unwrap() (Warning, error) {
return v.Warning, v.Err
}
func (v Validation) Error() string {
if v.Err == nil {
return ""
}
return v.Err.Error()
}
// ValidateFunc defines a validation func for an API proto.
type ValidateFunc func(config config.Config) (Warning, error)
// IsValidateFunc indicates whether there is a validation function with the given name.
func IsValidateFunc(name string) bool {
return GetValidateFunc(name) != nil
}
// GetValidateFunc returns the validation function with the given name, or null if it does not exist.
func GetValidateFunc(name string) ValidateFunc {
return validateFuncs[name]
}
func RegisterValidateFunc(name string, f ValidateFunc) ValidateFunc {
// Wrap the original validate function with an extra validate function for object metadata
validate := validateMetadata(f)
validateFuncs[name] = validate
return validate
}
func validateMetadata(f ValidateFunc) ValidateFunc {
return func(config config.Config) (Warning, error) {
// Check the annotation "istio.io/dry-run".
_, isAuthz := config.Spec.(*security_beta.AuthorizationPolicy)
// Only the AuthorizationPolicy supports the annotation "istio.io/dry-run".
if err := checkDryRunAnnotation(config, isAuthz); err != nil {
return nil, err
}
if _, f := config.Annotations[constants.AlwaysReject]; f {
return nil, fmt.Errorf("%q annotation found, rejecting", constants.AlwaysReject)
}
return f(config)
}
}
func checkDryRunAnnotation(cfg config.Config, allowed bool) error {
if val, found := cfg.Annotations[annotation.IoIstioDryRun.Name]; found {
if !allowed {
return fmt.Errorf("%s/%s has unsupported annotation %s, please remove the annotation", cfg.Namespace, cfg.Name, annotation.IoIstioDryRun.Name)
}
if spec, ok := cfg.Spec.(*security_beta.AuthorizationPolicy); ok {
switch spec.Action {
case security_beta.AuthorizationPolicy_ALLOW, security_beta.AuthorizationPolicy_DENY:
if _, err := strconv.ParseBool(val); err != nil {
return fmt.Errorf("%s/%s has annotation %s with invalid value (%s): %v", cfg.Namespace, cfg.Name, annotation.IoIstioDryRun.Name, val, err)
}
default:
return fmt.Errorf("the annotation %s currently only supports action ALLOW/DENY, found action %v in %s/%s",
annotation.IoIstioDryRun.Name, spec.Action, cfg.Namespace, cfg.Name)
}
}
}
return nil
}
// ValidatePort checks that the network port is in range
func ValidatePort(port int) error {
if 1 <= port && port <= 65535 {
return nil
}
return fmt.Errorf("port number %d must be in the range 1..65535", port)
}
// ValidateFQDN checks a fully-qualified domain name
func ValidateFQDN(fqdn string) error {
if err := checkDNS1123Preconditions(fqdn); err != nil {
return err
}
return validateDNS1123Labels(fqdn)
}
// ValidateWildcardDomain checks that a domain is a valid FQDN, but also allows wildcard prefixes.
func ValidateWildcardDomain(domain string) error {
if err := checkDNS1123Preconditions(domain); err != nil {
return err
}
// We only allow wildcards in the first label; split off the first label (parts[0]) from the rest of the host (parts[1])
parts := strings.SplitN(domain, ".", 2)
if !labels.IsWildcardDNS1123Label(parts[0]) {
return fmt.Errorf("domain name %q invalid (label %q invalid)", domain, parts[0])
} else if len(parts) > 1 {
return validateDNS1123Labels(parts[1])
}
return nil
}
// encapsulates DNS 1123 checks common to both wildcarded hosts and FQDNs
func checkDNS1123Preconditions(name string) error {
if len(name) > 255 {
return fmt.Errorf("domain name %q too long (max 255)", name)
}
if len(name) == 0 {
return fmt.Errorf("empty domain name not allowed")
}
return nil
}
func validateDNS1123Labels(domain string) error {
parts := strings.Split(domain, ".")
topLevelDomain := parts[len(parts)-1]
if _, err := strconv.Atoi(topLevelDomain); err == nil {
return fmt.Errorf("domain name %q invalid (top level domain %q cannot be all-numeric)", domain, topLevelDomain)
}
for i, label := range parts {
// Allow the last part to be empty, for unambiguous names like `istio.io.`
if i == len(parts)-1 && label == "" {
return nil
}
if !labels.IsDNS1123Label(label) {
return fmt.Errorf("domain name %q invalid (label %q invalid)", domain, label)
}
}
return nil
}
// validate the trust domain format
func ValidateTrustDomain(domain string) error {
if len(domain) == 0 {
return fmt.Errorf("empty domain name not allowed")
}
parts := strings.Split(domain, ".")
for i, label := range parts {
// Allow the last part to be empty, for unambiguous names like `istio.io.`
if i == len(parts)-1 && label == "" {
return nil
}
if !labels.IsDNS1123Label(label) {
return fmt.Errorf("trust domain name %q invalid", domain)
}
}
return nil
}
// ValidateHTTPHeaderName validates a header name
func ValidateHTTPHeaderName(name string) error {
if name == "" {
return fmt.Errorf("header name cannot be empty")
}
return nil
}
// ValidateHTTPHeaderWithAuthorityOperationName validates a header name when used to add/set in request.
func ValidateHTTPHeaderWithAuthorityOperationName(name string) error {
if name == "" {
return fmt.Errorf("header name cannot be empty")
}
// Authority header is validated later
if isInternalHeader(name) && !isAuthorityHeader(name) {
return fmt.Errorf(`invalid header %q: header cannot have ":" prefix`, name)
}
return nil
}
// ValidateHTTPHeaderOperationName validates a header name when used to remove from request or modify response.
func ValidateHTTPHeaderOperationName(name string) error {
if name == "" {
return fmt.Errorf("header name cannot be empty")
}
if strings.EqualFold(name, "host") {
return fmt.Errorf(`invalid header %q: cannot set Host header`, name)
}
if isInternalHeader(name) {
return fmt.Errorf(`invalid header %q: header cannot have ":" prefix`, name)
}
return nil
}
// Copy from https://github.com/bufbuild/protoc-gen-validate/blob/a65858624dd654f2fb306d6af60f737132986f44/module/checker.go#L18
var httpHeaderValueRegexp = regexp.MustCompile("^[^\u0000-\u0008\u000A-\u001F\u007F]*$")
// ValidateHTTPHeaderValue validates a header value for Envoy
// Valid: "foo", "%HOSTNAME%", "100%%", "prefix %HOSTNAME% suffix"
// Invalid: "abc%123", "%START_TIME%%"
// We don't try to check that what is inside the %% is one of Envoy recognized values, we just prevent invalid config.
// See: https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_conn_man/headers.html#custom-request-response-headers
func ValidateHTTPHeaderValue(value string) error {
if !httpHeaderValueRegexp.MatchString(value) {
return fmt.Errorf("header value configuration %s is invalid", value)
}
if err := validateHeaderValue(value); err != nil {
return fmt.Errorf("header value configuration: %w", err)
}
// TODO: find a better way to validate fields supported in custom header, e.g %ENVIRONMENT(X):Z%
return nil
}
// validateWeight checks if weight is valid
func validateWeight(weight int32) error {
if weight < 0 {
return fmt.Errorf("weight %d < 0", weight)
}
return nil
}
// ValidatePercent checks that percent is in range
func ValidatePercent(val int32) error {
if val < 0 || val > 100 {
return fmt.Errorf("percentage %v is not in range 0..100", val)
}
return nil
}
// validatePercentage checks if the specified fractional percentage is valid.
func validatePercentage(percentage *networking.Percent) error {
if percentage != nil {
if percentage.Value < 0.0 || percentage.Value > 100.0 || (percentage.Value > 0.0 && percentage.Value < 0.0001) {
return fmt.Errorf("percentage %v is neither 0.0, nor in range [0.0001, 100.0]", percentage.Value)
}
}
return nil
}
// ValidateIPSubnet checks that a string is in "CIDR notation" or "Dot-decimal notation"
func ValidateIPSubnet(subnet string) error {
// We expect a string in "CIDR notation" or "Dot-decimal notation"
// E.g., a.b.c.d/xx form or just a.b.c.d or 2001:1::1/64
if strings.Count(subnet, "/") == 1 {
// We expect a string in "CIDR notation", i.e. a.b.c.d/xx or 2001:1::1/64 form
if _, err := netip.ParsePrefix(subnet); err != nil {
return fmt.Errorf("%v is not a valid CIDR block", subnet)
}
return nil
}
return ValidateIPAddress(subnet)
}
// ValidateIPAddress validates that a string in "CIDR notation" or "Dot-decimal notation"
func ValidateIPAddress(addr string) error {
if _, err := netip.ParseAddr(addr); err != nil {
return fmt.Errorf("%v is not a valid IP", addr)
}
return nil
}
// ValidateUnixAddress validates that the string is a valid unix domain socket path.
func ValidateUnixAddress(addr string) error {
if len(addr) == 0 {
return errors.New("unix address must not be empty")
}
// Allow unix abstract domain sockets whose names start with @
if strings.HasPrefix(addr, "@") {
return nil
}
// Note that we use path, not path/filepath even though a domain socket path is a file path. We don't want the
// Pilot output to depend on which OS Pilot is run on, so we always use Unix-style forward slashes.
if !path.IsAbs(addr) || strings.HasSuffix(addr, "/") {
return fmt.Errorf("%s is not an absolute path to a file", addr)
}
return nil
}
// ValidateGateway checks gateway specifications
var ValidateGateway = RegisterValidateFunc("ValidateGateway",
func(cfg config.Config) (Warning, error) {
name := cfg.Name
// Check if this was converted from a k8s gateway-api resource
gatewaySemantics := cfg.Annotations[constants.InternalGatewaySemantics] == constants.GatewaySemanticsGateway
v := Validation{}
// Gateway name must conform to the DNS label format (no dots)
if !labels.IsDNS1123Label(name) {
v = AppendValidation(v, fmt.Errorf("invalid gateway name: %q", name))
}
value, ok := cfg.Spec.(*networking.Gateway)
if !ok {
v = AppendValidation(v, fmt.Errorf("cannot cast to gateway: %#v", cfg.Spec))
return v.Unwrap()
}
if len(value.Servers) == 0 {
v = AppendValidation(v, fmt.Errorf("gateway must have at least one server"))
} else {
for _, server := range value.Servers {
v = AppendValidation(v, validateServer(server, gatewaySemantics))
}
}
// Ensure unique port names
portNames := make(map[string]bool)
for _, s := range value.Servers {
if s == nil {
v = AppendValidation(v, fmt.Errorf("server may not be nil"))
continue
}
if s.Port != nil {
if portNames[s.Port.Name] {
v = AppendValidation(v, fmt.Errorf("port names in servers must be unique: duplicate name %s", s.Port.Name))
}
portNames[s.Port.Name] = true
if !protocol.Parse(s.Port.Protocol).IsHTTP() && s.GetTls().GetHttpsRedirect() {
v = AppendValidation(v, WrapWarning(fmt.Errorf("tls.httpsRedirect should only be used with http servers")))
}
}
}
return v.Unwrap()
})
func validateServer(server *networking.Server, gatewaySemantics bool) (v Validation) {
if server == nil {
return WrapError(fmt.Errorf("cannot have nil server"))
}
if len(server.Hosts) == 0 {
v = AppendValidation(v, fmt.Errorf("server config must contain at least one host"))
} else {
for _, hostname := range server.Hosts {
v = AppendValidation(v, validateNamespaceSlashWildcardHostname(hostname, true, gatewaySemantics))
}
}
portErr := validateServerPort(server.Port, server.Bind)
v = AppendValidation(v, portErr)
v = AppendValidation(v, validateServerBind(server.Port, server.Bind))
v = AppendValidation(v, validateTLSOptions(server.Tls))
// If port is HTTPS or TLS, make sure that server has TLS options
if _, err := portErr.Unwrap(); err == nil {
p := protocol.Parse(server.Port.Protocol)
if p.IsTLS() && server.Tls == nil {
v = AppendValidation(v, fmt.Errorf("server must have TLS settings for HTTPS/TLS protocols"))
} else if !p.IsTLS() && server.Tls != nil {
// only tls redirect is allowed if this is a HTTP server
if p.IsHTTP() {
if !gateway.IsPassThroughServer(server) ||
server.Tls.CaCertificates != "" || server.Tls.PrivateKey != "" || server.Tls.ServerCertificate != "" {
v = AppendValidation(v, fmt.Errorf("server cannot have TLS settings for plain text HTTP ports"))
}
} else {
v = AppendValidation(v, fmt.Errorf("server cannot have TLS settings for non HTTPS/TLS ports"))
}
}
}
return v
}
func validateServerPort(port *networking.Port, bind string) (errs Validation) {
if port == nil {
return AppendValidation(errs, fmt.Errorf("port is required"))
}
if protocol.Parse(port.Protocol) == protocol.Unsupported {
errs = AppendValidation(errs, fmt.Errorf("invalid protocol %q, supported protocols are HTTP, HTTP2, GRPC, GRPC-WEB, MONGO, REDIS, MYSQL, TCP", port.Protocol))
}
if port.Number > 0 || !strings.HasPrefix(bind, UnixAddressPrefix) {
errs = AppendValidation(errs, ValidatePort(int(port.Number)))
}
// nolint: staticcheck
if port.TargetPort > 0 {
errs = AppendValidation(errs, fmt.Errorf("targetPort has no impact on Gateways"))
}
if port.Name == "" {
errs = AppendValidation(errs, fmt.Errorf("port name must be set: %v", port))
}
return
}
func validateServerBind(port *networking.Port, bind string) (errs error) {
if strings.HasPrefix(bind, UnixAddressPrefix) {
errs = appendErrors(errs, ValidateUnixAddress(strings.TrimPrefix(bind, UnixAddressPrefix)))
if port != nil && port.Number != 0 {
errs = appendErrors(errs, fmt.Errorf("port number must be 0 for unix domain socket: %v", port))
}
} else if len(bind) != 0 {
errs = appendErrors(errs, ValidateIPAddress(bind))
}
return
}
func validateTLSOptions(tls *networking.ServerTLSSettings) (v Validation) {
if tls == nil {
// no tls config at all is valid
return
}
if tls.MinProtocolVersion == networking.ServerTLSSettings_TLSV1_0 || tls.MinProtocolVersion == networking.ServerTLSSettings_TLSV1_1 {
if len(tls.CipherSuites) == 0 {
v = AppendWarningf(v, "TLS version below TLSV1_2 require setting compatible ciphers as by default they no longer include compatible ciphers.")
}
}
invalidCiphers := sets.New[string]()
validCiphers := sets.New[string]()
duplicateCiphers := sets.New[string]()
for _, cs := range tls.CipherSuites {
if !security.IsValidCipherSuite(cs) {
invalidCiphers.Insert(cs)
} else if validCiphers.InsertContains(cs) {
duplicateCiphers.Insert(cs)
}
}
if len(invalidCiphers) > 0 {
v = AppendWarningf(v, "ignoring invalid cipher suites: %v", sets.SortedList(invalidCiphers))
}
if len(duplicateCiphers) > 0 {
v = AppendWarningf(v, "ignoring duplicate cipher suites: %v", sets.SortedList(duplicateCiphers))
}
if tls.Mode == networking.ServerTLSSettings_ISTIO_MUTUAL {
// ISTIO_MUTUAL TLS mode uses either SDS or default certificate mount paths
// therefore, we should fail validation if other TLS fields are set
if tls.ServerCertificate != "" {
v = AppendValidation(v, fmt.Errorf("ISTIO_MUTUAL TLS cannot have associated server certificate"))
}
if tls.PrivateKey != "" {
v = AppendValidation(v, fmt.Errorf("ISTIO_MUTUAL TLS cannot have associated private key"))
}
if tls.CaCertificates != "" {
v = AppendValidation(v, fmt.Errorf("ISTIO_MUTUAL TLS cannot have associated CA bundle"))
}
if tls.CredentialName != "" {
v = AppendValidation(v, fmt.Errorf("ISTIO_MUTUAL TLS cannot have associated credentialName"))
}
return
}
if tls.Mode == networking.ServerTLSSettings_PASSTHROUGH || tls.Mode == networking.ServerTLSSettings_AUTO_PASSTHROUGH {
if tls.CaCrl != "" || tls.ServerCertificate != "" || tls.PrivateKey != "" || tls.CaCertificates != "" || tls.CredentialName != "" {
// Warn for backwards compatibility
v = AppendWarningf(v, "%v mode does not use certificates, they will be ignored", tls.Mode)
}
}
if (tls.Mode == networking.ServerTLSSettings_SIMPLE || tls.Mode == networking.ServerTLSSettings_MUTUAL ||
tls.Mode == networking.ServerTLSSettings_OPTIONAL_MUTUAL) && tls.CredentialName != "" {
// If tls mode is SIMPLE or MUTUAL/OPTIONL_MUTUAL, and CredentialName is specified, credentials are fetched
// remotely. ServerCertificate and CaCertificates fields are not required.
return
}
if tls.Mode == networking.ServerTLSSettings_SIMPLE {
if tls.ServerCertificate == "" {
v = AppendValidation(v, fmt.Errorf("SIMPLE TLS requires a server certificate"))
}
if tls.PrivateKey == "" {
v = AppendValidation(v, fmt.Errorf("SIMPLE TLS requires a private key"))
}
} else if tls.Mode == networking.ServerTLSSettings_MUTUAL || tls.Mode == networking.ServerTLSSettings_OPTIONAL_MUTUAL {
if tls.ServerCertificate == "" {
v = AppendValidation(v, fmt.Errorf("MUTUAL TLS requires a server certificate"))
}
if tls.PrivateKey == "" {
v = AppendValidation(v, fmt.Errorf("MUTUAL TLS requires a private key"))
}
if tls.CaCertificates == "" {
v = AppendValidation(v, fmt.Errorf("MUTUAL TLS requires a client CA bundle"))
}
}
if tls.CaCrl != "" {
if tls.CredentialName != "" {
v = AppendValidation(v, fmt.Errorf("CRL is not supported with credentialName. CRL has to be specified in the credential"))
}
if tls.Mode == networking.ServerTLSSettings_SIMPLE {
v = AppendValidation(v, fmt.Errorf("CRL is not supported with SIMPLE TLS"))
}
}
return
}
// ValidateDestinationRule checks proxy policies
var ValidateDestinationRule = RegisterValidateFunc("ValidateDestinationRule",
func(cfg config.Config) (Warning, error) {
rule, ok := cfg.Spec.(*networking.DestinationRule)
if !ok {
return nil, fmt.Errorf("cannot cast to destination rule")
}
v := Validation{}
v = AppendValidation(v,
ValidateWildcardDomain(rule.Host),
validateTrafficPolicy(rule.TrafficPolicy))
subsets := sets.String{}
for _, subset := range rule.Subsets {
if subset == nil {
v = AppendValidation(v, errors.New("subset may not be null"))
continue
}
if subsets.InsertContains(subset.Name) {
v = AppendValidation(v, fmt.Errorf("duplicate subset names: %s", subset.Name))
}
v = AppendValidation(v, validateSubset(subset))
}
v = AppendValidation(v,
validateExportTo(cfg.Namespace, rule.ExportTo, false, rule.GetWorkloadSelector() != nil))
v = AppendValidation(v, validateWorkloadSelector(rule.GetWorkloadSelector()))
return v.Unwrap()
})
func validateExportTo(namespace string, exportTo []string, isServiceEntry bool, isDestinationRuleWithSelector bool) (errs error) {
if len(exportTo) > 0 {
// Make sure there are no duplicates
exportToSet := sets.New[string]()
for _, e := range exportTo {
key := e
if visibility.Instance(e) == visibility.Private {
// substitute this with the current namespace so that we
// can check for duplicates like ., namespace
key = namespace
}
if exportToSet.Contains(key) {
if key != e {
errs = appendErrors(errs, fmt.Errorf("duplicate entries in exportTo: . and current namespace %s", namespace))
} else {
errs = appendErrors(errs, fmt.Errorf("duplicate entries in exportTo for entry %s", e))
}
} else {
// if this is a serviceEntry, allow ~ in exportTo as it can be used to create
// a service that is not even visible within the local namespace to anyone other
// than the proxies of that service.
if isServiceEntry && visibility.Instance(e) == visibility.None {
exportToSet.Insert(key)
} else {
if err := visibility.Instance(key).Validate(); err != nil {
errs = appendErrors(errs, err)
} else {
exportToSet.Insert(key)
}
}
}
}
// Make sure workloadSelector based destination rule does not use exportTo other than current namespace
if isDestinationRuleWithSelector && !exportToSet.IsEmpty() {
if exportToSet.Contains(namespace) {
if exportToSet.Len() > 1 {
errs = appendErrors(errs, fmt.Errorf("destination rule with workload selector cannot have multiple entries in exportTo"))
}
} else {
errs = appendErrors(errs, fmt.Errorf("destination rule with workload selector cannot have exportTo beyond current namespace"))
}
}
// Make sure we have only one of . or *
if exportToSet.Contains(string(visibility.Public)) {
// make sure that there are no other entries in the exportTo
// i.e. no point in saying ns1,ns2,*. Might as well say *
if len(exportTo) > 1 {
errs = appendErrors(errs, fmt.Errorf("cannot have both public (*) and non-public exportTo values for a resource"))
}
}
// if this is a service entry, then we need to disallow * and ~ together. Or ~ and other namespaces
if exportToSet.Contains(string(visibility.None)) {
if len(exportTo) > 1 {
errs = appendErrors(errs, fmt.Errorf("cannot export service entry to no one (~) and someone"))
}
}
}
return
}
func ValidateAlphaWorkloadSelector(selector *networking.WorkloadSelector) (Warning, error) {
var errs error
var warning Warning
if selector != nil {
for k, v := range selector.Labels {
if k == "" {
errs = appendErrors(errs,
fmt.Errorf("empty key is not supported in selector: %q", fmt.Sprintf("%s=%s", k, v)))
}
if strings.Contains(k, "*") || strings.Contains(v, "*") {
errs = appendErrors(errs,
fmt.Errorf("wildcard is not supported in selector: %q", fmt.Sprintf("%s=%s", k, v)))
}
}
if len(selector.Labels) == 0 {
warning = fmt.Errorf("workload selector specified without labels") // nolint: stylecheck
}
}
return warning, errs
}
// validates that hostname in ns/<hostname> is a valid hostname according to
// API specs
func validateSidecarOrGatewayHostnamePart(hostname string, isGateway bool) (errs error) {
// short name hosts are not allowed
if hostname != "*" && !strings.Contains(hostname, ".") {
errs = appendErrors(errs, fmt.Errorf("short names (non FQDN) are not allowed"))
}
if err := ValidateWildcardDomain(hostname); err != nil {
if !isGateway {
errs = appendErrors(errs, err)
}
// Gateway allows IP as the host string, as well
if !netutil.IsValidIPAddress(hostname) {
errs = appendErrors(errs, err)
}
}
// partial wildcard is not allowed
// More details please refer to:
// Gateway: https://istio.io/latest/docs/reference/config/networking/gateway/
// SideCar: https://istio.io/latest/docs/reference/config/networking/sidecar/#IstioEgressListener
errs = appendErrors(errs, validatePartialWildCard(hostname))
return
}
func validateNamespaceSlashWildcardHostname(hostname string, isGateway bool, gatewaySemantics bool) (errs error) {
parts := strings.SplitN(hostname, "/", 2)
if len(parts) != 2 {
if isGateway {
// Old style host in the gateway
return validateSidecarOrGatewayHostnamePart(hostname, true)
}
errs = appendErrors(errs, fmt.Errorf("host must be of form namespace/dnsName"))
return
}
if len(parts[0]) == 0 || len(parts[1]) == 0 {
errs = appendErrors(errs, fmt.Errorf("config namespace and dnsName in host entry cannot be empty"))
}
if !isGateway {
// namespace can be * or . or ~ or a valid DNS label in sidecars
if parts[0] != "*" && parts[0] != "." && parts[0] != "~" {
if !labels.IsDNS1123Label(parts[0]) {
errs = appendErrors(errs, fmt.Errorf("invalid namespace value %q in sidecar", parts[0]))
}
}
} else {
// namespace can be * or . or a valid DNS label in gateways
// namespace can be ~ in gateways converted from Gateway API when no routes match
if parts[0] != "*" && parts[0] != "." && (parts[0] != "~" || !gatewaySemantics) {
if !labels.IsDNS1123Label(parts[0]) {
errs = appendErrors(errs, fmt.Errorf("invalid namespace value %q in gateway", parts[0]))
}
}
}
errs = appendErrors(errs, validateSidecarOrGatewayHostnamePart(parts[1], isGateway))
return
}
// ValidateSidecar checks sidecar config supplied by user
var ValidateSidecar = RegisterValidateFunc("ValidateSidecar",
func(cfg config.Config) (Warning, error) {
errs := Validation{}
rule, ok := cfg.Spec.(*networking.Sidecar)
if !ok {
return nil, fmt.Errorf("cannot cast to Sidecar")
}
warning, err := ValidateAlphaWorkloadSelector(rule.WorkloadSelector)
if err != nil {
return nil, err
}
// If workloadSelector is defined and labels are not set, it is most likely
// an user error. Marking it as a warning to keep it backwards compatible.
if warning != nil {
errs = AppendValidation(errs, WrapWarning(fmt.Errorf("sidecar: %s, will be applied to all services in namespace",
warning))) // nolint: stylecheck
}
if len(rule.Egress) == 0 && len(rule.Ingress) == 0 && rule.OutboundTrafficPolicy == nil && rule.InboundConnectionPool == nil {
return nil, fmt.Errorf("sidecar: empty configuration provided")
}
portMap := sets.Set[uint32]{}
for _, i := range rule.Ingress {
if i == nil {
errs = AppendValidation(errs, fmt.Errorf("sidecar: ingress may not be null"))
continue
}
if i.Port == nil {
errs = AppendValidation(errs, fmt.Errorf("sidecar: port is required for ingress listeners"))
continue
}
// nolint: staticcheck
if i.Port.TargetPort > 0 {
errs = AppendValidation(errs, fmt.Errorf("targetPort has no impact on Sidecars"))
}
bind := i.GetBind()
errs = AppendValidation(errs, validateSidecarIngressPortAndBind(i.Port, bind))
if portMap.Contains(i.Port.Number) {
errs = AppendValidation(errs, fmt.Errorf("sidecar: ports on IP bound listeners must be unique"))
}
portMap.Insert(i.Port.Number)
if len(i.DefaultEndpoint) != 0 {
if strings.HasPrefix(i.DefaultEndpoint, UnixAddressPrefix) {
errs = AppendValidation(errs, ValidateUnixAddress(strings.TrimPrefix(i.DefaultEndpoint, UnixAddressPrefix)))
} else {
// format should be 127.0.0.1:port, [::1]:port or :port
sHost, sPort, sErr := net.SplitHostPort(i.DefaultEndpoint)
if sErr != nil {
errs = AppendValidation(errs, sErr)
}
if sHost != "" && sHost != "127.0.0.1" && sHost != "0.0.0.0" && sHost != "::1" && sHost != "::" {
errMsg := "sidecar: defaultEndpoint must be of form 127.0.0.1:<port>,0.0.0.0:<port>,[::1]:port,[::]:port,unix://filepath or unset"
errs = AppendValidation(errs, fmt.Errorf(errMsg))
}
port, err := strconv.Atoi(sPort)
if err != nil {
errs = AppendValidation(errs, fmt.Errorf("sidecar: defaultEndpoint port (%s) is not a number: %v", sPort, err))
} else {
errs = AppendValidation(errs, ValidatePort(port))
}
}
}
if i.Tls != nil {
if len(i.Tls.SubjectAltNames) > 0 {
errs = AppendValidation(errs, fmt.Errorf("sidecar: subjectAltNames is not supported in ingress tls"))
}
if i.Tls.HttpsRedirect {
errs = AppendValidation(errs, fmt.Errorf("sidecar: httpsRedirect is not supported"))
}
if i.Tls.CredentialName != "" {
errs = AppendValidation(errs, fmt.Errorf("sidecar: credentialName is not currently supported"))
}
if i.Tls.Mode == networking.ServerTLSSettings_ISTIO_MUTUAL || i.Tls.Mode == networking.ServerTLSSettings_AUTO_PASSTHROUGH {
errs = AppendValidation(errs, fmt.Errorf("configuration is invalid: cannot set mode to %s in sidecar ingress tls", i.Tls.Mode.String()))
}
protocol := protocol.Parse(i.Port.Protocol)
if !protocol.IsTLS() {
errs = AppendValidation(errs, fmt.Errorf("server cannot have TLS settings for non HTTPS/TLS ports"))
}
errs = AppendValidation(errs, validateTLSOptions(i.Tls))
}
// Validate per-port connection pool settings
errs = AppendValidation(errs, validateConnectionPool(i.ConnectionPool))
if i.ConnectionPool != nil && i.ConnectionPool.Http != nil && i.Port != nil && !protocol.Parse(i.Port.Protocol).IsHTTP() {
errs = AppendWarningf(errs,
"sidecar: HTTP connection pool settings are configured for port %d (%q) but its protocol is not HTTP (%s); only TCP settings will apply",
i.Port.Number, i.Port.Name, i.Port.Protocol)
}
}
// Validate top-level connection pool setting
errs = AppendValidation(errs, validateConnectionPool(rule.InboundConnectionPool))
portMap = sets.Set[uint32]{}
udsMap := sets.String{}
catchAllEgressListenerFound := false
for index, egress := range rule.Egress {
if egress == nil {
errs = AppendValidation(errs, errors.New("egress listener may not be null"))
continue
}
// there can be only one catch all egress listener with empty port, and it should be the last listener.
if egress.Port == nil {
if !catchAllEgressListenerFound {
if index == len(rule.Egress)-1 {
catchAllEgressListenerFound = true
} else {
errs = AppendValidation(errs, fmt.Errorf("sidecar: the egress listener with empty port should be the last listener in the list"))
}
} else {
errs = AppendValidation(errs, fmt.Errorf("sidecar: egress can have only one listener with empty port"))
continue
}
} else {
// nolint: staticcheck
if egress.Port.TargetPort > 0 {
errs = AppendValidation(errs, fmt.Errorf("targetPort has no impact on Sidecars"))
}
bind := egress.GetBind()
captureMode := egress.GetCaptureMode()
errs = AppendValidation(errs, validateSidecarEgressPortBindAndCaptureMode(egress.Port, bind, captureMode))
if egress.Port.Number == 0 {
if _, found := udsMap[bind]; found {
errs = AppendValidation(errs, fmt.Errorf("sidecar: unix domain socket values for listeners must be unique"))
}
udsMap[bind] = struct{}{}
} else {
if portMap.Contains(egress.Port.Number) {
errs = AppendValidation(errs, fmt.Errorf("sidecar: ports on IP bound listeners must be unique"))
}
portMap.Insert(egress.Port.Number)
}
}
// validate that the hosts field is a slash separated value
// of form ns1/host, or */host, or */*, or ns1/*, or ns1/*.example.com
if len(egress.Hosts) == 0 {
errs = AppendValidation(errs, fmt.Errorf("sidecar: egress listener must contain at least one host"))
} else {
nssSvcs := map[string]map[string]bool{}
for _, hostname := range egress.Hosts {
parts := strings.SplitN(hostname, "/", 2)
if len(parts) == 2 {
ns := parts[0]
svc := parts[1]
if ns == "." {
ns = cfg.Namespace
}
if _, ok := nssSvcs[ns]; !ok {