Routing egress traffic to wildcard destinations (2024)

If you are using Istio to handle application-originated traffic to destinations outside of the mesh, you’re probably familiar with the concept of egress gateways.Egress gateways can be used to monitor and forward traffic from mesh-internal applications to locations outside of the mesh.This is a useful feature if your system is operating in a restrictedenvironment and you want to control what can be reached on the public internet from your mesh.

The use-case of configuring an egress gateway to handle arbitrary wildcard domains had been included in the official Istio docs up until version 1.13, but was subsequently removed because the documented solution was not officially supported or recommended and was subject to breakage in future versions of Istio.Nevertheless, the old solution was still usable with Istio versions before 1.20. Istio 1.20, however, dropped some Envoy functionality that was required for the approach to work.

This post attempts to describe how we resolved the issue and filled the gap with a similar approach using Istio version-independent components and Envoy features, but without the need for a separate Nginx SNI proxy.Our approach allows users of the old solution to seamlessly migrate configurations before their systems face the breaking changes in Istio 1.20.

Problem to solve

The currently documented egress gateway use-cases rely on the fact that the target of the traffic(the hostname) is statically configured in a VirtualService, telling Envoy in the egress gateway pod where to TCP proxythe matching outbound connections. You can use multiple, and even wildcard, DNS names to match the routing criteria, but youare not able to route the traffic to the exact location specified in the application request. For example you can match traffic for targets*.wikipedia.org, but you then need to forward the traffic to a single final target, e.g., en.wikipedia.org. If there is anotherservice, e.g., anyservice.wikipedia.org, that is not hosted by the same server(s) as en.wikipedia.org, the traffic to that host will fail. This is because, even though the target hostname in theTLS handshake of the HTTP payload contains anyservice.wikipedia.org, the en.wikipedia.org servers will not be able to serve the request.

The solution to this problem at a high level is to inspect the original server name (SNI extension) in the application TLS handshake (which is sentin plain-text, so no TLS termination or other man-in-the-middle operation is needed) in every new gateway connection and use it asthe target to dynamically TCP proxy the traffic leaving the gateway.

When restricting egress traffic via egress gateways, we need to lock down the egress gateways so that they can only be usedby clients within the mesh. This is achieved by enforcing ISTIO_MUTUAL (mTLS peer authentication) between the applicationsidecar and the gateway. That means that there will be two layers of TLS on the application L7 payload. One that is the applicationoriginated end-to-end TLS session terminated by the final remote target, and another one that is the Istio mTLS session.

Another thing to keep in mind is that in order to mitigate any potential application pod corruption, the application sidecar and the gateway should both perform hostname list checks.This way, any compromised application pod will still only be able to access the allowed targets and nothing more.

Low-level Envoy programming to the rescue

Recent Envoy releases include a dynamic TCP forward proxy solution that uses the SNI header on a per-connection basis to determine the target of an application request. While an Istio VirtualService cannot configure a target like this, we are able to useEnvoyFilters to alter the Istio generated routing instructions so that the SNI header is used to determine the target.

To make it all work, we start by configuring a custom egress gateway to listen for the outbound traffic. Usinga DestinationRule and a VirtualService we instruct the application sidecars to route the traffic (for a selectedlist of hostnames) to that gateway, using Istio mTLS. On the gateway pod side we build the SNI forwarder with theEnvoyFilters, mentioned above, introducing internal Envoy listeners and clusters to make it all work. Finally, we patch theinternal destination of the gateway-implemented TCP proxy to the internal SNI forwarder.

The end-to-end request flow is shown in the following diagram:

This diagram shows an egress HTTPS request to en.wikipedia.org using SNI as a routing key.

  • Application container

    Application originates HTTP/TLS connection towards the final destination.Puts destination’s hostname into the SNI header. This TLS session is notdecrypted inside the mesh. Only SNI header is inspected (as it is in cleartext).

  • Sidecar proxy

    Sidecar intercepts traffic to matching hostnames in the SNI header from the application originated TLS sessions.Based on the VirtualService, the traffic is routed to the egress gateway while wrapping original traffic intoIstio mTLS as well. Outer TLS session has the gateway Service address in the SNI header.

  • Mesh listener

    A dedicated listener is created in the Gateway that mutually authenticates the Istio mTLS traffic.After the outer Istio mTLS termination, it unconditionally sends the inner TLS traffic with a TCP proxyto the other (internal) listener in the same Gateway.

  • SNI forwarder

    Another listener with SNI forwarder performs a new TLS header inspection for the original TLS session.If the inner SNI hostname matches the allowed domain names (including wildcards), it TCP proxies thetraffic to the destination, read from the header per connection. This listener is internal to Envoy(allowing it to restart traffic processing to see the inner SNI value), so that no pods (inside or outside the mesh)can connect to it directly. This listener is 100% manually configured through EnvoyFilter.

Deploy the sample

In order to deploy the sample configuration, start by creating the istio-egress namespace and then use the following YAML to deploy an egress gateway, along with some RBACand its Service. We use the gateway injection method to create the gateway in this example. Depending on your install method, you may want todeploy it differently (for example, using an IstioOperator CR or using Helm).

# New k8s cluster service to put egressgateway into the Service Registry,# so application sidecars can route traffic towards it within the mesh.apiVersion: v1kind: Servicemetadata: name: egressgateway namespace: istio-egressspec: type: ClusterIP selector: istio: egressgateway ports: - port: 443 name: tls-egress targetPort: 8443---# Gateway deployment with injection methodapiVersion: apps/v1kind: Deploymentmetadata: name: istio-egressgateway namespace: istio-egressspec: selector: matchLabels: istio: egressgateway template: metadata: annotations: inject.istio.io/templates: gateway labels: istio: egressgateway sidecar.istio.io/inject: "true" spec: containers: - name: istio-proxy image: auto # The image will automatically update each time the pod starts. securityContext: capabilities: drop: - ALL runAsUser: 1337 runAsGroup: 1337---# Set up roles to allow reading credentials for TLSapiVersion: rbac.authorization.k8s.io/v1kind: Rolemetadata: name: istio-egressgateway-sds namespace: istio-egressrules:- apiGroups: [""] resources: ["secrets"] verbs: ["get", "watch", "list"]- apiGroups: - security.openshift.io resourceNames: - anyuid resources: - securitycontextconstraints verbs: - use---apiVersion: rbac.authorization.k8s.io/v1kind: RoleBindingmetadata: name: istio-egressgateway-sds namespace: istio-egressroleRef: apiGroup: rbac.authorization.k8s.io kind: Role name: istio-egressgateway-sdssubjects:- kind: ServiceAccount name: default

Verify the gateway pod is up and running in the istio-egress namespace and then apply the following YAML to configure the gateway routing:

# Define a new listener that enforces Istio mTLS on inbound connections.# This is where sidecar will route the application traffic, wrapped into# Istio mTLS.apiVersion: networking.istio.io/v1alpha3kind: Gatewaymetadata: name: egressgateway namespace: istio-systemspec: selector: istio: egressgateway servers: - port: number: 8443 name: tls-egress protocol: TLS hosts: - "*" tls: mode: ISTIO_MUTUAL---# VirtualService that will instruct sidecars in the mesh to route the outgoing# traffic to the egress gateway Service if the SNI target hostname matchesapiVersion: networking.istio.io/v1alpha3kind: VirtualServicemetadata: name: direct-wildcard-through-egress-gateway namespace: istio-systemspec: hosts: - "*.wikipedia.org" gateways: - mesh - egressgateway tls: - match: - gateways: - mesh port: 443 sniHosts: - "*.wikipedia.org" route: - destination: host: egressgateway.istio-egress.svc.cluster.local subset: wildcard# Dummy routing instruction. If omitted, no reference will point to the Gateway# definition, and istiod will optimise the whole new listener out. tcp: - match: - gateways: - egressgateway port: 8443 route: - destination: host: "dummy.local" weight: 100---# Instruct sidecars to use Istio mTLS when sending traffic to the egress gatewayapiVersion: networking.istio.io/v1alpha3kind: DestinationRulemetadata: name: egressgateway namespace: istio-systemspec: host: egressgateway.istio-egress.svc.cluster.local subsets: - name: wildcard trafficPolicy: tls: mode: ISTIO_MUTUAL---# Put the remote targets into the Service RegistryapiVersion: networking.istio.io/v1alpha3kind: ServiceEntrymetadata: name: wildcard namespace: istio-systemspec: hosts: - "*.wikipedia.org" ports: - number: 443 name: tls protocol: TLS---# Access logging for the gatewayapiVersion: telemetry.istio.io/v1alpha1kind: Telemetrymetadata: name: mesh-default namespace: istio-systemspec: accessLogging: - providers: - name: envoy---# And finally, the configuration of the SNI forwarder,# it's internal listener, and the patch to the original Gateway# listener to route everything into the SNI forwarder.apiVersion: networking.istio.io/v1alpha3kind: EnvoyFiltermetadata: name: sni-magic namespace: istio-systemspec: configPatches: - applyTo: CLUSTER match: context: GATEWAY patch: operation: ADD value: name: sni_cluster load_assignment: cluster_name: sni_cluster endpoints: - lb_endpoints: - endpoint: address: envoy_internal_address: server_listener_name: sni_listener - applyTo: CLUSTER match: context: GATEWAY patch: operation: ADD value: name: dynamic_forward_proxy_cluster lb_policy: CLUSTER_PROVIDED cluster_type: name: envoy.clusters.dynamic_forward_proxy typed_config: "@type": type.googleapis.com/envoy.extensions.clusters.dynamic_forward_proxy.v3.ClusterConfig dns_cache_config: name: dynamic_forward_proxy_cache_config dns_lookup_family: V4_ONLY - applyTo: LISTENER match: context: GATEWAY patch: operation: ADD value: name: sni_listener internal_listener: {} listener_filters: - name: envoy.filters.listener.tls_inspector typed_config: "@type": type.googleapis.com/envoy.extensions.filters.listener.tls_inspector.v3.TlsInspector filter_chains: - filter_chain_match: server_names: - "*.wikipedia.org" filters: - name: envoy.filters.network.sni_dynamic_forward_proxy typed_config: "@type": type.googleapis.com/envoy.extensions.filters.network.sni_dynamic_forward_proxy.v3.FilterConfig port_value: 443 dns_cache_config: name: dynamic_forward_proxy_cache_config dns_lookup_family: V4_ONLY - name: envoy.tcp_proxy typed_config: "@type": type.googleapis.com/envoy.extensions.filters.network.tcp_proxy.v3.TcpProxy stat_prefix: tcp cluster: dynamic_forward_proxy_cluster access_log: - name: envoy.access_loggers.file typed_config: "@type": type.googleapis.com/envoy.extensions.access_loggers.file.v3.FileAccessLog path: "/dev/stdout" log_format: text_format_source: inline_string: '[%START_TIME%] "%REQ(:METHOD)% %REQ(X-ENVOY-ORIGINAL-PATH?:PATH)% %PROTOCOL%" %RESPONSE_CODE% %RESPONSE_FLAGS% %RESPONSE_CODE_DETAILS% %CONNECTION_TERMINATION_DETAILS% "%UPSTREAM_TRANSPORT_FAILURE_REASON%" %BYTES_RECEIVED% %BYTES_SENT% %DURATION% %RESP(X-ENVOY-UPSTREAM-SERVICE-TIME)% "%REQ(X-FORWARDED-FOR)%" "%REQ(USER-AGENT)%" "%REQ(X-REQUEST-ID)%" "%REQ(:AUTHORITY)%" "%UPSTREAM_HOST%" %UPSTREAM_CLUSTER% %UPSTREAM_LOCAL_ADDRESS% %DOWNSTREAM_LOCAL_ADDRESS% %DOWNSTREAM_REMOTE_ADDRESS% %REQUESTED_SERVER_NAME% %ROUTE_NAME% ' - applyTo: NETWORK_FILTER match: context: GATEWAY listener: filterChain: filter: name: "envoy.filters.network.tcp_proxy" patch: operation: MERGE value: name: envoy.tcp_proxy typed_config: "@type": type.googleapis.com/envoy.extensions.filters.network.tcp_proxy.v3.TcpProxy stat_prefix: tcp cluster: sni_cluster

Check the istiod and gateway logs for any errors or warnings. If all went well, your mesh sidecars are now routing*.wikipedia.org requests to your gateway pod while the gateway pod is then forwarding them to the exact remote host specified in the applicationrequest.

Try it out

Following other Istio egress examples, we will use thesleep pod as a test source for sending requests.Assuming automatic sidecar injection is enabled in your default namespace, deploythe test app using the following command:

$ kubectl apply -f https://raw.githubusercontent.com/istio/istio/release-1.21/samples/sleep/sleep.yaml

Get your sleep and gateway pods:

$ export SOURCE_POD=$(kubectl get pod -l app=sleep -o jsonpath={.items..metadata.name})$ export GATEWAY_POD=$(kubectl get pod -n istio-egress -l istio=egressgateway -o jsonpath={.items..metadata.name})

Run the following command to confirm that you are able to connect to the wikipedia.org site:

$ kubectl exec "$SOURCE_POD" -c sleep -- sh -c 'curl -s https://en.wikipedia.org/wiki/Main_Page | grep -o "<title>.*</title>"; curl -s https://de.wikipedia.org/wiki/Wikipedia:Hauptseite | grep -o "<title>.*</title>"'<title>Wikipedia, the free encyclopedia</title><title>Wikipedia – Die freie Enzyklopädie</title>

We could reach both English and German wikipedia.org subdomains, great!

Normally, in a production environment, we would block external requests that are not configured to redirect through the egress gateway, but since we didn’t do that in our test environment, let’s access another external site for comparison:

$ kubectl exec "$SOURCE_POD" -c sleep -- sh -c 'curl -s https://cloud.ibm.com/login | grep -o "<title>.*</title>"'<title>IBM Cloud</title>

Since we have access logging turned on globally (with the Telemetry CR in the manifest), we can now inspect the logs to see how the above requests were handled by the proxies.

First, check the gateway logs:

$ kubectl logs -n istio-egress $GATEWAY_POD[...][2023-11-24T13:21:52.798Z] "- - -" 0 - - - "-" 813 111152 55 - "-" "-" "-" "-" "185.15.59.224:443" dynamic_forward_proxy_cluster 172.17.5.170:48262 envoy://sni_listener/ envoy://internal_client_address/ en.wikipedia.org -[2023-11-24T13:21:52.798Z] "- - -" 0 - - - "-" 1531 111950 55 - "-" "-" "-" "-" "envoy://sni_listener/" sni_cluster envoy://internal_client_address/ 172.17.5.170:8443 172.17.34.35:55102 outbound_.443_.wildcard_.egressgateway.istio-egress.svc.cluster.local -[2023-11-24T13:21:53.000Z] "- - -" 0 - - - "-" 821 92848 49 - "-" "-" "-" "-" "185.15.59.224:443" dynamic_forward_proxy_cluster 172.17.5.170:48278 envoy://sni_listener/ envoy://internal_client_address/ de.wikipedia.org -[2023-11-24T13:21:53.000Z] "- - -" 0 - - - "-" 1539 93646 50 - "-" "-" "-" "-" "envoy://sni_listener/" sni_cluster envoy://internal_client_address/ 172.17.5.170:8443 172.17.34.35:55108 outbound_.443_.wildcard_.egressgateway.istio-egress.svc.cluster.local -

There are four log entries, representing two of our three curl requests. Each pair shows how a single request flows through the envoy traffic processing pipeline.They are printed in reverse order, but we can see the 2nd and the 4th line show that the requests arrived at the gateway service and were passed through the internal sni_cluster target.The 1st and 3rd line show that the final target is determined from the inner SNI header, i.e., the target host set by the application.The request is forwarded to dynamic_forward_proxy_cluster which finally sends on the request from Envoy to the remote target.

Great, but where is the third request to IBM Cloud? Let’s check the sidecar logs:

$ kubectl logs $SOURCE_POD -c istio-proxy[...][2023-11-24T13:21:52.793Z] "- - -" 0 - - - "-" 813 111152 61 - "-" "-" "-" "-" "172.17.5.170:8443" outbound|443|wildcard|egressgateway.istio-egress.svc.cluster.local 172.17.34.35:55102 208.80.153.224:443 172.17.34.35:37020 en.wikipedia.org -[2023-11-24T13:21:52.994Z] "- - -" 0 - - - "-" 821 92848 55 - "-" "-" "-" "-" "172.17.5.170:8443" outbound|443|wildcard|egressgateway.istio-egress.svc.cluster.local 172.17.34.35:55108 208.80.153.224:443 172.17.34.35:37030 de.wikipedia.org -[2023-11-24T13:21:55.197Z] "- - -" 0 - - - "-" 805 15199 158 - "-" "-" "-" "-" "104.102.54.251:443" PassthroughCluster 172.17.34.35:45584 104.102.54.251:443 172.17.34.35:45582 cloud.ibm.com -

As you can see, Wikipedia requests were sent through the gateway while the request to IBM Cloud went straight out from the application pod to the internet, as indicated by the PassthroughCluster log.

Conclusion

We implemented controlled routing for egress HTTPS/TLS traffic using egress gateways, supporting arbitrary and wildcard domain names. In a production environment, the example shown in this postwould be extended to support HA requirements (e.g., adding zone aware gateway Deployments, etc.) and to restrict the direct externalnetwork access of your application so that the application can only access the public network through the gateway, which is limited to a predefined set of remote hostnames.

The solution scales easily. You can include multiple domain names in the configuration, and they will be allow-listed as soon as you roll it out!No need to configure per domain VirtualServices or other routing details. Be careful, however, as the domain names are listed in multiple places in the config. If you usetooling for CI/CD (e.g., Kustomize), it’s best to extract the domain name list into a single place from which you can render into the required configuration resources.

That’s all! I hope this was helpful.If you’re an existing user of the previous Nginx-based solution,you can now migrate to this approach before upgrading to Istio 1.20, which will otherwise disrupt your current setup.

Happy SNI routing!

References

Routing egress traffic to wildcard destinations (2024)
Top Articles
Latest Posts
Article information

Author: Manual Maggio

Last Updated:

Views: 5825

Rating: 4.9 / 5 (69 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Manual Maggio

Birthday: 1998-01-20

Address: 359 Kelvin Stream, Lake Eldonview, MT 33517-1242

Phone: +577037762465

Job: Product Hospitality Supervisor

Hobby: Gardening, Web surfing, Video gaming, Amateur radio, Flag Football, Reading, Table tennis

Introduction: My name is Manual Maggio, I am a thankful, tender, adventurous, delightful, fantastic, proud, graceful person who loves writing and wants to share my knowledge and understanding with you.