-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
server.go
1188 lines (1072 loc) · 39.6 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
// Copyright 2018 Authors of Cilium
//
// 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 envoy
import (
"context"
"fmt"
"io/ioutil"
"net"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/cilium/cilium/pkg/bpf"
"github.com/cilium/cilium/pkg/completion"
"github.com/cilium/cilium/pkg/envoy/xds"
"github.com/cilium/cilium/pkg/identity"
"github.com/cilium/cilium/pkg/lock"
"github.com/cilium/cilium/pkg/logging/logfields"
"github.com/cilium/cilium/pkg/option"
"github.com/cilium/cilium/pkg/policy"
"github.com/cilium/cilium/pkg/policy/api"
"github.com/cilium/cilium/pkg/proxy/logger"
cilium "github.com/cilium/proxy/go/cilium/api"
envoy_api_v2 "github.com/cilium/proxy/go/envoy/api/v2"
envoy_api_v2_core "github.com/cilium/proxy/go/envoy/api/v2/core"
envoy_api_v2_endpoint "github.com/cilium/proxy/go/envoy/api/v2/endpoint"
envoy_api_v2_listener "github.com/cilium/proxy/go/envoy/api/v2/listener"
envoy_api_v2_route "github.com/cilium/proxy/go/envoy/api/v2/route"
envoy_config_bootstrap_v2 "github.com/cilium/proxy/go/envoy/config/bootstrap/v2"
envoy_config_http "github.com/cilium/proxy/go/envoy/config/filter/network/http_connection_manager/v2"
envoy_config_tcp "github.com/cilium/proxy/go/envoy/config/filter/network/tcp_proxy/v2"
envoy_type_matcher "github.com/cilium/proxy/go/envoy/type/matcher"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/ptypes"
"github.com/golang/protobuf/ptypes/any"
"github.com/golang/protobuf/ptypes/duration"
"github.com/golang/protobuf/ptypes/wrappers"
"golang.org/x/sys/unix"
)
var (
// allowAllPortNetworkPolicy is a PortNetworkPolicy that allows all traffic
// to any L4 port.
allowAllPortNetworkPolicy = []*cilium.PortNetworkPolicy{
// Allow all TCP traffic to any port.
{Protocol: envoy_api_v2_core.SocketAddress_TCP},
// Allow all UDP traffic to any port.
{Protocol: envoy_api_v2_core.SocketAddress_UDP},
}
)
const (
egressClusterName = "egress-cluster"
egressTLSClusterName = "egress-cluster-tls"
ingressClusterName = "ingress-cluster"
ingressTLSClusterName = "ingress-cluster-tls"
EnvoyTimeout = 300 * time.Second // must be smaller than endpoint.EndpointGenerationTimeout
)
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
// 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
// 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 each network policy's name 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) *any.Any {
a, err := ptypes.MarshalAny(pb)
if err != nil {
panic(err.Error())
}
return a
}
// StartXDSServer configures and starts the xDS GRPC server.
func StartXDSServer(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 non-root Envoy proxies, e.g. running in
// sidecar containers.
if err = os.Chmod(xdsPath, 0777); err != nil {
log.WithError(err).Fatalf("Envoy: Failed to change mode of xDS listen socket at %s", xdsPath)
}
ldsCache := xds.NewCache()
ldsMutator := xds.NewAckingResourceMutatorWrapper(ldsCache)
ldsConfig := &xds.ResourceTypeConfiguration{
Source: ldsCache,
AckObserver: ldsMutator,
}
npdsCache := xds.NewCache()
npdsMutator := xds.NewAckingResourceMutatorWrapper(npdsCache)
npdsConfig := &xds.ResourceTypeConfiguration{
Source: npdsCache,
AckObserver: npdsMutator,
}
nphdsConfig := &xds.ResourceTypeConfiguration{
Source: NetworkPolicyHostsCache,
AckObserver: &NetworkPolicyHostsCache,
}
stopServer := startXDSGRPCServer(socketListener, ldsConfig, npdsConfig, nphdsConfig, 5*time.Second)
return &XDSServer{
socketPath: xdsPath,
accessLogPath: getAccessLogPath(stateDir),
listenerMutator: ldsMutator,
listeners: make(map[string]*Listener),
networkPolicyCache: npdsCache,
NetworkPolicyMutator: npdsMutator,
networkPolicyEndpoints: make(map[string]logger.EndpointUpdater),
stopServer: stopServer,
}
}
func (s *XDSServer) getHttpFilterChainProto(clusterName string, tls bool) *envoy_api_v2_listener.FilterChain {
denied403body := option.Config.HTTP403Message
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",
HttpFilters: []*envoy_config_http.HttpFilter{{
Name: "cilium.l7policy",
ConfigType: &envoy_config_http.HttpFilter_TypedConfig{
TypedConfig: toAny(&cilium.L7Policy{
AccessLogPath: s.accessLogPath,
Denied_403Body: denied403body,
}),
},
}, {
Name: "envoy.router",
}},
StreamIdleTimeout: &duration.Duration{}, // 0 == disabled
RouteSpecifier: &envoy_config_http.HttpConnectionManager_RouteConfig{
RouteConfig: &envoy_api_v2.RouteConfiguration{
VirtualHosts: []*envoy_api_v2_route.VirtualHost{{
Name: "default_route",
Domains: []string{"*"},
Routes: []*envoy_api_v2_route.Route{{
Match: &envoy_api_v2_route.RouteMatch{
PathSpecifier: &envoy_api_v2_route.RouteMatch_Prefix{Prefix: "/"},
Grpc: &envoy_api_v2_route.RouteMatch_GrpcRouteMatchOptions{},
},
Action: &envoy_api_v2_route.Route_Route{
Route: &envoy_api_v2_route.RouteAction{
ClusterSpecifier: &envoy_api_v2_route.RouteAction_Cluster{
Cluster: clusterName,
},
Timeout: &duration.Duration{Seconds: requestTimeout},
MaxGrpcTimeout: &duration.Duration{Seconds: maxGRPCTimeout},
RetryPolicy: &envoy_api_v2_route.RetryPolicy{
RetryOn: "5xx",
NumRetries: &wrappers.UInt32Value{Value: numRetries},
PerTryTimeout: &duration.Duration{Seconds: retryTimeout},
},
},
},
}, {
Match: &envoy_api_v2_route.RouteMatch{
PathSpecifier: &envoy_api_v2_route.RouteMatch_Prefix{Prefix: "/"},
},
Action: &envoy_api_v2_route.Route_Route{
Route: &envoy_api_v2_route.RouteAction{
ClusterSpecifier: &envoy_api_v2_route.RouteAction_Cluster{
Cluster: clusterName,
},
Timeout: &duration.Duration{Seconds: requestTimeout},
//IdleTimeout: &duration.Duration{Seconds: idleTimeout},
RetryPolicy: &envoy_api_v2_route.RetryPolicy{
RetryOn: "5xx",
NumRetries: &wrappers.UInt32Value{Value: numRetries},
PerTryTimeout: &duration.Duration{Seconds: retryTimeout},
},
},
},
}},
}},
},
},
}
// Idle timeout can only be specified if non-zero
if idleTimeout > 0 {
hcmConfig.GetRouteConfig().VirtualHosts[0].Routes[1].GetRoute().IdleTimeout = &duration.Duration{Seconds: idleTimeout}
}
chain := &envoy_api_v2_listener.FilterChain{
Filters: []*envoy_api_v2_listener.Filter{{
Name: "cilium.network",
}, {
Name: "envoy.http_connection_manager",
ConfigType: &envoy_api_v2_listener.Filter_TypedConfig{
TypedConfig: toAny(hcmConfig),
},
}},
}
if tls {
chain.FilterChainMatch = &envoy_api_v2_listener.FilterChainMatch{
TransportProtocol: "tls",
}
chain.TransportSocket = &envoy_api_v2_core.TransportSocket{
Name: "cilium.tls_wrapper",
}
}
return chain
}
func (s *XDSServer) getTcpFilterChainProto(clusterName string) *envoy_api_v2_listener.FilterChain {
return &envoy_api_v2_listener.FilterChain{
Filters: []*envoy_api_v2_listener.Filter{{
Name: "cilium.network",
ConfigType: &envoy_api_v2_listener.Filter_TypedConfig{
TypedConfig: toAny(&cilium.NetworkFilter{
Proxylib: "libcilium.so",
ProxylibParams: map[string]string{
"access-log-path": s.accessLogPath,
"xds-path": s.socketPath,
},
}),
},
}, {
Name: "envoy.tcp_proxy",
ConfigType: &envoy_api_v2_listener.Filter_TypedConfig{
TypedConfig: toAny(&envoy_config_tcp.TcpProxy{
StatPrefix: "tcp_proxy",
ClusterSpecifier: &envoy_config_tcp.TcpProxy_Cluster{
Cluster: clusterName,
},
}),
},
}},
}
}
// 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.mutex.Lock()
listener := s.listeners[name]
if listener == nil {
listener = &Listener{}
s.listeners[name] = listener
}
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()
s.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
clusterName := egressClusterName
socketMark := int64(0xB00)
if isIngress {
clusterName = ingressClusterName
socketMark = 0xA00
}
listenerConf := &envoy_api_v2.Listener{
Name: name,
Address: &envoy_api_v2_core.Address{
Address: &envoy_api_v2_core.Address_SocketAddress{
SocketAddress: &envoy_api_v2_core.SocketAddress{
Protocol: envoy_api_v2_core.SocketAddress_TCP,
Address: "::",
Ipv4Compat: true,
PortSpecifier: &envoy_api_v2_core.SocketAddress_PortValue{PortValue: uint32(port)},
},
},
},
Transparent: &wrappers.BoolValue{Value: true},
SocketOptions: []*envoy_api_v2_core.SocketOption{{
Description: "Listener socket mark",
Level: unix.SOL_SOCKET,
Name: unix.SO_MARK,
Value: &envoy_api_v2_core.SocketOption_IntValue{IntValue: socketMark},
State: envoy_api_v2_core.SocketOption_STATE_PREBIND,
}},
// FilterChains: []*envoy_api_v2_listener.FilterChain
ListenerFilters: []*envoy_api_v2_listener.ListenerFilter{{
Name: "cilium.bpf_metadata",
ConfigType: &envoy_api_v2_listener.ListenerFilter_TypedConfig{
TypedConfig: toAny(&cilium.BpfMetadata{
IsIngress: isIngress,
MayUseOriginalSourceAddress: mayUseOriginalSourceAddr,
BpfRoot: bpf.GetMapRoot(),
}),
},
}, {
Name: "envoy.listener.tls_inspector",
}},
}
// Add filter chains
if kind == policy.ParserTypeHTTP {
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 {
listenerConf.FilterChains = append(listenerConf.FilterChains, s.getTcpFilterChainProto(clusterName))
}
s.listenerMutator.Upsert(ListenerTypeURL, name, listenerConf, []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()
})
s.mutex.Unlock()
}
// RemoveListener removes an existing Envoy Listener.
func (s *XDSServer) RemoveListener(name string, wg *completion.WaitGroup) xds.AckingResourceMutatorRevertFunc {
log.Debugf("Envoy: removeListener %s", name)
var listenerRevertFunc func(*completion.Completion)
s.mutex.Lock()
listener, ok := s.listeners[name]
if ok && listener != nil {
listener.count--
if listener.count == 0 {
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)
}
listener.count++
s.listeners[name] = listener
s.mutex.Unlock()
}
}
func (s *XDSServer) stop() {
s.stopServer()
os.Remove(s.socketPath)
}
func getL7Rule(l7 *api.PortRuleL7) *cilium.L7NetworkPolicyRule {
rule := &cilium.L7NetworkPolicyRule{Rule: make(map[string]string, len(*l7))}
for k, v := range *l7 {
rule.Rule[k] = v
}
return rule
}
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{
MaxProgramSize: &wrappers.UInt32Value{Value: 100}, // Envoy default
}}
headers := make([]*envoy_api_v2_route.HeaderMatcher, 0, cnt)
if h.Path != "" {
headers = append(headers, &envoy_api_v2_route.HeaderMatcher{
Name: ":path",
HeaderMatchSpecifier: &envoy_api_v2_route.HeaderMatcher_SafeRegexMatch{
SafeRegexMatch: &envoy_type_matcher.RegexMatcher{
EngineType: googleRe2,
Regex: h.Path,
}}})
}
if h.Method != "" {
headers = append(headers, &envoy_api_v2_route.HeaderMatcher{
Name: ":method",
HeaderMatchSpecifier: &envoy_api_v2_route.HeaderMatcher_SafeRegexMatch{
SafeRegexMatch: &envoy_type_matcher.RegexMatcher{
EngineType: googleRe2,
Regex: h.Method,
}}})
}
if h.Host != "" {
headers = append(headers, &envoy_api_v2_route.HeaderMatcher{
Name: ":authority",
HeaderMatchSpecifier: &envoy_api_v2_route.HeaderMatcher_SafeRegexMatch{
SafeRegexMatch: &envoy_type_matcher.RegexMatcher{
EngineType: googleRe2,
Regex: h.Host,
}}})
}
for _, hdr := range h.Headers {
strs := strings.SplitN(hdr, " ", 2)
if len(strs) == 2 {
// Remove ':' in "X-Key: true"
key := strings.TrimRight(strs[0], ":")
// Header presence and matching (literal) value needed.
headers = append(headers, &envoy_api_v2_route.HeaderMatcher{Name: key,
HeaderMatchSpecifier: &envoy_api_v2_route.HeaderMatcher_ExactMatch{ExactMatch: strs[1]}})
} else {
// Only header presence needed
headers = append(headers, &envoy_api_v2_route.HeaderMatcher{Name: strs[0],
HeaderMatchSpecifier: &envoy_api_v2_route.HeaderMatcher_PresentMatch{PresentMatch: true}})
}
}
headerMatches := make([]*cilium.HeaderMatch, 0, len(h.HeaderMatches))
for _, hdr := range h.HeaderMatches {
var mismatch_action cilium.HeaderMatch_MismatchAction
switch hdr.Mismatch {
case api.MismatchActionLog:
mismatch_action = cilium.HeaderMatch_CONTINUE_ON_MISMATCH
case api.MismatchActionAdd:
mismatch_action = cilium.HeaderMatch_ADD_ON_MISMATCH
case api.MismatchActionDelete:
mismatch_action = cilium.HeaderMatch_DELETE_ON_MISMATCH
case api.MismatchActionReplace:
mismatch_action = cilium.HeaderMatch_REPLACE_ON_MISMATCH
default:
mismatch_action = cilium.HeaderMatch_FAIL_ON_MISMATCH
}
// Fetch the secret
value, err := getSecretString(certManager, hdr, ns)
if err != nil {
log.WithError(err).Warning("Failed fetching K8s Secret, header match will fail")
// Envoy treats an empty exact match value as matching ANY value; adding
// InvertMatch: true here will cause this rule to NEVER match.
headers = append(headers, &envoy_api_v2_route.HeaderMatcher{Name: hdr.Name,
HeaderMatchSpecifier: &envoy_api_v2_route.HeaderMatcher_ExactMatch{ExactMatch: ""},
InvertMatch: true})
} else {
// Header presence and matching (literal) value needed.
if mismatch_action == cilium.HeaderMatch_FAIL_ON_MISMATCH {
if value != "" {
headers = append(headers, &envoy_api_v2_route.HeaderMatcher{Name: hdr.Name,
HeaderMatchSpecifier: &envoy_api_v2_route.HeaderMatcher_ExactMatch{ExactMatch: value}})
} else {
// Only header presence needed
headers = append(headers, &envoy_api_v2_route.HeaderMatcher{Name: hdr.Name,
HeaderMatchSpecifier: &envoy_api_v2_route.HeaderMatcher_PresentMatch{PresentMatch: true}})
}
} else {
log.Debugf("HeaderMatches: Adding %s: %s", hdr.Name, value)
headerMatches = append(headerMatches, &cilium.HeaderMatch{
MismatchAction: mismatch_action,
Name: hdr.Name,
Value: value,
})
}
}
}
if len(headers) == 0 {
headers = nil
} else {
SortHeaderMatchers(headers)
}
if len(headerMatches) == 0 {
headerMatches = nil
} else {
// Optimally we should sort the headerMatches to avoid
// updating the policy if only the order of the rules
// has changed. Right now, when 'headerMatches' is a
// slice (rather than a map) the order only changes if
// the order of the rules in the imported policies
// changes, so there is minimal likelihood of
// unnecessary policy updates.
// SortHeaderMatches(headerMatches)
}
return &cilium.HttpNetworkPolicyRule{Headers: headers, HeaderMatches: headerMatches}, len(headerMatches) == 0
}
func createBootstrap(filePath string, nodeId, cluster string, xdsSock, egressClusterName, ingressClusterName string, adminPath string) {
connectTimeout := int64(option.Config.ProxyConnectTimeout) // in seconds
bs := &envoy_config_bootstrap_v2.Bootstrap{
Node: &envoy_api_v2_core.Node{Id: nodeId, Cluster: cluster},
StaticResources: &envoy_config_bootstrap_v2.Bootstrap_StaticResources{
Clusters: []*envoy_api_v2.Cluster{
{
Name: egressClusterName,
ClusterDiscoveryType: &envoy_api_v2.Cluster_Type{Type: envoy_api_v2.Cluster_ORIGINAL_DST},
ConnectTimeout: &duration.Duration{Seconds: connectTimeout, Nanos: 0},
CleanupInterval: &duration.Duration{Seconds: connectTimeout, Nanos: 500000000},
LbPolicy: envoy_api_v2.Cluster_CLUSTER_PROVIDED,
ProtocolSelection: envoy_api_v2.Cluster_USE_DOWNSTREAM_PROTOCOL,
},
{
Name: egressTLSClusterName,
ClusterDiscoveryType: &envoy_api_v2.Cluster_Type{Type: envoy_api_v2.Cluster_ORIGINAL_DST},
ConnectTimeout: &duration.Duration{Seconds: connectTimeout, Nanos: 0},
CleanupInterval: &duration.Duration{Seconds: connectTimeout, Nanos: 500000000},
LbPolicy: envoy_api_v2.Cluster_CLUSTER_PROVIDED,
ProtocolSelection: envoy_api_v2.Cluster_USE_DOWNSTREAM_PROTOCOL,
TransportSocket: &envoy_api_v2_core.TransportSocket{Name: "cilium.tls_wrapper"},
},
{
Name: ingressClusterName,
ClusterDiscoveryType: &envoy_api_v2.Cluster_Type{Type: envoy_api_v2.Cluster_ORIGINAL_DST},
ConnectTimeout: &duration.Duration{Seconds: connectTimeout, Nanos: 0},
CleanupInterval: &duration.Duration{Seconds: connectTimeout, Nanos: 500000000},
LbPolicy: envoy_api_v2.Cluster_CLUSTER_PROVIDED,
ProtocolSelection: envoy_api_v2.Cluster_USE_DOWNSTREAM_PROTOCOL,
},
{
Name: ingressTLSClusterName,
ClusterDiscoveryType: &envoy_api_v2.Cluster_Type{Type: envoy_api_v2.Cluster_ORIGINAL_DST},
ConnectTimeout: &duration.Duration{Seconds: connectTimeout, Nanos: 0},
CleanupInterval: &duration.Duration{Seconds: connectTimeout, Nanos: 500000000},
LbPolicy: envoy_api_v2.Cluster_CLUSTER_PROVIDED,
ProtocolSelection: envoy_api_v2.Cluster_USE_DOWNSTREAM_PROTOCOL,
TransportSocket: &envoy_api_v2_core.TransportSocket{Name: "cilium.tls_wrapper"},
},
{
Name: "xds-grpc-cilium",
ClusterDiscoveryType: &envoy_api_v2.Cluster_Type{Type: envoy_api_v2.Cluster_STATIC},
ConnectTimeout: &duration.Duration{Seconds: connectTimeout, Nanos: 0},
LbPolicy: envoy_api_v2.Cluster_ROUND_ROBIN,
LoadAssignment: &envoy_api_v2.ClusterLoadAssignment{
ClusterName: "xds-grpc-cilium",
Endpoints: []*envoy_api_v2_endpoint.LocalityLbEndpoints{{
LbEndpoints: []*envoy_api_v2_endpoint.LbEndpoint{{
HostIdentifier: &envoy_api_v2_endpoint.LbEndpoint_Endpoint{
Endpoint: &envoy_api_v2_endpoint.Endpoint{
Address: &envoy_api_v2_core.Address{
Address: &envoy_api_v2_core.Address_Pipe{
Pipe: &envoy_api_v2_core.Pipe{Path: xdsSock}},
},
},
},
}},
}},
},
Http2ProtocolOptions: &envoy_api_v2_core.Http2ProtocolOptions{},
},
},
},
DynamicResources: &envoy_config_bootstrap_v2.Bootstrap_DynamicResources{
LdsConfig: &envoy_api_v2_core.ConfigSource{
ConfigSourceSpecifier: &envoy_api_v2_core.ConfigSource_ApiConfigSource{
ApiConfigSource: &envoy_api_v2_core.ApiConfigSource{
ApiType: envoy_api_v2_core.ApiConfigSource_GRPC,
GrpcServices: []*envoy_api_v2_core.GrpcService{
{
TargetSpecifier: &envoy_api_v2_core.GrpcService_EnvoyGrpc_{
EnvoyGrpc: &envoy_api_v2_core.GrpcService_EnvoyGrpc{
ClusterName: "xds-grpc-cilium",
},
},
},
},
},
},
},
},
Admin: &envoy_config_bootstrap_v2.Admin{
AccessLogPath: "/dev/null",
Address: &envoy_api_v2_core.Address{
Address: &envoy_api_v2_core.Address_Pipe{
Pipe: &envoy_api_v2_core.Pipe{Path: adminPath},
},
},
},
}
log.Debugf("Envoy: Bootstrap: %s", bs)
data, err := proto.Marshal(bs)
if err != nil {
log.WithError(err).Fatal("Envoy: Error marshaling Envoy bootstrap")
}
err = ioutil.WriteFile(filePath, data, 0644)
if err != nil {
log.WithError(err).Fatal("Envoy: Error writing Envoy bootstrap file")
}
}
func getCiliumTLSContext(tls *policy.TLSContext) *cilium.TLSContext {
return &cilium.TLSContext{
TrustedCa: tls.TrustedCA,
CertificateChain: tls.CertificateChain,
PrivateKey: tls.PrivateKey,
}
}
func GetEnvoyHTTPRules(certManager policy.CertificateManager, l7Rules *api.L7Rules, ns string) (*cilium.HttpNetworkPolicyRules, bool) {
if len(l7Rules.HTTP) > 0 { // Just cautious. This should never be false.
// Assume none of the rules have side-effects so that rule evaluation can
// be stopped as soon as the first allowing rule is found. 'canShortCircuit'
// is set to 'false' below if any rules with side effects are encountered,
// causing all the applicable rules to be evaluated instead.
canShortCircuit := true
httpRules := make([]*cilium.HttpNetworkPolicyRule, 0, len(l7Rules.HTTP))
for _, l7 := range l7Rules.HTTP {
var cs bool
rule, cs := getHTTPRule(certManager, &l7, ns)
httpRules = append(httpRules, rule)
if !cs {
canShortCircuit = false
}
}
SortHTTPNetworkPolicyRules(httpRules)
return &cilium.HttpNetworkPolicyRules{
HttpRules: httpRules,
}, canShortCircuit
}
return nil, true
}
func getPortNetworkPolicyRule(sel policy.CachedSelector, l7Parser policy.L7ParserType, l7Rules *policy.PerSelectorPolicy) (*cilium.PortNetworkPolicyRule, bool) {
// Optimize the policy if the endpoint selector is a wildcard by
// keeping remote policies list empty to match all remote policies.
var remotePolicies []uint64
if !sel.IsWildcard() {
for _, id := range sel.GetSelections() {
remotePolicies = append(remotePolicies, uint64(id))
}
// No remote policies would match this rule. Discard it.
if len(remotePolicies) == 0 {
return nil, true
}
sort.Slice(remotePolicies, func(i, j int) bool {
return remotePolicies[i] < remotePolicies[j]
})
}
r := &cilium.PortNetworkPolicyRule{
RemotePolicies: remotePolicies,
}
if l7Rules == nil {
// L3/L4 only rule, everything in L7 is allowed
return r, true
}
if l7Rules.TerminatingTLS != nil {
r.DownstreamTlsContext = getCiliumTLSContext(l7Rules.TerminatingTLS)
}
if l7Rules.OriginatingTLS != nil {
r.UpstreamTlsContext = getCiliumTLSContext(l7Rules.OriginatingTLS)
}
// Assume none of the rules have side-effects so that rule evaluation can
// be stopped as soon as the first allowing rule is found. 'canShortCircuit'
// is set to 'false' below if any rules with side effects are encountered,
// causing all the applicable rules to be evaluated instead.
canShortCircuit := true
switch l7Parser {
case policy.ParserTypeHTTP:
// 'r.L7' is an interface which must not be set to a typed 'nil',
// so check if we have any rules
if len(l7Rules.HTTP) > 0 {
// Use L7 rules computed earlier?
var httpRules *cilium.HttpNetworkPolicyRules
if l7Rules.EnvoyHTTPRules != nil {
httpRules = l7Rules.EnvoyHTTPRules
canShortCircuit = l7Rules.CanShortCircuit
} else {
httpRules, canShortCircuit = GetEnvoyHTTPRules(nil, &l7Rules.L7Rules, "")
}
r.L7 = &cilium.PortNetworkPolicyRule_HttpRules{
HttpRules: httpRules,
}
}
case policy.ParserTypeKafka:
// TODO: Support Kafka. For now, just ignore any Kafka L7 rule.
case policy.ParserTypeDNS:
// TODO: Support DNS. For now, just ignore any DNS L7 rule.
default:
// Assume unknown parser types use a Key-Value Pair policy
if len(l7Rules.L7) > 0 {
kvpRules := make([]*cilium.L7NetworkPolicyRule, 0, len(l7Rules.L7))
for _, l7 := range l7Rules.L7 {
kvpRules = append(kvpRules, getL7Rule(&l7))
}
// L7 rules are not sorted
r.L7Proto = l7Parser.String()
r.L7 = &cilium.PortNetworkPolicyRule_L7Rules{
L7Rules: &cilium.L7NetworkPolicyRules{
L7Rules: kvpRules,
},
}
}
}
return r, canShortCircuit
}
func getWildcardNetworkPolicyRule(selectors policy.L7DataMap) *cilium.PortNetworkPolicyRule {
// Use map to remove duplicates
remoteMap := make(map[uint64]struct{})
wildcardFound := false
for sel, l7 := range selectors {
if sel.IsWildcard() {
wildcardFound = true
break
}
for _, id := range sel.GetSelections() {
remoteMap[uint64(id)] = struct{}{}
}
if l7 != nil {
log.Warningf("L3-only rule for selector %v surprisingly has L7 rules (%v)!", sel, *l7)
}
}
if wildcardFound {
// Optimize the policy if the endpoint selector is a wildcard by
// keeping remote policies list empty to match all remote policies.
remoteMap = nil
} else if len(remoteMap) == 0 {
// No remote policies would match this rule. Discard it.
return nil
}
// Convert to a sorted slice
remotePolicies := make([]uint64, 0, len(remoteMap))
for id := range remoteMap {
remotePolicies = append(remotePolicies, id)
}
sort.Slice(remotePolicies, func(i, j int) bool {
return remotePolicies[i] < remotePolicies[j]
})
return &cilium.PortNetworkPolicyRule{
RemotePolicies: remotePolicies,
}
}
func getDirectionNetworkPolicy(l4Policy policy.L4PolicyMap, npMap policy.NamedPortsMap, policyEnforced bool) []*cilium.PortNetworkPolicy {
if !policyEnforced {
// Return an allow-all policy.
return allowAllPortNetworkPolicy
}
if len(l4Policy) == 0 {
return nil
}
PerPortPolicies := make([]*cilium.PortNetworkPolicy, 0, len(l4Policy))
// map to locate entries already on the same port
pnps := make(map[string]*cilium.PortNetworkPolicy, len(l4Policy))
for _, l4 := range l4Policy {
var protocol envoy_api_v2_core.SocketAddress_Protocol
switch l4.Protocol {
case api.ProtoTCP:
protocol = envoy_api_v2_core.SocketAddress_TCP
case api.ProtoUDP:
protocol = envoy_api_v2_core.SocketAddress_UDP
}
port := uint16(l4.Port)
if port == 0 && l4.PortName != "" {
var err error
port, err = npMap.GetNamedPort(l4.PortName, uint8(l4.U8Proto))
if err != nil {
log.WithError(err).WithField(logfields.PortName, l4.PortName).Debug("getDirectionNetworkPolicy: Skipping named port")
continue
}
}
rules := make([]*cilium.PortNetworkPolicyRule, 0, len(l4.L7RulesPerSelector))
allowAll := false
// Assume none of the rules have side-effects so that rule evaluation can
// be stopped as soon as the first allowing rule is found. 'canShortCircuit'
// is set to 'false' below if any rules with side effects are encountered,
// causing all the applicable rules to be evaluated instead.
canShortCircuit := true
if port == 0 {
// L3-only rule, must generate L7 allow-all in case there are other
// port-specific rules. Otherwise traffic from allowed remotes could be dropped.
rule := getWildcardNetworkPolicyRule(l4.L7RulesPerSelector)
if rule != nil {
if len(rule.RemotePolicies) == 0 && rule.L7 == nil {
// Got an allow-all rule, which can short-circuit all of
// the other rules.
allowAll = true
}
rules = append(rules, rule)
}
} else {
for sel, l7 := range l4.L7RulesPerSelector {
rule, cs := getPortNetworkPolicyRule(sel, l4.L7Parser, l7)
if rule != nil {
if !cs {
canShortCircuit = false
}
if len(rule.RemotePolicies) == 0 && rule.L7 == nil {
// Got an allow-all rule, which can short-circuit all of
// the other rules.
allowAll = true
}
rules = append(rules, rule)
}
}
}
// Short-circuit rules if a rule allows all and all other rules can be short-circuited
if allowAll && canShortCircuit {
log.Debug("Short circuiting HTTP rules due to rule allowing all and no other rules needing attention")
rules = nil
}
// No rule for this port matches any remote identity.
// This means that no traffic was explicitly allowed for this port.
// In this case, just don't generate any PortNetworkPolicy for this
// port.
if !allowAll && len(rules) == 0 {
continue
}
// Add rules to a new or existing entry for this port
key := fmt.Sprintf("%d/%s", port, l4.Protocol)
pnp, exists := pnps[key]
if !exists {
pnp = &cilium.PortNetworkPolicy{
Port: uint32(port),
Protocol: protocol,
Rules: rules,
}
pnps[key] = pnp
PerPortPolicies = append(PerPortPolicies, pnp)
} else {
pnp.Rules = append(pnp.Rules, rules...)
}
SortPortNetworkPolicyRules(pnp.Rules)
}
if len(PerPortPolicies) == 0 {
return nil
}
SortPortNetworkPolicies(PerPortPolicies)
return PerPortPolicies
}
// getNetworkPolicy converts a network policy into a cilium.NetworkPolicy.
func getNetworkPolicy(name string, id identity.NumericIdentity, conntrackName string, policy *policy.L4Policy,
npMap policy.NamedPortsMap, ingressPolicyEnforced, egressPolicyEnforced bool) *cilium.NetworkPolicy {
p := &cilium.NetworkPolicy{
Name: name,
Policy: uint64(id),
ConntrackMapName: conntrackName,
}
// If no policy, deny all traffic. Otherwise, convert the policies for ingress and egress.