-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
server.go
1806 lines (1641 loc) · 64.5 KB
/
server.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
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
package envoy
import (
"context"
"fmt"
"net"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
cilium "github.com/cilium/proxy/go/cilium/api"
envoy_mysql_proxy "github.com/cilium/proxy/go/contrib/envoy/extensions/filters/network/mysql_proxy/v3"
envoy_config_bootstrap "github.com/cilium/proxy/go/envoy/config/bootstrap/v3"
envoy_config_cluster "github.com/cilium/proxy/go/envoy/config/cluster/v3"
envoy_config_core "github.com/cilium/proxy/go/envoy/config/core/v3"
envoy_config_endpoint "github.com/cilium/proxy/go/envoy/config/endpoint/v3"
envoy_config_listener "github.com/cilium/proxy/go/envoy/config/listener/v3"
envoy_config_route "github.com/cilium/proxy/go/envoy/config/route/v3"
envoy_extensions_filters_http_router_v3 "github.com/cilium/proxy/go/envoy/extensions/filters/http/router/v3"
envoy_extensions_listener_tls_inspector_v3 "github.com/cilium/proxy/go/envoy/extensions/filters/listener/tls_inspector/v3"
envoy_config_http "github.com/cilium/proxy/go/envoy/extensions/filters/network/http_connection_manager/v3"
envoy_mongo_proxy "github.com/cilium/proxy/go/envoy/extensions/filters/network/mongo_proxy/v3"
envoy_config_tcp "github.com/cilium/proxy/go/envoy/extensions/filters/network/tcp_proxy/v3"
envoy_config_tls "github.com/cilium/proxy/go/envoy/extensions/transport_sockets/tls/v3"
envoy_config_upstream "github.com/cilium/proxy/go/envoy/extensions/upstreams/http/v3"
envoy_type_matcher "github.com/cilium/proxy/go/envoy/type/matcher/v3"
"github.com/sirupsen/logrus"
"golang.org/x/sys/unix"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/anypb"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/structpb"
"google.golang.org/protobuf/types/known/wrapperspb"
"github.com/cilium/cilium/pkg/bpf"
"github.com/cilium/cilium/pkg/completion"
"github.com/cilium/cilium/pkg/envoy/xds"
"github.com/cilium/cilium/pkg/ipcache"
"github.com/cilium/cilium/pkg/lock"
"github.com/cilium/cilium/pkg/logging/logfields"
"github.com/cilium/cilium/pkg/node"
"github.com/cilium/cilium/pkg/option"
"github.com/cilium/cilium/pkg/policy"
"github.com/cilium/cilium/pkg/policy/api"
"github.com/cilium/cilium/pkg/policy/api/kafka"
"github.com/cilium/cilium/pkg/proxy/logger"
"github.com/cilium/cilium/pkg/u8proto"
)
var (
// allowAllPortNetworkPolicy is a PortNetworkPolicy that allows all traffic
// to any L4 port.
allowAllTCPPortNetworkPolicy = &cilium.PortNetworkPolicy{
// Allow all TCP traffic to any port.
Protocol: envoy_config_core.SocketAddress_TCP,
}
allowAllPortNetworkPolicy = []*cilium.PortNetworkPolicy{
// Allow all TCP traffic to any port.
allowAllTCPPortNetworkPolicy,
// Allow all UDP traffic to any port.
// UDP rules not sent to Envoy for now.
}
)
const (
CiliumXDSClusterName = "xds-grpc-cilium"
adminClusterName = "envoy-admin"
egressClusterName = "egress-cluster"
egressTLSClusterName = "egress-cluster-tls"
ingressClusterName = "ingress-cluster"
ingressTLSClusterName = "ingress-cluster-tls"
metricsListenerName = "envoy-prometheus-metrics-listener"
)
type Listener struct {
// must hold the XDSServer.mutex when accessing 'count'
count uint
// mutex is needed when accessing the fields below.
// XDSServer.mutex is not needed, but if taken it must be taken before 'mutex'
mutex lock.RWMutex
acked bool
nacked bool
waiters []*completion.Completion
}
// XDSServer provides a high-lever interface to manage resources published
// using the xDS gRPC API.
type XDSServer struct {
// socketPath is the path to the gRPC UNIX domain socket.
socketPath string
// accessLogPath is the path to the L7 access logs
accessLogPath string
// mutex protects accesses to the configuration resources below.
mutex lock.RWMutex
// listenerMutator publishes listener updates to Envoy proxies.
// Manages it's own locking
listenerMutator xds.AckingResourceMutator
// routeMutator publishes route updates to Envoy proxies.
// Manages it's own locking
routeMutator xds.AckingResourceMutator
// clusterMutator publishes cluster updates to Envoy proxies.
// Manages it's own locking
clusterMutator xds.AckingResourceMutator
// endpointMutator publishes endpoint updates to Envoy proxies.
// Manages it's own locking
endpointMutator xds.AckingResourceMutator
// secretMutator publishes secret updates to Envoy proxies.
// Manages it's own locking
secretMutator xds.AckingResourceMutator
// listeners is the set of names of listeners that have been added by
// calling AddListener.
// mutex must be held when accessing this.
// Value holds the number of redirects using the listener named by the key.
listeners map[string]*Listener
// proxyListeners is the count of redirection proxy listeners in 'listeners'.
// When this is zero, cilium should not wait for NACKs/ACKs from envoy.
// This value is different from len(listeners) due to non-proxy listeners
// (e.g., prometheus listener)
proxyListeners int
// networkPolicyCache publishes network policy configuration updates to
// Envoy proxies.
networkPolicyCache *xds.Cache
// NetworkPolicyMutator wraps networkPolicyCache to publish policy
// updates to Envoy proxies.
// Exported for testing only!
NetworkPolicyMutator xds.AckingResourceMutator
// networkPolicyEndpoints maps endpoint IP to the info on the local endpoint.
// mutex must be held when accessing this.
networkPolicyEndpoints map[string]logger.EndpointUpdater
// stopServer stops the xDS gRPC server.
stopServer context.CancelFunc
}
func getXDSPath(stateDir string) string {
return filepath.Join(stateDir, "xds.sock")
}
func toAny(pb proto.Message) *anypb.Any {
a, err := anypb.New(pb)
if err != nil {
panic(err.Error())
}
return a
}
// StartXDSServer configures and starts the xDS GRPC server.
func StartXDSServer(ipcache *ipcache.IPCache, stateDir string) *XDSServer {
xdsPath := getXDSPath(stateDir)
os.Remove(xdsPath)
socketListener, err := net.ListenUnix("unix", &net.UnixAddr{Name: xdsPath, Net: "unix"})
if err != nil {
log.WithError(err).Fatalf("Envoy: Failed to open xDS listen socket at %s", xdsPath)
}
// Make the socket accessible by owner and group only. Group access is needed for Istio
// sidecar proxies.
if err = os.Chmod(xdsPath, 0660); err != nil {
log.WithError(err).Fatalf("Envoy: Failed to change mode of xDS listen socket at %s", xdsPath)
}
// Change the group to ProxyGID allowing access from any process from that group.
if err = os.Chown(xdsPath, -1, option.Config.ProxyGID); err != nil {
log.WithError(err).Warningf("Envoy: Failed to change the group of xDS listen socket at %s, sidecar proxies may not work", xdsPath)
}
ldsCache := xds.NewCache()
ldsMutator := xds.NewAckingResourceMutatorWrapper(ldsCache)
ldsConfig := &xds.ResourceTypeConfiguration{
Source: ldsCache,
AckObserver: ldsMutator,
}
rdsCache := xds.NewCache()
rdsMutator := xds.NewAckingResourceMutatorWrapper(rdsCache)
rdsConfig := &xds.ResourceTypeConfiguration{
Source: rdsCache,
AckObserver: rdsMutator,
}
cdsCache := xds.NewCache()
cdsMutator := xds.NewAckingResourceMutatorWrapper(cdsCache)
cdsConfig := &xds.ResourceTypeConfiguration{
Source: cdsCache,
AckObserver: cdsMutator,
}
edsCache := xds.NewCache()
edsMutator := xds.NewAckingResourceMutatorWrapper(edsCache)
edsConfig := &xds.ResourceTypeConfiguration{
Source: edsCache,
AckObserver: edsMutator,
}
sdsCache := xds.NewCache()
sdsMutator := xds.NewAckingResourceMutatorWrapper(sdsCache)
sdsConfig := &xds.ResourceTypeConfiguration{
Source: sdsCache,
AckObserver: sdsMutator,
}
npdsCache := xds.NewCache()
npdsMutator := xds.NewAckingResourceMutatorWrapper(npdsCache)
npdsConfig := &xds.ResourceTypeConfiguration{
Source: npdsCache,
AckObserver: npdsMutator,
}
nphdsCache := newNPHDSCache(ipcache)
nphdsConfig := &xds.ResourceTypeConfiguration{
Source: nphdsCache,
AckObserver: &nphdsCache,
}
stopServer := startXDSGRPCServer(socketListener, map[string]*xds.ResourceTypeConfiguration{
ListenerTypeURL: ldsConfig,
RouteTypeURL: rdsConfig,
ClusterTypeURL: cdsConfig,
EndpointTypeURL: edsConfig,
SecretTypeURL: sdsConfig,
NetworkPolicyTypeURL: npdsConfig,
NetworkPolicyHostsTypeURL: nphdsConfig,
}, 5*time.Second)
return &XDSServer{
socketPath: xdsPath,
accessLogPath: getAccessLogPath(stateDir),
listenerMutator: ldsMutator,
listeners: make(map[string]*Listener),
routeMutator: rdsMutator,
clusterMutator: cdsMutator,
endpointMutator: edsMutator,
secretMutator: sdsMutator,
networkPolicyCache: npdsCache,
NetworkPolicyMutator: npdsMutator,
networkPolicyEndpoints: make(map[string]logger.EndpointUpdater),
stopServer: stopServer,
}
}
func getCiliumHttpFilter() *envoy_config_http.HttpFilter {
return &envoy_config_http.HttpFilter{
Name: "cilium.l7policy",
ConfigType: &envoy_config_http.HttpFilter_TypedConfig{
TypedConfig: toAny(&cilium.L7Policy{
AccessLogPath: getAccessLogPath(option.Config.RunDir),
Denied_403Body: option.Config.HTTP403Message,
}),
},
}
}
func (s *XDSServer) getHttpFilterChainProto(clusterName string, tls bool) *envoy_config_listener.FilterChain {
requestTimeout := int64(option.Config.HTTPRequestTimeout) // seconds
idleTimeout := int64(option.Config.HTTPIdleTimeout) // seconds
maxGRPCTimeout := int64(option.Config.HTTPMaxGRPCTimeout) // seconds
numRetries := uint32(option.Config.HTTPRetryCount)
retryTimeout := int64(option.Config.HTTPRetryTimeout) //seconds
hcmConfig := &envoy_config_http.HttpConnectionManager{
StatPrefix: "proxy",
UseRemoteAddress: &wrapperspb.BoolValue{Value: true},
SkipXffAppend: true,
HttpFilters: []*envoy_config_http.HttpFilter{
getCiliumHttpFilter(),
{
Name: "envoy.filters.http.router",
ConfigType: &envoy_config_http.HttpFilter_TypedConfig{
TypedConfig: toAny(&envoy_extensions_filters_http_router_v3.Router{}),
},
},
},
StreamIdleTimeout: &durationpb.Duration{}, // 0 == disabled
RouteSpecifier: &envoy_config_http.HttpConnectionManager_RouteConfig{
RouteConfig: &envoy_config_route.RouteConfiguration{
VirtualHosts: []*envoy_config_route.VirtualHost{{
Name: "default_route",
Domains: []string{"*"},
Routes: []*envoy_config_route.Route{{
Match: &envoy_config_route.RouteMatch{
PathSpecifier: &envoy_config_route.RouteMatch_Prefix{Prefix: "/"},
Grpc: &envoy_config_route.RouteMatch_GrpcRouteMatchOptions{},
},
Action: &envoy_config_route.Route_Route{
Route: &envoy_config_route.RouteAction{
ClusterSpecifier: &envoy_config_route.RouteAction_Cluster{
Cluster: clusterName,
},
Timeout: &durationpb.Duration{Seconds: requestTimeout},
MaxStreamDuration: &envoy_config_route.RouteAction_MaxStreamDuration{
GrpcTimeoutHeaderMax: &durationpb.Duration{Seconds: maxGRPCTimeout},
},
RetryPolicy: &envoy_config_route.RetryPolicy{
RetryOn: "5xx",
NumRetries: &wrapperspb.UInt32Value{Value: numRetries},
PerTryTimeout: &durationpb.Duration{Seconds: retryTimeout},
},
},
},
}, {
Match: &envoy_config_route.RouteMatch{
PathSpecifier: &envoy_config_route.RouteMatch_Prefix{Prefix: "/"},
},
Action: &envoy_config_route.Route_Route{
Route: &envoy_config_route.RouteAction{
ClusterSpecifier: &envoy_config_route.RouteAction_Cluster{
Cluster: clusterName,
},
Timeout: &durationpb.Duration{Seconds: requestTimeout},
//IdleTimeout: &durationpb.Duration{Seconds: idleTimeout},
RetryPolicy: &envoy_config_route.RetryPolicy{
RetryOn: "5xx",
NumRetries: &wrapperspb.UInt32Value{Value: numRetries},
PerTryTimeout: &durationpb.Duration{Seconds: retryTimeout},
},
},
},
}},
}},
},
},
}
if option.Config.HTTPNormalizePath {
hcmConfig.NormalizePath = &wrapperspb.BoolValue{Value: true}
hcmConfig.MergeSlashes = true
hcmConfig.PathWithEscapedSlashesAction = envoy_config_http.HttpConnectionManager_UNESCAPE_AND_REDIRECT
}
// Idle timeout can only be specified if non-zero
if idleTimeout > 0 {
hcmConfig.GetRouteConfig().VirtualHosts[0].Routes[1].GetRoute().IdleTimeout = &durationpb.Duration{Seconds: idleTimeout}
}
chain := &envoy_config_listener.FilterChain{
Filters: []*envoy_config_listener.Filter{{
Name: "cilium.network",
ConfigType: &envoy_config_listener.Filter_TypedConfig{
TypedConfig: toAny(&cilium.NetworkFilter{}),
},
}, {
Name: "envoy.filters.network.http_connection_manager",
ConfigType: &envoy_config_listener.Filter_TypedConfig{
TypedConfig: toAny(hcmConfig),
},
}},
}
if tls {
chain.FilterChainMatch = &envoy_config_listener.FilterChainMatch{
TransportProtocol: "tls",
}
chain.TransportSocket = &envoy_config_core.TransportSocket{
Name: "cilium.tls_wrapper",
ConfigType: &envoy_config_core.TransportSocket_TypedConfig{
TypedConfig: toAny(&cilium.DownstreamTlsWrapperContext{}),
},
}
}
return chain
}
// getTcpFilterChainProto creates a TCP filter chain with the Cilium network filter.
// By default, the returned chain can be used with the Cilium Go extensions L7 parsers
// in 'proxylib' directory in the Cilium repo.
// When optional 'filterName' is given, it is configured as the first filter in the chain
// and 'proxylib' is not configured. In this case the returned filter chain is only used
// if the applicable network policy specifies 'filterName' as the L7 parser.
func (s *XDSServer) getTcpFilterChainProto(clusterName string, filterName string, config *anypb.Any) *envoy_config_listener.FilterChain {
var filters []*envoy_config_listener.Filter
// 1. Add the filter 'filterName' to the beginning of the TCP chain with optional 'config', if needed.
if filterName != "" {
filter := &envoy_config_listener.Filter{Name: filterName}
if config != nil {
filter.ConfigType = &envoy_config_listener.Filter_TypedConfig{
TypedConfig: config,
}
}
filters = append(filters, filter)
}
// 2. Add Cilium Network filter.
var ciliumConfig *cilium.NetworkFilter
if filterName == "" {
// Use proxylib by default
ciliumConfig = &cilium.NetworkFilter{
Proxylib: "libcilium.so",
ProxylibParams: map[string]string{
"access-log-path": s.accessLogPath,
"xds-path": s.socketPath,
},
}
} else {
// Envoy metadata logging requires accesslog path
ciliumConfig = &cilium.NetworkFilter{
AccessLogPath: s.accessLogPath,
}
}
filters = append(filters, &envoy_config_listener.Filter{
Name: "cilium.network",
ConfigType: &envoy_config_listener.Filter_TypedConfig{
TypedConfig: toAny(ciliumConfig),
},
})
// 3. Add the TCP proxy filter.
filters = append(filters, &envoy_config_listener.Filter{
Name: "envoy.filters.network.tcp_proxy",
ConfigType: &envoy_config_listener.Filter_TypedConfig{
TypedConfig: toAny(&envoy_config_tcp.TcpProxy{
StatPrefix: "tcp_proxy",
ClusterSpecifier: &envoy_config_tcp.TcpProxy_Cluster{
Cluster: clusterName,
},
}),
},
})
chain := &envoy_config_listener.FilterChain{
Filters: filters,
FilterChainMatch: &envoy_config_listener.FilterChainMatch{
// must have transport match, otherwise TLS inspector will be automatically inserted
TransportProtocol: "raw_buffer",
},
}
if filterName != "" {
// Add filter chain match for 'filterName' so that connections for which policy says to use this L7
// are handled by this filter chain.
chain.FilterChainMatch.ApplicationProtocols = []string{filterName}
}
return chain
}
func getListenerAddress(port uint16, ipv4, ipv6 bool) *envoy_config_core.Address {
listenerAddr := "0.0.0.0"
if ipv6 {
listenerAddr = "::"
}
return &envoy_config_core.Address{
Address: &envoy_config_core.Address_SocketAddress{
SocketAddress: &envoy_config_core.SocketAddress{
Protocol: envoy_config_core.SocketAddress_TCP,
Address: listenerAddr,
Ipv4Compat: ipv4 && ipv6,
PortSpecifier: &envoy_config_core.SocketAddress_PortValue{PortValue: uint32(port)},
},
},
}
}
// AddMetricsListener adds a prometheus metrics listener to Envoy.
// We could do this in the bootstrap config, but then a failure to bind to the configured port
// would fail starting Envoy.
func (s *XDSServer) AddMetricsListener(port uint16, wg *completion.WaitGroup) {
if port == 0 {
return // 0 == disabled
}
log.WithField(logfields.Port, port).Debug("Envoy: AddMetricsListener")
s.addListener(metricsListenerName, func() *envoy_config_listener.Listener {
hcmConfig := &envoy_config_http.HttpConnectionManager{
StatPrefix: metricsListenerName,
UseRemoteAddress: &wrapperspb.BoolValue{Value: true},
SkipXffAppend: true,
HttpFilters: []*envoy_config_http.HttpFilter{{
Name: "envoy.filters.http.router",
ConfigType: &envoy_config_http.HttpFilter_TypedConfig{
TypedConfig: toAny(&envoy_extensions_filters_http_router_v3.Router{}),
},
}},
StreamIdleTimeout: &durationpb.Duration{}, // 0 == disabled
RouteSpecifier: &envoy_config_http.HttpConnectionManager_RouteConfig{
RouteConfig: &envoy_config_route.RouteConfiguration{
VirtualHosts: []*envoy_config_route.VirtualHost{{
Name: "prometheus_metrics_route",
Domains: []string{"*"},
Routes: []*envoy_config_route.Route{{
Match: &envoy_config_route.RouteMatch{
PathSpecifier: &envoy_config_route.RouteMatch_Prefix{Prefix: "/metrics"},
},
Action: &envoy_config_route.Route_Route{
Route: &envoy_config_route.RouteAction{
ClusterSpecifier: &envoy_config_route.RouteAction_Cluster{
Cluster: adminClusterName,
},
PrefixRewrite: "/stats/prometheus",
},
},
}},
}},
},
},
}
listenerConf := &envoy_config_listener.Listener{
Name: metricsListenerName,
Address: getListenerAddress(port, option.Config.IPv4Enabled(), option.Config.IPv6Enabled()),
FilterChains: []*envoy_config_listener.FilterChain{{
Filters: []*envoy_config_listener.Filter{{
Name: "envoy.filters.network.http_connection_manager",
ConfigType: &envoy_config_listener.Filter_TypedConfig{
TypedConfig: toAny(hcmConfig),
},
}},
}},
}
return listenerConf
}, wg, func(err error) {
if err != nil {
log.WithField(logfields.Port, port).WithError(err).Debug("Envoy: Adding metrics listener failed")
// Remove the added listener in case of a failure
s.removeListener(metricsListenerName, nil, false)
} else {
log.WithField(logfields.Port, port).Info("Envoy: Listening for prometheus metrics")
}
}, false)
}
// addListener either reuses an existing listener with 'name', or creates a new one.
// 'listenerConf()' is only called if a new listener is being created.
func (s *XDSServer) addListener(name string, listenerConf func() *envoy_config_listener.Listener, wg *completion.WaitGroup, cb func(err error), isProxyListener bool) {
s.mutex.Lock()
defer s.mutex.Unlock()
listener := s.listeners[name]
if listener == nil {
listener = &Listener{}
s.listeners[name] = listener
if isProxyListener {
s.proxyListeners++
}
}
listener.count++
listener.mutex.Lock() // needed for other than 'count'
if listener.count > 1 && !listener.nacked {
log.Debugf("Envoy: Reusing listener: %s", name)
if !listener.acked {
// Listener not acked yet, add a completion to the waiter's list
log.Debugf("Envoy: Waiting for a non-acknowledged reused listener: %s", name)
listener.waiters = append(listener.waiters, wg.AddCompletion())
}
listener.mutex.Unlock()
return
}
// Try again after a NACK, potentially with a different port number, etc.
if listener.nacked {
listener.acked = false
listener.nacked = false
}
listener.mutex.Unlock() // Listener locked again in callbacks below
listenerConfig := listenerConf()
if option.Config.EnableBPFTProxy {
// Envoy since 1.20.0 uses SO_REUSEPORT on listeners by default.
// BPF TPROXY is currently not compatible with SO_REUSEPORT, so disable it.
// Note that this may degrade Envoy performance.
listenerConfig.EnableReusePort = &wrapperspb.BoolValue{Value: false}
}
if err := listenerConfig.Validate(); err != nil {
log.Errorf("Envoy: Could not validate Listener (%s): %s", err, listenerConfig.String())
return
}
s.listenerMutator.Upsert(ListenerTypeURL, name, listenerConfig, []string{"127.0.0.1"}, wg,
func(err error) {
// listener might have already been removed, so we can't look again
// but we still need to complete all the completions in case
// someone is still waiting!
listener.mutex.Lock()
if err == nil {
// Allow future users to not need to wait
listener.acked = true
} else {
// Prevent further reuse of a failed listener
listener.nacked = true
}
// Pass the completion result to all the additional waiters.
for _, waiter := range listener.waiters {
waiter.Complete(err)
}
listener.waiters = nil
listener.mutex.Unlock()
if cb != nil {
cb(err)
}
})
}
// upsertListener either updates an existing LDS listener with 'name', or creates a new one.
func (s *XDSServer) upsertListener(name string, listenerConf *envoy_config_listener.Listener, wg *completion.WaitGroup, callback func(error)) xds.AckingResourceMutatorRevertFunc {
s.mutex.Lock()
defer s.mutex.Unlock()
// 'callback' is not called if there is no change and this configuration has already been acked.
return s.listenerMutator.Upsert(ListenerTypeURL, name, listenerConf, []string{"127.0.0.1"}, wg, callback)
}
// deleteListener deletes an LDS Envoy Listener.
func (s *XDSServer) deleteListener(name string, wg *completion.WaitGroup, callback func(error)) xds.AckingResourceMutatorRevertFunc {
s.mutex.Lock()
defer s.mutex.Unlock()
// 'callback' is not called if there is no change and this configuration has already been acked.
return s.listenerMutator.Delete(ListenerTypeURL, name, []string{"127.0.0.1"}, wg, callback)
}
// upsertRoute either updates an existing RDS route with 'name', or creates a new one.
func (s *XDSServer) upsertRoute(name string, conf *envoy_config_route.RouteConfiguration, wg *completion.WaitGroup, callback func(error)) xds.AckingResourceMutatorRevertFunc {
s.mutex.Lock()
defer s.mutex.Unlock()
// 'callback' is not called if there is no change and this configuration has already been acked.
return s.routeMutator.Upsert(RouteTypeURL, name, conf, []string{"127.0.0.1"}, wg, callback)
}
// deleteRoute deletes an RDS Route.
func (s *XDSServer) deleteRoute(name string, wg *completion.WaitGroup, callback func(error)) xds.AckingResourceMutatorRevertFunc {
s.mutex.Lock()
defer s.mutex.Unlock()
// 'callback' is not called if there is no change and this configuration has already been acked.
return s.routeMutator.Delete(RouteTypeURL, name, []string{"127.0.0.1"}, wg, callback)
}
// upsertCluster either updates an existing CDS cluster with 'name', or creates a new one.
func (s *XDSServer) upsertCluster(name string, conf *envoy_config_cluster.Cluster, wg *completion.WaitGroup, callback func(error)) xds.AckingResourceMutatorRevertFunc {
s.mutex.Lock()
defer s.mutex.Unlock()
// 'callback' is not called if there is no change and this configuration has already been acked.
return s.clusterMutator.Upsert(ClusterTypeURL, name, conf, []string{"127.0.0.1"}, wg, callback)
}
// deleteCluster deletes an CDS cluster.
func (s *XDSServer) deleteCluster(name string, wg *completion.WaitGroup, callback func(error)) xds.AckingResourceMutatorRevertFunc {
s.mutex.Lock()
defer s.mutex.Unlock()
// 'callback' is not called if there is no change and this configuration has already been acked.
return s.clusterMutator.Delete(ClusterTypeURL, name, []string{"127.0.0.1"}, wg, callback)
}
// upsertEndpoint either updates an existing EDS endpoint with 'name', or creates a new one.
func (s *XDSServer) upsertEndpoint(name string, conf *envoy_config_endpoint.ClusterLoadAssignment, wg *completion.WaitGroup, callback func(error)) xds.AckingResourceMutatorRevertFunc {
s.mutex.Lock()
defer s.mutex.Unlock()
// 'callback' is not called if there is no change and this configuration has already been acked.
return s.endpointMutator.Upsert(EndpointTypeURL, name, conf, []string{"127.0.0.1"}, wg, callback)
}
// deleteEndpoint deletes an EDS endpoint.
func (s *XDSServer) deleteEndpoint(name string, wg *completion.WaitGroup, callback func(error)) xds.AckingResourceMutatorRevertFunc {
s.mutex.Lock()
defer s.mutex.Unlock()
// 'callback' is not called if there is no change and this configuration has already been acked.
return s.endpointMutator.Delete(EndpointTypeURL, name, []string{"127.0.0.1"}, wg, callback)
}
// upsertSecret either updates an existing SDS secret with 'name', or creates a new one.
func (s *XDSServer) upsertSecret(name string, conf *envoy_config_tls.Secret, wg *completion.WaitGroup, callback func(error)) xds.AckingResourceMutatorRevertFunc {
s.mutex.Lock()
defer s.mutex.Unlock()
// 'callback' is not called if there is no change and this configuration has already been acked.
return s.secretMutator.Upsert(SecretTypeURL, name, conf, []string{"127.0.0.1"}, wg, callback)
}
// deleteSecret deletes an SDS secret.
func (s *XDSServer) deleteSecret(name string, wg *completion.WaitGroup, callback func(error)) xds.AckingResourceMutatorRevertFunc {
s.mutex.Lock()
defer s.mutex.Unlock()
// 'callback' is not called if there is no change and this configuration has already been acked.
return s.secretMutator.Delete(SecretTypeURL, name, []string{"127.0.0.1"}, wg, callback)
}
// 'l7lb' triggers the upstream mark to embed source pod EndpointID instead of source security ID
func getListenerFilter(isIngress bool, mayUseOriginalSourceAddr bool, l7lb bool) *envoy_config_listener.ListenerFilter {
conf := &cilium.BpfMetadata{
IsIngress: isIngress,
MayUseOriginalSourceAddress: mayUseOriginalSourceAddr,
BpfRoot: bpf.GetMapRoot(),
EgressMarkSourceEndpointId: l7lb,
}
// Set Ingress source addresses if configuring for L7 LB
if l7lb {
ingressIPv4 := node.GetIngressIPv4()
if ingressIPv4 != nil {
conf.Ipv4SourceAddress = ingressIPv4.String()
}
ingressIPv6 := node.GetIngressIPv6()
if ingressIPv6 != nil {
conf.Ipv6SourceAddress = ingressIPv6.String()
}
log.Debugf("cilium.bpf_metadata: ipv4_source_address: %s", conf.GetIpv4SourceAddress())
log.Debugf("cilium.bpf_metadata: ipv6_source_address: %s", conf.GetIpv6SourceAddress())
}
return &envoy_config_listener.ListenerFilter{
Name: "cilium.bpf_metadata",
ConfigType: &envoy_config_listener.ListenerFilter_TypedConfig{
TypedConfig: toAny(conf),
},
}
}
func getListenerSocketMarkOption(isIngress bool) *envoy_config_core.SocketOption {
socketMark := int64(0xB00)
if isIngress {
socketMark = 0xA00
}
return &envoy_config_core.SocketOption{
Description: "Listener socket mark",
Level: unix.SOL_SOCKET,
Name: unix.SO_MARK,
Value: &envoy_config_core.SocketOption_IntValue{IntValue: socketMark},
State: envoy_config_core.SocketOption_STATE_PREBIND,
}
}
func (s *XDSServer) getListenerConf(name string, kind policy.L7ParserType, port uint16, isIngress bool, mayUseOriginalSourceAddr bool) *envoy_config_listener.Listener {
clusterName := egressClusterName
if isIngress {
clusterName = ingressClusterName
}
listenerConf := &envoy_config_listener.Listener{
Name: name,
Address: getListenerAddress(port, option.Config.IPv4Enabled(), option.Config.IPv6Enabled()),
Transparent: &wrapperspb.BoolValue{Value: true},
SocketOptions: []*envoy_config_core.SocketOption{
getListenerSocketMarkOption(isIngress),
},
// FilterChains: []*envoy_config_listener.FilterChain
ListenerFilters: []*envoy_config_listener.ListenerFilter{
getListenerFilter(isIngress, mayUseOriginalSourceAddr, false),
},
}
// Add filter chains
if kind == policy.ParserTypeHTTP {
// Use tls_inspector only with HTTP, insert as the first filter
listenerConf.ListenerFilters = append([]*envoy_config_listener.ListenerFilter{{
Name: "envoy.filters.listener.tls_inspector",
ConfigType: &envoy_config_listener.ListenerFilter_TypedConfig{
TypedConfig: toAny(&envoy_extensions_listener_tls_inspector_v3.TlsInspector{}),
},
}}, listenerConf.ListenerFilters...)
listenerConf.FilterChains = append(listenerConf.FilterChains, s.getHttpFilterChainProto(clusterName, false))
// Add a TLS variant
tlsClusterName := egressTLSClusterName
if isIngress {
tlsClusterName = ingressTLSClusterName
}
listenerConf.FilterChains = append(listenerConf.FilterChains, s.getHttpFilterChainProto(tlsClusterName, true))
} else {
// Default TCP chain, takes care of all parsers in proxylib
listenerConf.FilterChains = append(listenerConf.FilterChains, s.getTcpFilterChainProto(clusterName, "", nil))
// Experimental TCP chain for MySQL 5.x
listenerConf.FilterChains = append(listenerConf.FilterChains, s.getTcpFilterChainProto(clusterName,
"envoy.filters.network.mysql_proxy", toAny(&envoy_mysql_proxy.MySQLProxy{
StatPrefix: "mysql",
})))
// Experimental TCP chain for MongoDB
listenerConf.FilterChains = append(listenerConf.FilterChains, s.getTcpFilterChainProto(clusterName,
"envoy.filters.network.mongo_proxy", toAny(&envoy_mongo_proxy.MongoProxy{
StatPrefix: "mongo",
EmitDynamicMetadata: true,
})))
}
return listenerConf
}
// AddListener adds a listener to a running Envoy proxy.
func (s *XDSServer) AddListener(name string, kind policy.L7ParserType, port uint16, isIngress bool, mayUseOriginalSourceAddr bool, wg *completion.WaitGroup) {
log.Debugf("Envoy: %s AddListener %s (mayUseOriginalSourceAddr: %v)", kind, name, mayUseOriginalSourceAddr)
s.addListener(name, func() *envoy_config_listener.Listener {
return s.getListenerConf(name, kind, port, isIngress, mayUseOriginalSourceAddr)
}, wg, nil, true)
}
// RemoveListener removes an existing Envoy Listener.
func (s *XDSServer) RemoveListener(name string, wg *completion.WaitGroup) xds.AckingResourceMutatorRevertFunc {
return s.removeListener(name, wg, true)
}
// removeListener removes an existing Envoy Listener.
func (s *XDSServer) removeListener(name string, wg *completion.WaitGroup, isProxyListener bool) xds.AckingResourceMutatorRevertFunc {
log.Debugf("Envoy: RemoveListener %s", name)
var listenerRevertFunc xds.AckingResourceMutatorRevertFunc
s.mutex.Lock()
listener, ok := s.listeners[name]
if ok && listener != nil {
listener.count--
if listener.count == 0 {
if isProxyListener {
s.proxyListeners--
}
delete(s.listeners, name)
listenerRevertFunc = s.listenerMutator.Delete(ListenerTypeURL, name, []string{"127.0.0.1"}, wg, nil)
}
} else {
// Bail out if this listener does not exist
log.Fatalf("Envoy: Attempt to remove non-existent listener: %s", name)
}
s.mutex.Unlock()
return func(completion *completion.Completion) {
s.mutex.Lock()
if listenerRevertFunc != nil {
listenerRevertFunc(completion)
if isProxyListener {
s.proxyListeners++
}
}
listener.count++
s.listeners[name] = listener
s.mutex.Unlock()
}
}
func (s *XDSServer) stop() {
s.stopServer()
os.Remove(s.socketPath)
}
func getL7Rules(l7Rules []api.PortRuleL7, l7Proto string) *cilium.L7NetworkPolicyRules {
allowRules := make([]*cilium.L7NetworkPolicyRule, 0, len(l7Rules))
denyRules := make([]*cilium.L7NetworkPolicyRule, 0, len(l7Rules))
useEnvoyMetadataMatcher := false
if strings.HasPrefix(l7Proto, "envoy.") {
useEnvoyMetadataMatcher = true
}
for _, l7 := range l7Rules {
if useEnvoyMetadataMatcher {
envoyFilterName := l7Proto
rule := &cilium.L7NetworkPolicyRule{MetadataRule: make([]*envoy_type_matcher.MetadataMatcher, 0, len(l7))}
denyRule := false
for k, v := range l7 {
switch k {
case "action":
switch v {
case "deny":
denyRule = true
}
default:
// map key to path segments and value to value matcher
// For now only one path segment is allowed
segments := strings.Split(k, "/")
var path []*envoy_type_matcher.MetadataMatcher_PathSegment
for _, key := range segments {
path = append(path, &envoy_type_matcher.MetadataMatcher_PathSegment{
Segment: &envoy_type_matcher.MetadataMatcher_PathSegment_Key{Key: key},
})
}
var value *envoy_type_matcher.ValueMatcher
if len(v) == 0 {
value = &envoy_type_matcher.ValueMatcher{
MatchPattern: &envoy_type_matcher.ValueMatcher_PresentMatch{
PresentMatch: true,
}}
} else {
value = &envoy_type_matcher.ValueMatcher{
MatchPattern: &envoy_type_matcher.ValueMatcher_ListMatch{
ListMatch: &envoy_type_matcher.ListMatcher{
MatchPattern: &envoy_type_matcher.ListMatcher_OneOf{
OneOf: &envoy_type_matcher.ValueMatcher{
MatchPattern: &envoy_type_matcher.ValueMatcher_StringMatch{
StringMatch: &envoy_type_matcher.StringMatcher{
MatchPattern: &envoy_type_matcher.StringMatcher_Exact{
Exact: v,
},
IgnoreCase: false,
},
},
},
},
},
}}
}
rule.MetadataRule = append(rule.MetadataRule, &envoy_type_matcher.MetadataMatcher{
Filter: envoyFilterName,
Path: path,
Value: value,
})
}
}
if denyRule {
denyRules = append(denyRules, rule)
} else {
allowRules = append(allowRules, rule)
}
} else {
// proxylib go extension key/value policy
rule := &cilium.L7NetworkPolicyRule{Rule: make(map[string]string, len(l7))}
for k, v := range l7 {
rule.Rule[k] = v
}
allowRules = append(allowRules, rule)
}
}
rules := &cilium.L7NetworkPolicyRules{}
if len(allowRules) > 0 {
rules.L7AllowRules = allowRules
}
if len(denyRules) > 0 {
rules.L7DenyRules = denyRules
}
return rules
}
func getKafkaL7Rules(l7Rules []kafka.PortRule) *cilium.KafkaNetworkPolicyRules {
allowRules := make([]*cilium.KafkaNetworkPolicyRule, 0, len(l7Rules))
for _, kr := range l7Rules {
rule := &cilium.KafkaNetworkPolicyRule{
ApiVersion: kr.GetAPIVersion(),
ApiKeys: kr.GetAPIKeys(),
ClientId: kr.ClientID,
Topic: kr.Topic,
}
allowRules = append(allowRules, rule)
}
rules := &cilium.KafkaNetworkPolicyRules{}
if len(allowRules) > 0 {
rules.KafkaRules = allowRules
}
return rules
}
func getSecretString(certManager policy.CertificateManager, hdr *api.HeaderMatch, ns string) (string, error) {
value := ""
var err error
if hdr.Secret != nil {
if certManager == nil {
err = fmt.Errorf("HeaderMatches: Nil certManager")
} else {
value, err = certManager.GetSecretString(context.TODO(), hdr.Secret, ns)
}
}
// Only use Value if secret was not obtained
if value == "" && hdr.Value != "" {
value = hdr.Value
if err != nil {
log.WithError(err).Debug("HeaderMatches: Using a default value due to k8s secret not being available")
err = nil
}
}
return value, err
}
func getHTTPRule(certManager policy.CertificateManager, h *api.PortRuleHTTP, ns string) (*cilium.HttpNetworkPolicyRule, bool) {
// Count the number of header matches we need
cnt := len(h.Headers) + len(h.HeaderMatches)
if h.Path != "" {
cnt++
}
if h.Method != "" {
cnt++
}
if h.Host != "" {
cnt++
}
googleRe2 := &envoy_type_matcher.RegexMatcher_GoogleRe2{GoogleRe2: &envoy_type_matcher.RegexMatcher_GoogleRE2{}}
headers := make([]*envoy_config_route.HeaderMatcher, 0, cnt)
if h.Path != "" {
headers = append(headers, &envoy_config_route.HeaderMatcher{
Name: ":path",
HeaderMatchSpecifier: &envoy_config_route.HeaderMatcher_SafeRegexMatch{
SafeRegexMatch: &envoy_type_matcher.RegexMatcher{