Compare commits

...

17 Commits

Author SHA1 Message Date
1c0b30963b In DNSRR there is no Endpoint.VirtualIPs - use Spec.TaskTemplate.Networks 2023-02-03 00:11:24 +01:00
c757750ff3 Merge branch 'master' of https://git.ivasoft.cz/rv/traefik 2023-02-02 21:27:19 +01:00
a2089c3a5d CI build trigger. 2023-02-02 21:26:49 +01:00
881bfb4b11 Merge branch 'master' into master 2023-01-26 08:57:22 +00:00
d1899ff250 Use DDNS for swarm load balancing 2023-01-26 09:40:23 +01:00
7a284c0840 Merge pull request 'master' (#1) from rv/traefik:master into master
Reviewed-on: SW/traefik#1
2023-01-25 23:14:34 +00:00
48f3e5cf1c FIX Drone CI repo 2023-01-25 23:55:20 +01:00
34c3effdde Drone CI 2023-01-25 23:53:15 +01:00
Tom Moulard
e54ee89330 Prepare release v3.0.0-beta2 2022-12-07 17:26:04 +01:00
Simon Delicata
fdd3f2abef Moves HTTP/3 outside the experimental section 2022-12-07 17:02:05 +01:00
Tom Moulard
517917cd7c Merge current v2.9 into master 2022-12-07 15:55:46 +01:00
Tom Moulard
d97d3a6726 Prepare release v2.9.6 2022-12-07 15:14:05 +01:00
Tom Moulard
6c75052a13 Change traefik cmd error log to error level 2022-12-07 11:34:06 +01:00
Ludovic Fernandez
a8df674dcf fix: flaky tests 2022-12-07 10:56:05 +01:00
Ludovic Fernandez
abd569701f fix: update golang.org/x/net 2022-12-07 10:02:04 +01:00
mpl
7e3fe48b80 Handle broken TLS conf better
Co-authored-by: Jean-Baptiste Doumenjou <925513+jbdoumenjou@users.noreply.github.com>
Co-authored-by: Romain <rtribotte@users.noreply.github.com>
2022-12-06 18:28:05 +01:00
Tom Moulard
8cf9385938 Rework Host and HostRegexp matchers
Co-authored-by: Simon Delicata <simon.delicata@traefik.io>
2022-12-06 10:40:06 +01:00
31 changed files with 599 additions and 304 deletions

17
.drone.yml Normal file
View File

@@ -0,0 +1,17 @@
kind: pipeline
name: default
steps:
- name: docker
image: plugins/docker
settings:
dockerfile: exp.Dockerfile
registry: https://git.ivasoft.cz
username:
from_secret: repo_user
password:
from_secret: repo_pass
repo: git.ivasoft.cz/sw/traefik
tags:
- latest
- ${DRONE_TAG:-latest}

View File

@@ -1,3 +1,35 @@
## [v3.0.0-beta2](https://github.com/traefik/traefik/tree/v3.0.0-beta2) (2022-12-07)
[All Commits](https://github.com/traefik/traefik/compare/v3.0.0-beta1...v3.0.0-beta2)
**Enhancements:**
- **[http3]** Moves HTTP/3 outside the experimental section ([#9570](https://github.com/traefik/traefik/pull/9570) by [sdelicata](https://github.com/sdelicata))
**Bug fixes:**
- **[logs]** Change traefik cmd error log to error level ([#9569](https://github.com/traefik/traefik/pull/9569) by [tomMoulard](https://github.com/tomMoulard))
- **[rules]** Rework Host and HostRegexp matchers ([#9559](https://github.com/traefik/traefik/pull/9559) by [tomMoulard](https://github.com/tomMoulard))
**Misc:**
- Merge current v2.9 into master ([#9586](https://github.com/traefik/traefik/pull/9586) by [tomMoulard](https://github.com/tomMoulard))
## [v2.9.6](https://github.com/traefik/traefik/tree/v2.9.6) (2022-12-07)
[All Commits](https://github.com/traefik/traefik/compare/v2.9.5...v2.9.6)
**Bug fixes:**
- **[acme]** Update go-acme/lego to v4.9.1 ([#9550](https://github.com/traefik/traefik/pull/9550) by [ldez](https://github.com/ldez))
- **[k8s/crd]** Support of allowEmptyServices in TraefikService ([#9424](https://github.com/traefik/traefik/pull/9424) by [jeromeguiard](https://github.com/jeromeguiard))
- **[logs]** Remove logs of the request ([#9574](https://github.com/traefik/traefik/pull/9574) by [ldez](https://github.com/ldez))
- **[plugins]** Increase the timeout on plugin download ([#9529](https://github.com/traefik/traefik/pull/9529) by [ldez](https://github.com/ldez))
- **[server]** Update golang.org/x/net ([#9582](https://github.com/traefik/traefik/pull/9582) by [ldez](https://github.com/ldez))
- **[tls]** Handle broken TLS conf better ([#9572](https://github.com/traefik/traefik/pull/9572) by [mpl](https://github.com/mpl))
- **[tracing]** Update DataDog tracing dependency to v1.43.1 ([#9526](https://github.com/traefik/traefik/pull/9526) by [rtribotte](https://github.com/rtribotte))
- **[webui]** Add missing serialNumber passTLSClientCert option to middleware panel ([#9539](https://github.com/traefik/traefik/pull/9539) by [rtribotte](https://github.com/rtribotte))
**Documentation:**
- **[docker]** Add networking example ([#9542](https://github.com/traefik/traefik/pull/9542) by [Janik-Haag](https://github.com/Janik-Haag))
- **[hub]** Add information about the Hub Agent ([#9560](https://github.com/traefik/traefik/pull/9560) by [nmengin](https://github.com/nmengin))
- **[k8s/helm]** Update Helm installation section ([#9564](https://github.com/traefik/traefik/pull/9564) by [mloiseleur](https://github.com/mloiseleur))
- **[middleware]** Clarify PathPrefix matcher greediness ([#9519](https://github.com/traefik/traefik/pull/9519) by [mpl](https://github.com/mpl))
## [v3.0.0-beta1](https://github.com/traefik/traefik/tree/v3.0.0-beta1) (2022-12-05)
[All Commits](https://github.com/traefik/traefik/compare/v2.9.0-rc1...v3.0.0-beta1)

View File

@@ -79,7 +79,7 @@ Complete documentation is available at https://traefik.io`,
err = cli.Execute(cmdTraefik)
if err != nil {
stdlog.Println(err)
log.Error().Err(err).Msg("Command error")
logrus.Exit(1)
}

View File

@@ -50,3 +50,8 @@ and should be explicitly combined using logical operators to mimic previous beha
In v3, the `Content-Type` header is not auto-detected anymore when it is not set by the backend.
One should use the `ContentType` middleware to enable the `Content-Type` header value auto-detection.
## HTTP/3
In v3, HTTP/3 is no longer an experimental feature.
The `experimental.http3` option has been removed from the static configuration.

View File

@@ -189,9 +189,6 @@ WriteTimeout is the maximum duration before timing out writes of the response. I
`--entrypoints.<name>.udp.timeout`:
Timeout defines how long to wait on an idle session before releasing the related resources. (Default: ```3```)
`--experimental.http3`:
Enable HTTP3. (Default: ```false```)
`--experimental.hub`:
Enable the Traefik Hub provider. (Default: ```false```)

View File

@@ -189,9 +189,6 @@ WriteTimeout is the maximum duration before timing out writes of the response. I
`TRAEFIK_ENTRYPOINTS_<NAME>_UDP_TIMEOUT`:
Timeout defines how long to wait on an idle session before releasing the related resources. (Default: ```3```)
`TRAEFIK_EXPERIMENTAL_HTTP3`:
Enable HTTP3. (Default: ```false```)
`TRAEFIK_EXPERIMENTAL_HUB`:
Enable the Traefik Hub provider. (Default: ```false```)

View File

@@ -461,7 +461,6 @@
[experimental]
kubernetesGateway = true
http3 = true
hub = true
[experimental.plugins]
[experimental.plugins.Descriptor0]

View File

@@ -489,7 +489,6 @@ hub:
key: foobar
experimental:
kubernetesGateway: true
http3: true
hub: true
plugins:
Descriptor0:

View File

@@ -312,39 +312,32 @@ entryPoints:
#### `http3`
`http3` enables HTTP/3 protocol on the entryPoint.
HTTP/3 requires a TCP entryPoint, as HTTP/3 always starts as a TCP connection that then gets upgraded to UDP.
In most scenarios, this entryPoint is the same as the one used for TLS traffic.
HTTP/3 requires a TCP entryPoint,
as HTTP/3 always starts as a TCP connection that then gets upgraded to UDP.
In most scenarios,
this entryPoint is the same as the one used for TLS traffic.
```yaml tab="File (YAML)"
entryPoints:
name:
http3: {}
```
```toml tab="File (TOML)"
[entryPoints.name.http3]
```
```bash tab="CLI"
--entrypoints.name.http3
```
??? info "HTTP/3 uses UDP+TLS"
As HTTP/3 uses UDP, you can't have a TCP entryPoint with HTTP/3 on the same port as a UDP entryPoint.
Since HTTP/3 requires the use of TLS, only routers with TLS enabled will be usable with HTTP/3.
!!! warning "Enabling Experimental HTTP/3"
As the HTTP/3 spec is still in draft, HTTP/3 support in Traefik is an experimental feature and needs to be activated
in the experimental section of the static configuration.
```yaml tab="File (YAML)"
experimental:
http3: true
entryPoints:
name:
http3: {}
```
```toml tab="File (TOML)"
[experimental]
http3 = true
[entryPoints.name.http3]
```
```bash tab="CLI"
--experimental.http3=true
--entrypoints.name.http3
```
As HTTP/3 actually uses UDP, when traefik is configured with a TCP entryPoint on port N with HTTP/3 enabled,
the underlying HTTP/3 server that is started automatically listens on UDP port N too. As a consequence,
it means port N cannot be used by another UDP entryPoint.
Since HTTP/3 requires the use of TLS,
only routers with TLS enabled will be usable with HTTP/3.
#### `advertisedPort`
@@ -355,9 +348,6 @@ It can be used to override the authority in the `alt-svc` header, for example if
!!! info "http3.advertisedPort"
```yaml tab="File (YAML)"
experimental:
http3: true
entryPoints:
name:
http3:
@@ -365,15 +355,11 @@ It can be used to override the authority in the `alt-svc` header, for example if
```
```toml tab="File (TOML)"
[experimental]
http3 = true
[entryPoints.name.http3]
advertisedPort = 443
```
```bash tab="CLI"
--experimental.http3=true
--entrypoints.name.http3.advertisedport=443
```

View File

@@ -244,14 +244,14 @@ The table below lists all the available matchers:
The usual AND (`&&`) and OR (`||`) logical operators can be used, with the expected precedence rules,
as well as parentheses.
One can invert a matcher by using the NOT (`!`) operator.
The following rule matches requests where:
- either host is `example.com` OR,
- host is `example.org` AND path is NOT `/traefik`
```yaml
Host(`example.com`) || (Host(`example.org`) && !Path(`/traefik`))
```
@@ -261,21 +261,21 @@ The table below lists all the available matchers:
The `Header` and `HeaderRegexp` matchers allow to match requests that contain specific header.
!!! example "Examples"
Match requests with a `Content-Type` header set to `application/yaml`:
```yaml
Header(`Content-Type`, `application/yaml`)
```
Match requests with a `Content-Type` header set to either `application/json` or `application/yaml`:
```yaml
HeaderRegexp(`Content-Type`, `^application/(json|yaml)$`)
```
To match headers [case-insensitively](https://en.wikipedia.org/wiki/Case_sensitivity), use the `(?i)` option:
```yaml
HeaderRegexp(`Content-Type`, `(?i)^application/(json|yaml)$`)
```
@@ -288,22 +288,24 @@ These matchers do not support non-ASCII characters, use punycode encoded values
If no Host is set in the request URL (e.g., it's an IP address), these matchers will look at the `Host` header.
These matchers will match the request's host in lowercase.
!!! example "Examples"
Match requests with `Host` set to `example.com`:
```yaml
Host(`example.com`)
```
Match requests sent to any subdomain of `example.com`:
```yaml
HostRegexp(`^.+\.example\.com$`)
```
Match requests with `Host` set to either `example.com` or `example.org`:
```yaml
HostRegexp(`^example\.(com|org)$`)
```
@@ -321,7 +323,7 @@ The `Method` matchers allows to match requests sent with the given method.
!!! example "Example"
Match `OPTIONS` requests:
```yaml
Method(`OPTIONS`)
```
@@ -337,14 +339,14 @@ Path are always starting with a `/`, except for `PathRegexp`.
!!! example "Examples"
Match `/products` but neither `/products/shoes` nor `/products/`:
```yaml
Path(`/products`)
```
Match `/products` as well as everything under `/products`,
such as `/products/shoes`, `/products/` but also `/products-for-sale`:
```yaml
PathPrefix(`/products`)
```
@@ -376,7 +378,7 @@ The `Query` and `QueryRegexp` matchers allow to match requests based on query pa
!!! example "Examples"
Match requests with a `mobile` query parameter set to `true`, such as in `/search?mobile=true`:
```yaml
Query(`mobile`, `true`)
```
@@ -388,13 +390,13 @@ The `Query` and `QueryRegexp` matchers allow to match requests based on query pa
```
Match requests with a `mobile` query parameter set to either `true` or `yes`:
```yaml
QueryRegexp(`mobile`, `^(true|yes)$`)
```
Match requests with a `mobile` query parameter set to any value (including the empty value):
```yaml
QueryRegexp(`mobile`, `^.*$`)
```
@@ -414,15 +416,15 @@ It only matches the request client IP and does not use the `X-Forwarded-For` hea
!!! example "Examples"
Match requests coming from a given IP:
```yaml tab="IPv4"
ClientIP(`10.76.105.11`)
```
```yaml tab="IPv6"
ClientIP(`::1`)
```
Match requests coming from a given subnet:
```yaml tab="IPv4"
@@ -831,9 +833,9 @@ If you want to limit the router scope to a set of entry points, set the entry po
a situation where both sides are waiting for data and the
connection appears to have hanged.
The only way that Traefik can deal with such a case, is to make
sure that on the concerned entry point, there is no TLS router
whatsoever (neither TCP nor HTTP), and there is at least one
The only way that Traefik can deal with such a case, is to make
sure that on the concerned entry point, there is no TLS router
whatsoever (neither TCP nor HTTP), and there is at least one
non-TLS TCP router that leads to the server in question.
??? example "Listens to Every Entry Point"
@@ -990,14 +992,14 @@ The table below lists all the available matchers:
The usual AND (`&&`) and OR (`||`) logical operators can be used, with the expected precedence rules,
as well as parentheses.
One can invert a matcher by using the NOT (`!`) operator.
The following rule matches connections where:
- either Server Name Indication is `example.com` OR,
- Server Name Indication is `example.org` AND ALPN protocol is NOT `h2`
```yaml
HostSNI(`example.com`) || (HostSNI(`example.org`) && !ALPN(`h2`))
```
@@ -1019,23 +1021,23 @@ These matchers do not support non-ASCII characters, use punycode encoded values
!!! example "Examples"
Match all connections:
```yaml tab="HostSNI"
HostSNI(`*`)
```
```yaml tab="HostSNIRegexp"
HostSNIRegexp(`^.*$`)
```
Match TCP connections sent to `example.com`:
```yaml
HostSNI(`example.com`)
```
Match TCP connections openned on any subdomain of `example.com`:
```yaml
HostSNIRegexp(`^.+\.example\.com$`)
```
@@ -1047,17 +1049,17 @@ The `ClientIP` matcher allows matching connections opened by a client with the g
!!! example "Examples"
Match connections opened by a given IP:
```yaml tab="IPv4"
ClientIP(`10.76.105.11`)
```
```yaml tab="IPv6"
ClientIP(`::1`)
```
Match connections coming from a given subnet:
```yaml tab="IPv4"
ClientIP(`192.168.1.0/24`)
```
@@ -1078,14 +1080,14 @@ protocol, and Traefik returns an error if this is attempted.
!!! example "Example"
Match connections using the ALPN protocol `h2`:
```yaml
ALPN(`h2`)
```
### Priority
To avoid path overlap, routes are sorted, by default, in descending order using rules length.
To avoid path overlap, routes are sorted, by default, in descending order using rules length.
The priority is directly equal to the length of the rule, and so the longest length has the highest priority.
A value of `0` for the priority is ignored: `priority = 0` means that the default rules length sorting is used.
@@ -1415,8 +1417,8 @@ So UDP "routers" at this time are pretty much only load-balancers in one form or
It basically means that some state is kept about an ongoing communication between a client and a backend,
notably so that the proxy knows where to forward a response packet from a backend.
As expected, a `timeout` is associated to each of these sessions,
so that they get cleaned out if they go through a period of inactivity longer than a given duration.
Timeout can be configured using the `entryPoints.name.udp.timeout` option as described
so that they get cleaned out if they go through a period of inactivity longer than a given duration.
Timeout can be configured using the `entryPoints.name.udp.timeout` option as described
under [EntryPoints](../entrypoints/#udp-options).
### EntryPoints

8
go.mod
View File

@@ -91,8 +91,8 @@ require (
go.opentelemetry.io/otel/trace v1.11.1
golang.org/x/exp v0.0.0-20221114191408-850992195362
golang.org/x/mod v0.6.0
golang.org/x/net v0.1.0
golang.org/x/text v0.4.0
golang.org/x/net v0.3.1-0.20221206200815-1e63c2f08a10
golang.org/x/text v0.5.0
golang.org/x/time v0.0.0-20220609170525-579cf78fd858
golang.org/x/tools v0.2.0
google.golang.org/grpc v1.50.1
@@ -360,8 +360,8 @@ require (
golang.org/x/lint v0.0.0-20210508222113-6edffad5e616 // indirect
golang.org/x/oauth2 v0.0.0-20220909003341-f21342109be1 // indirect
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 // indirect
golang.org/x/sys v0.1.0 // indirect
golang.org/x/term v0.1.0 // indirect
golang.org/x/sys v0.3.0 // indirect
golang.org/x/term v0.3.0 // indirect
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
google.golang.org/api v0.57.0 // indirect
google.golang.org/appengine v1.6.7 // indirect

16
go.sum
View File

@@ -2224,8 +2224,8 @@ golang.org/x/net v0.0.0-20211216030914-fe4d6282115f/go.mod h1:9nx3DQGgdP8bBQD5qx
golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/net v0.0.0-20220624214902-1bab6f366d9e/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.1.0 h1:hZ/3BUoy5aId7sCpA/Tc5lt8DkFgdVS2onTpJsZ/fl0=
golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco=
golang.org/x/net v0.3.1-0.20221206200815-1e63c2f08a10 h1:Frnccbp+ok2GkUS2tC84yAq/U9Vg+0sIO7aRL3T4Xnc=
golang.org/x/net v0.3.1-0.20221206200815-1e63c2f08a10/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE=
golang.org/x/oauth2 v0.0.0-20180724155351-3d292e4d0cdc/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20181017192945-9dcd33a902f4/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
@@ -2395,14 +2395,14 @@ golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0 h1:kunALQeHf1/185U1i0GOB/fy1IPRDDpuoOOqRReG57U=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.3.0 h1:w8ZOecv6NaNa/zC8944JTU3vz4u6Lagfk4RPQxv92NQ=
golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210220032956-6a3ed077a48d/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.1.0 h1:g6Z6vPFA9dYBAF7DWcH6sCcOntplXsDKcliusYijMlw=
golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.3.0 h1:qoo4akIqOcDME5bhc/NgxUdovd6BSS2uMsVjB56q1xI=
golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA=
golang.org/x/text v0.0.0-20160726164857-2910a502d2bf/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
@@ -2413,8 +2413,8 @@ golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.4.0 h1:BrVqGRd7+k1DiOgtnFvAkoQEWQvBc25ouMJM6429SFg=
golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.5.0 h1:OLmvp0KP+FVG99Ct/qFiL/Fhk4zp4QQnZ7b2U+5piUM=
golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=

View File

@@ -0,0 +1,60 @@
[global]
checkNewVersion = false
sendAnonymousUsage = false
[log]
level = "DEBUG"
[entryPoints.websecure]
address = ":4443"
[api]
insecure = true
[providers.file]
filename = "{{ .SelfFilename }}"
## dynamic configuration ##
[http.routers]
[http.routers.router1]
entryPoints = ["websecure"]
service = "service1"
rule = "Host(`snitest.com`)"
[http.routers.router1.tls]
options = "invalidTLSOptions"
[http.routers.router2]
entryPoints = ["websecure"]
service = "service1"
rule = "Host(`snitest.org`)"
[http.routers.router2.tls]
# fallback router
[http.routers.router3]
entryPoints = ["websecure"]
service = "service1"
rule = "Path(`/`)"
[http.routers.router3.tls]
[[http.services.service1.loadBalancer.servers]]
url = "http://127.0.0.1:9010"
[[tls.certificates]]
certFile = "fixtures/https/snitest.com.cert"
keyFile = "fixtures/https/snitest.com.key"
[[tls.certificates]]
certFile = "fixtures/https/snitest.org.cert"
keyFile = "fixtures/https/snitest.org.key"
[tls.options]
[tls.options.default.clientAuth]
# Missing caFile to have an invalid mTLS configuration.
clientAuthType = "RequireAndVerifyClientCert"
[tls.options.invalidTLSOptions.clientAuth]
# Missing caFile to have an invalid mTLS configuration.
clientAuthType = "RequireAndVerifyClientCert"

View File

@@ -34,6 +34,13 @@
[tcp.routers.to-whoami-sni-strict.tls]
options = "bar"
[tcp.routers.to-whoami-invalid-tls]
rule = "HostSNI(`whoami-i.test`)"
service = "whoami-no-cert"
entryPoints = [ "tcp" ]
[tcp.routers.to-whoami-invalid-tls.tls]
options = "invalid"
[tcp.services.whoami-no-cert]
[tcp.services.whoami-no-cert.loadBalancer]
[[tcp.services.whoami-no-cert.loadBalancer.servers]]
@@ -46,3 +53,7 @@
[tls.options.bar]
minVersion = "VersionTLS13"
[tls.options.invalid.clientAuth]
# Missing CA files to have an invalid mTLS configuration.
clientAuthType = "RequireAndVerifyClientCert"

View File

@@ -1226,3 +1226,53 @@ func (s *HTTPSSuite) TestWithDomainFronting(c *check.C) {
c.Assert(err, checker.IsNil)
}
}
// TestWithInvalidTLSOption verifies the behavior when using an invalid tlsOption configuration.
func (s *HTTPSSuite) TestWithInvalidTLSOption(c *check.C) {
backend := startTestServer("9010", http.StatusOK, "server1")
defer backend.Close()
file := s.adaptFile(c, "fixtures/https/https_invalid_tls_options.toml", struct{}{})
defer os.Remove(file)
cmd, display := s.traefikCmd(withConfigFile(file))
defer display(c)
err := cmd.Start()
c.Assert(err, checker.IsNil)
defer s.killCmd(cmd)
// wait for Traefik
err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 500*time.Millisecond, try.BodyContains("Host(`snitest.com`)"))
c.Assert(err, checker.IsNil)
testCases := []struct {
desc string
serverName string
}{
{
desc: "With invalid TLS Options specified",
serverName: "snitest.com",
},
{
desc: "With invalid Default TLS Options",
serverName: "snitest.org",
},
{
desc: "With TLS Options without servername (fallback to default)",
},
}
for _, test := range testCases {
test := test
tlsConfig := &tls.Config{
InsecureSkipVerify: true,
}
if test.serverName != "" {
tlsConfig.ServerName = test.serverName
}
conn, err := tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
c.Assert(err, checker.NotNil, check.Commentf("connected to server successfully"))
c.Assert(conn, checker.IsNil)
}
}

View File

@@ -116,6 +116,14 @@ func (s *TCPSuite) TestTLSOptions(c *check.C) {
_, err = guessWhoTLSMaxVersion("127.0.0.1:8093", "whoami-d.test", true, tls.VersionTLS12)
c.Assert(err, checker.NotNil)
c.Assert(err.Error(), checker.Contains, "protocol version not supported")
// Check that we can't reach a route with an invalid mTLS configuration.
conn, err := tls.Dial("tcp", "127.0.0.1:8093", &tls.Config{
ServerName: "whoami-i.test",
InsecureSkipVerify: true,
})
c.Assert(conn, checker.IsNil)
c.Assert(err, checker.NotNil)
}
func (s *TCPSuite) TestNonTLSFallback(c *check.C) {

View File

@@ -8,6 +8,5 @@ type Experimental struct {
LocalPlugins map[string]plugins.LocalDescriptor `description:"Local plugins configuration." json:"localPlugins,omitempty" toml:"localPlugins,omitempty" yaml:"localPlugins,omitempty" export:"true"`
KubernetesGateway bool `description:"Allow the Kubernetes gateway api provider usage." json:"kubernetesGateway,omitempty" toml:"kubernetesGateway,omitempty" yaml:"kubernetesGateway,omitempty" export:"true"`
HTTP3 bool `description:"Enable HTTP3." json:"http3,omitempty" toml:"http3,omitempty" yaml:"http3,omitempty" export:"true"`
Hub bool `description:"Enable the Traefik Hub provider." json:"hub,omitempty" toml:"hub,omitempty" yaml:"hub,omitempty" export:"true"`
}

View File

@@ -268,16 +268,6 @@ func (c *Configuration) SetEffectiveConfiguration() {
c.Providers.KubernetesGateway = nil
}
if c.Experimental == nil || !c.Experimental.HTTP3 {
for epName, ep := range c.EntryPoints {
if ep.HTTP3 != nil {
ep.HTTP3 = nil
log.Debug().Str(logs.EntryPointName, epName).
Msgf("Disabling HTTP3 configuration for entryPoint %q: HTTP3 is disabled in the experimental configuration section", epName)
}
}
}
// Configure Gateway API provider
if c.Providers.KubernetesGateway != nil {
log.Debug().Msg("Experimental Kubernetes Gateway provider has been activated")

View File

@@ -75,25 +75,6 @@ func host(route *mux.Route, hosts ...string) error {
route.MatcherFunc(func(req *http.Request, _ *mux.RouteMatch) bool {
reqHost := requestdecorator.GetCanonizedHost(req.Context())
if len(reqHost) == 0 {
// If the request is an HTTP/1.0 request, then a Host may not be defined.
if req.ProtoAtLeast(1, 1) {
log.Ctx(req.Context()).Warn().Str("host", req.Host).Msg("Could not retrieve CanonizedHost, rejecting")
}
return false
}
flatH := requestdecorator.GetCNAMEFlatten(req.Context())
if len(flatH) > 0 {
if strings.EqualFold(reqHost, host) || strings.EqualFold(flatH, host) {
return true
}
log.Ctx(req.Context()).Debug().
Str("host", reqHost).
Str("flattenHost", flatH).
Str("matcher", host).
Msg("CNAMEFlattening: resolved Host does not match")
return false
}
@@ -101,6 +82,11 @@ func host(route *mux.Route, hosts ...string) error {
return true
}
flatH := requestdecorator.GetCNAMEFlatten(req.Context())
if len(flatH) > 0 {
return strings.EqualFold(flatH, host)
}
// Check for match on trailing period on host
if last := len(host) - 1; last >= 0 && host[last] == '.' {
h := host[:last]
@@ -136,7 +122,8 @@ func hostRegexp(route *mux.Route, hosts ...string) error {
}
route.MatcherFunc(func(req *http.Request, _ *mux.RouteMatch) bool {
return re.MatchString(req.Host)
return re.MatchString(requestdecorator.GetCanonizedHost(req.Context())) ||
re.MatchString(requestdecorator.GetCNAMEFlatten(req.Context()))
})
return nil

View File

@@ -198,6 +198,7 @@ func TestHostMatcher(t *testing.T) {
rule: "Host(`example.com`)",
expected: map[string]int{
"https://example.com": http.StatusOK,
"https://example.com:8080": http.StatusOK,
"https://example.com/path": http.StatusOK,
"https://example.org": http.StatusNotFound,
"https://example.org/path": http.StatusNotFound,
@@ -227,6 +228,16 @@ func TestHostMatcher(t *testing.T) {
"https://example.org./path": http.StatusNotFound,
},
},
{
desc: "valid Host matcher - matcher with UPPER case",
rule: "Host(`EXAMPLE.COM`)",
expected: map[string]int{
"https://example.com": http.StatusOK,
"https://example.com/path": http.StatusOK,
"https://example.org": http.StatusNotFound,
"https://example.org/path": http.StatusNotFound,
},
},
{
desc: "valid Host matcher - puny-coded emoji",
rule: "Host(`xn--9t9h.com`)",
@@ -258,7 +269,7 @@ func TestHostMatcher(t *testing.T) {
require.NoError(t, err)
// RequestDecorator is necessary for the host rule
// RequestDecorator is necessary for the Host matcher
reqHost := requestdecorator.New(nil)
results := make(map[string]int)
@@ -312,11 +323,23 @@ func TestHostRegexpMatcher(t *testing.T) {
rule: "HostRegexp(`^[a-zA-Z-]+\\.com$`)",
expected: map[string]int{
"https://example.com": http.StatusOK,
"https://example.com:8080": http.StatusOK,
"https://example.com/path": http.StatusOK,
"https://example.org": http.StatusNotFound,
"https://example.org/path": http.StatusNotFound,
},
},
{
desc: "valid HostRegexp matcher with case sensitive regexp",
rule: "HostRegexp(`^[A-Z]+\\.com$`)",
expected: map[string]int{
"https://example.com": http.StatusNotFound,
"https://EXAMPLE.com": http.StatusNotFound,
"https://example.com/path": http.StatusNotFound,
"https://example.org": http.StatusNotFound,
"https://example.org/path": http.StatusNotFound,
},
},
{
desc: "valid HostRegexp matcher with Traefik v2 syntax",
rule: "HostRegexp(`{domain:[a-zA-Z-]+\\.com}`)",
@@ -343,16 +366,18 @@ func TestHostRegexpMatcher(t *testing.T) {
require.Error(t, err)
return
}
require.NoError(t, err)
// RequestDecorator is necessary for the HostRegexp matcher
reqHost := requestdecorator.New(nil)
results := make(map[string]int)
for calledURL := range test.expected {
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, calledURL, http.NoBody)
muxer.ServeHTTP(w, req)
reqHost.ServeHTTP(w, req, muxer.ServeHTTP)
results[calledURL] = w.Code
}
assert.Equal(t, test.expected, results)

View File

@@ -509,7 +509,22 @@ func (p *Provider) parseService(ctx context.Context, service swarmtypes.Service,
if service.Spec.EndpointSpec != nil {
if service.Spec.EndpointSpec.Mode == swarmtypes.ResolutionModeDNSRR {
if dData.ExtraConf.Docker.LBSwarm {
logger.Warn().Msgf("Ignored %s endpoint-mode not supported, service name: %s. Fallback to Traefik load balancing", swarmtypes.ResolutionModeDNSRR, service.Spec.Annotations.Name)
dData.NetworkSettings.Networks = make(map[string]*networkData)
for _, net := range service.Spec.TaskTemplate.Networks {
networkService := networkMap[net.Target]
if networkService != nil {
network := &networkData{
Name: networkService.Name,
ID: net.Target,
Addr: "tasks." + service.Spec.Name,
}
dData.NetworkSettings.Networks[network.Name] = network
} else {
logger.Debug().Msgf("Network not found, id: %s", net.Target)
}
}
} else {
// Each service task IP will get extracted later on in parseTasks
}
} else if service.Spec.EndpointSpec.Mode == swarmtypes.ResolutionModeVIP {
dData.NetworkSettings.Networks = make(map[string]*networkData)

View File

@@ -3,6 +3,7 @@ package router
import (
"context"
"errors"
"fmt"
"net/http"
"github.com/containous/alice"
@@ -17,6 +18,7 @@ import (
httpmuxer "github.com/traefik/traefik/v2/pkg/muxer/http"
"github.com/traefik/traefik/v2/pkg/server/middleware"
"github.com/traefik/traefik/v2/pkg/server/provider"
"github.com/traefik/traefik/v2/pkg/tls"
)
type middlewareBuilder interface {
@@ -36,10 +38,11 @@ type Manager struct {
middlewaresBuilder middlewareBuilder
chainBuilder *middleware.ChainBuilder
conf *runtime.Configuration
tlsManager *tls.Manager
}
// NewManager Creates a new Manager.
func NewManager(conf *runtime.Configuration, serviceManager serviceManager, middlewaresBuilder middlewareBuilder, chainBuilder *middleware.ChainBuilder, metricsRegistry metrics.Registry) *Manager {
// NewManager creates a new Manager.
func NewManager(conf *runtime.Configuration, serviceManager serviceManager, middlewaresBuilder middlewareBuilder, chainBuilder *middleware.ChainBuilder, metricsRegistry metrics.Registry, tlsManager *tls.Manager) *Manager {
return &Manager{
routerHandlers: make(map[string]http.Handler),
serviceManager: serviceManager,
@@ -47,6 +50,7 @@ func NewManager(conf *runtime.Configuration, serviceManager serviceManager, midd
middlewaresBuilder: middlewaresBuilder,
chainBuilder: chainBuilder,
conf: conf,
tlsManager: tlsManager,
}
}
@@ -145,6 +149,17 @@ func (m *Manager) buildRouterHandler(ctx context.Context, routerName string, rou
return handler, nil
}
if routerConfig.TLS != nil {
// Don't build the router if the TLSOptions configuration is invalid.
tlsOptionsName := tls.DefaultTLSConfigName
if len(routerConfig.TLS.Options) > 0 && routerConfig.TLS.Options != tls.DefaultTLSConfigName {
tlsOptionsName = provider.GetQualifiedName(ctx, routerConfig.TLS.Options)
}
if _, err := m.tlsManager.Get(tls.DefaultTLSStoreName, tlsOptionsName); err != nil {
return nil, fmt.Errorf("building router handler: %w", err)
}
}
handler, err := m.buildHTTPHandler(ctx, routerConfig, routerName)
if err != nil {
return nil, err

View File

@@ -22,6 +22,7 @@ import (
"github.com/traefik/traefik/v2/pkg/server/middleware"
"github.com/traefik/traefik/v2/pkg/server/service"
"github.com/traefik/traefik/v2/pkg/testhelpers"
"github.com/traefik/traefik/v2/pkg/tls"
"github.com/traefik/traefik/v2/pkg/types"
)
@@ -319,8 +320,9 @@ func TestRouterManager_Get(t *testing.T) {
serviceManager := service.NewManager(rtConf.Services, nil, nil, roundTripperManager)
middlewaresBuilder := middleware.NewBuilder(rtConf.Middlewares, serviceManager, nil)
chainBuilder := middleware.NewChainBuilder(nil, nil, nil)
tlsManager := tls.NewManager()
routerManager := NewManager(rtConf, serviceManager, middlewaresBuilder, chainBuilder, metrics.NewVoidRegistry())
routerManager := NewManager(rtConf, serviceManager, middlewaresBuilder, chainBuilder, metrics.NewVoidRegistry(), tlsManager)
handlers := routerManager.BuildHandlers(context.Background(), test.entryPoints, false)
@@ -425,8 +427,9 @@ func TestAccessLog(t *testing.T) {
serviceManager := service.NewManager(rtConf.Services, nil, nil, roundTripperManager)
middlewaresBuilder := middleware.NewBuilder(rtConf.Middlewares, serviceManager, nil)
chainBuilder := middleware.NewChainBuilder(nil, nil, nil)
tlsManager := tls.NewManager()
routerManager := NewManager(rtConf, serviceManager, middlewaresBuilder, chainBuilder, metrics.NewVoidRegistry())
routerManager := NewManager(rtConf, serviceManager, middlewaresBuilder, chainBuilder, metrics.NewVoidRegistry(), tlsManager)
handlers := routerManager.BuildHandlers(context.Background(), test.entryPoints, false)
@@ -464,6 +467,7 @@ func TestRuntimeConfiguration(t *testing.T) {
serviceConfig map[string]*dynamic.Service
routerConfig map[string]*dynamic.Router
middlewareConfig map[string]*dynamic.Middleware
tlsOptions map[string]tls.Options
expectedError int
}{
{
@@ -667,7 +671,6 @@ func TestRuntimeConfiguration(t *testing.T) {
},
expectedError: 1,
},
{
desc: "Router with broken middleware",
serviceConfig: map[string]*dynamic.Service{
@@ -698,8 +701,71 @@ func TestRuntimeConfiguration(t *testing.T) {
},
expectedError: 2,
},
{
desc: "Router with broken tlsOption",
serviceConfig: map[string]*dynamic.Service{
"foo-service": {
LoadBalancer: &dynamic.ServersLoadBalancer{
Servers: []dynamic.Server{
{
URL: "http://127.0.0.1",
},
},
},
},
},
middlewareConfig: map[string]*dynamic.Middleware{},
routerConfig: map[string]*dynamic.Router{
"bar": {
EntryPoints: []string{"web"},
Service: "foo-service",
Rule: "Host(`foo.bar`)",
TLS: &dynamic.RouterTLSConfig{
Options: "broken-tlsOption",
},
},
},
tlsOptions: map[string]tls.Options{
"broken-tlsOption": {
ClientAuth: tls.ClientAuth{
ClientAuthType: "foobar",
},
},
},
expectedError: 1,
},
{
desc: "Router with broken default tlsOption",
serviceConfig: map[string]*dynamic.Service{
"foo-service": {
LoadBalancer: &dynamic.ServersLoadBalancer{
Servers: []dynamic.Server{
{
URL: "http://127.0.0.1",
},
},
},
},
},
middlewareConfig: map[string]*dynamic.Middleware{},
routerConfig: map[string]*dynamic.Router{
"bar": {
EntryPoints: []string{"web"},
Service: "foo-service",
Rule: "Host(`foo.bar`)",
TLS: &dynamic.RouterTLSConfig{},
},
},
tlsOptions: map[string]tls.Options{
"default": {
ClientAuth: tls.ClientAuth{
ClientAuthType: "foobar",
},
},
},
expectedError: 1,
},
}
for _, test := range testCases {
test := test
t.Run(test.desc, func(t *testing.T) {
@@ -713,6 +779,9 @@ func TestRuntimeConfiguration(t *testing.T) {
Routers: test.routerConfig,
Middlewares: test.middlewareConfig,
},
TLS: &dynamic.TLSConfiguration{
Options: test.tlsOptions,
},
})
roundTripperManager := service.NewRoundTripperManager(nil)
@@ -720,10 +789,13 @@ func TestRuntimeConfiguration(t *testing.T) {
serviceManager := service.NewManager(rtConf.Services, nil, nil, roundTripperManager)
middlewaresBuilder := middleware.NewBuilder(rtConf.Middlewares, serviceManager, nil)
chainBuilder := middleware.NewChainBuilder(nil, nil, nil)
tlsManager := tls.NewManager()
tlsManager.UpdateConfigs(context.Background(), nil, test.tlsOptions, nil)
routerManager := NewManager(rtConf, serviceManager, middlewaresBuilder, chainBuilder, metrics.NewVoidRegistry())
routerManager := NewManager(rtConf, serviceManager, middlewaresBuilder, chainBuilder, metrics.NewVoidRegistry(), tlsManager)
_ = routerManager.BuildHandlers(context.Background(), entryPoints, false)
_ = routerManager.BuildHandlers(context.Background(), entryPoints, true)
// even though rtConf was passed by argument to the manager builders above,
// it's ok to use it as the result we check, because everything worth checking
@@ -795,8 +867,9 @@ func TestProviderOnMiddlewares(t *testing.T) {
serviceManager := service.NewManager(rtConf.Services, nil, nil, roundTripperManager)
middlewaresBuilder := middleware.NewBuilder(rtConf.Middlewares, serviceManager, nil)
chainBuilder := middleware.NewChainBuilder(nil, nil, nil)
tlsManager := tls.NewManager()
routerManager := NewManager(rtConf, serviceManager, middlewaresBuilder, chainBuilder, metrics.NewVoidRegistry())
routerManager := NewManager(rtConf, serviceManager, middlewaresBuilder, chainBuilder, metrics.NewVoidRegistry(), tlsManager)
_ = routerManager.BuildHandlers(context.Background(), entryPoints, false)
@@ -863,8 +936,9 @@ func BenchmarkRouterServe(b *testing.B) {
serviceManager := service.NewManager(rtConf.Services, nil, nil, staticRoundTripperGetter{res})
middlewaresBuilder := middleware.NewBuilder(rtConf.Middlewares, serviceManager, nil)
chainBuilder := middleware.NewChainBuilder(nil, nil, nil)
tlsManager := tls.NewManager()
routerManager := NewManager(rtConf, serviceManager, middlewaresBuilder, chainBuilder, metrics.NewVoidRegistry())
routerManager := NewManager(rtConf, serviceManager, middlewaresBuilder, chainBuilder, metrics.NewVoidRegistry(), tlsManager)
handlers := routerManager.BuildHandlers(context.Background(), entryPoints, false)

View File

@@ -105,18 +105,21 @@ func (m *Manager) buildEntryPointHandler(ctx context.Context, configs map[string
router.SetHTTPHandler(handlerHTTP)
// Even though the error is seemingly ignored (aside from logging it),
// we actually rely later on the fact that a tls config is nil (which happens when an error is returned) to take special steps
// when assigning a handler to a route.
defaultTLSConf, err := m.tlsManager.Get(traefiktls.DefaultTLSStoreName, traefiktls.DefaultTLSConfigName)
if err != nil {
log.Ctx(ctx).Error().Err(err).Msg("Error during the build of the default TLS configuration")
}
// Keyed by domain. The source of truth for doing SNI checking, and for what TLS
// options will actually be used for the connection.
// Keyed by domain. The source of truth for doing SNI checking (domain fronting).
// As soon as there's (at least) two different tlsOptions found for the same domain,
// we set the value to the default TLS conf.
tlsOptionsForHost := map[string]string{}
// Keyed by domain, then by options reference.
// The actual source of truth for what TLS options will actually be used for the connection.
// As opposed to tlsOptionsForHost, it keeps track of all the (different) TLS
// options that occur for a given host name, so that later on we can set relevant
// errors and logging for all the routers concerned (i.e. wrongly configured).
@@ -144,21 +147,20 @@ func (m *Manager) buildEntryPointHandler(ctx context.Context, configs map[string
}
if len(domains) == 0 {
// Extra Host(*) rule, for HTTPS routers with no Host rule, and for requests for
// which the SNI does not match _any_ of the other existing routers Host. This is
// only about choosing the TLS configuration. The actual routing will be done
// further on by the HTTPS handler. See examples below.
// Extra Host(*) rule, for HTTPS routers with no Host rule,
// and for requests for which the SNI does not match _any_ of the other existing routers Host.
// This is only about choosing the TLS configuration.
// The actual routing will be done further on by the HTTPS handler.
// See examples below.
router.AddHTTPTLSConfig("*", defaultTLSConf)
// The server name (from a Host(SNI) rule) is the only parameter (available in
// HTTP routing rules) on which we can map a TLS config, because it is the only one
// accessible before decryption (we obtain it during the ClientHello). Therefore,
// when a router has no Host rule, it does not make any sense to specify some TLS
// options. Consequently, when it comes to deciding what TLS config will be used,
// for a request that will match an HTTPS router with no Host rule, the result will
// depend on the _others_ existing routers (their Host rule, to be precise), and
// the TLS options associated with them, even though they don't match the incoming
// request. Consider the following examples:
// The server name (from a Host(SNI) rule) is the only parameter (available in HTTP routing rules) on which we can map a TLS config,
// because it is the only one accessible before decryption (we obtain it during the ClientHello).
// Therefore, when a router has no Host rule, it does not make any sense to specify some TLS options.
// Consequently, when it comes to deciding what TLS config will be used,
// for a request that will match an HTTPS router with no Host rule,
// the result will depend on the _others_ existing routers (their Host rule, to be precise), and the TLS options associated with them,
// even though they don't match the incoming request. Consider the following examples:
// # conf1
// httpRouter1:
@@ -172,17 +174,19 @@ func (m *Manager) buildEntryPointHandler(ctx context.Context, configs map[string
// httpRouter2:
// rule: Host("foo.com") && PathPrefix("/bar")
// tlsoptions: myTLSOptions
// # When a request for "/foo" comes, even though it won't be routed by
// httpRouter2, if its SNI is set to foo.com, myTLSOptions will be used for the TLS
// connection. Otherwise, it will fallback to the default TLS config.
// # When a request for "/foo" comes, even though it won't be routed by httpRouter2,
// # if its SNI is set to foo.com, myTLSOptions will be used for the TLS connection.
// # Otherwise, it will fallback to the default TLS config.
logger.Warn().Msgf("No domain found in rule %v, the TLS options applied for this router will depend on the SNI of each request", routerHTTPConfig.Rule)
}
tlsConf, err := m.tlsManager.Get(traefiktls.DefaultTLSStoreName, tlsOptionsName)
if err != nil {
routerHTTPConfig.AddError(err, true)
logger.Error().Err(err).Send()
continue
// Even though the error is seemingly ignored (aside from logging it),
// we actually rely later on the fact that a tls config is nil (which happens when an error is returned) to take special steps
// when assigning a handler to a route.
tlsConf, tlsConfErr := m.tlsManager.Get(traefiktls.DefaultTLSStoreName, tlsOptionsName)
if tlsConfErr != nil {
// Note: we do not call AddError here because we already did so when buildRouterHandler errored for the same reason.
logger.Error().Err(tlsConfErr).Send()
}
for _, domain := range domains {
@@ -206,6 +210,7 @@ func (m *Manager) buildEntryPointHandler(ctx context.Context, configs map[string
sniCheck := snicheck.New(tlsOptionsForHost, handlerHTTPS)
// Keep in mind that defaultTLSConf might be nil here.
router.SetHTTPSHandler(sniCheck, defaultTLSConf)
logger := log.Ctx(ctx)
@@ -219,22 +224,42 @@ func (m *Manager) buildEntryPointHandler(ctx context.Context, configs map[string
break
}
logger.Debug().Msgf("Adding route for %s with TLS options %s", hostSNI, optionsName)
router.AddHTTPTLSConfig(hostSNI, config)
} else {
routers := make([]string, 0, len(tlsConfigs))
for _, v := range tlsConfigs {
configsHTTP[v.routerName].AddError(fmt.Errorf("found different TLS options for routers on the same host %v, so using the default TLS options instead", hostSNI), false)
routers = append(routers, v.routerName)
if config == nil {
// we use nil config as a signal to insert a handler
// that enforces that TLS connection attempts to the corresponding (broken) router should fail.
logger.Debug().Msgf("Adding special closing route for %s because broken TLS options %s", hostSNI, optionsName)
router.AddHTTPTLSConfig(hostSNI, nil)
continue
}
logger.Warn().Msgf("Found different TLS options for routers on the same host %v, so using the default TLS options instead for these routers: %#v", hostSNI, routers)
router.AddHTTPTLSConfig(hostSNI, defaultTLSConf)
logger.Debug().Msgf("Adding route for %s with TLS options %s", hostSNI, optionsName)
router.AddHTTPTLSConfig(hostSNI, config)
continue
}
// multiple tlsConfigs
routers := make([]string, 0, len(tlsConfigs))
for _, v := range tlsConfigs {
configsHTTP[v.routerName].AddError(fmt.Errorf("found different TLS options for routers on the same host %v, so using the default TLS options instead", hostSNI), false)
routers = append(routers, v.routerName)
}
logger.Warn().Msgf("Found different TLS options for routers on the same host %v, so using the default TLS options instead for these routers: %#v", hostSNI, routers)
if defaultTLSConf == nil {
logger.Debug().Msgf("Adding special closing route for %s because broken default TLS options", hostSNI)
}
router.AddHTTPTLSConfig(hostSNI, defaultTLSConf)
}
m.addTCPHandlers(ctx, configs, router)
return router, nil
}
// addTCPHandlers creates the TCP handlers defined in configs, and adds them to router.
func (m *Manager) addTCPHandlers(ctx context.Context, configs map[string]*runtime.TCPRouterInfo, router *Router) {
for routerName, routerConfig := range configs {
logger := log.Ctx(ctx).With().Str(logs.RouterName, routerName).Logger()
ctxRouter := logger.WithContext(provider.AddInContext(ctx, routerName))
@@ -253,13 +278,6 @@ func (m *Manager) buildEntryPointHandler(ctx context.Context, configs map[string
continue
}
handler, err := m.buildTCPHandler(ctxRouter, routerConfig)
if err != nil {
routerConfig.AddError(err, true)
logger.Error().Err(err).Send()
continue
}
domains, err := tcpmuxer.ParseHostSNI(routerConfig.Rule)
if err != nil {
routerErr := fmt.Errorf("invalid rule: %q , %w", routerConfig.Rule, err)
@@ -276,6 +294,16 @@ func (m *Manager) buildEntryPointHandler(ctx context.Context, configs map[string
logger.Error().Err(routerErr).Send()
}
var handler tcp.Handler
if routerConfig.TLS == nil || routerConfig.TLS.Passthrough {
handler, err = m.buildTCPHandler(ctxRouter, routerConfig)
if err != nil {
routerConfig.AddError(err, true)
logger.Error().Err(err).Send()
continue
}
}
if routerConfig.TLS == nil {
logger.Debug().Msgf("Adding route for %q", routerConfig.Rule)
if err := router.AddRoute(routerConfig.Rule, routerConfig.Priority, handler); err != nil {
@@ -287,7 +315,7 @@ func (m *Manager) buildEntryPointHandler(ctx context.Context, configs map[string
if routerConfig.TLS.Passthrough {
logger.Debug().Msgf("Adding Passthrough route for %q", routerConfig.Rule)
if err := router.AddRouteTLS(routerConfig.Rule, routerConfig.Priority, handler, nil); err != nil {
if err := router.muxerTCPTLS.AddRoute(routerConfig.Rule, routerConfig.Priority, handler); err != nil {
routerConfig.AddError(err, true)
logger.Error().Err(err).Send()
}
@@ -318,6 +346,14 @@ func (m *Manager) buildEntryPointHandler(ctx context.Context, configs map[string
if err != nil {
routerConfig.AddError(err, true)
logger.Error().Err(err).Send()
logger.Debug().Msgf("Adding special TLS closing route for %q because broken TLS options %s", routerConfig.Rule, tlsOptionsName)
err = router.muxerTCPTLS.AddRoute(routerConfig.Rule, routerConfig.Priority, &brokenTLSRouter{})
if err != nil {
routerConfig.AddError(err, true)
logger.Error().Err(err).Send()
}
continue
}
@@ -329,20 +365,30 @@ func (m *Manager) buildEntryPointHandler(ctx context.Context, configs map[string
// rule: HostSNI(foo.com) && ClientIP(IP2)
// tlsOption: tlsTwo
// i.e. same HostSNI but different tlsOptions
// This is only applicable if the muxer can decide about the routing _before_
// telling the client about the tlsConf (i.e. before the TLS HandShake). This seems
// to be the case so far with the existing matchers (HostSNI, and ClientIP), so
// it's all good. Otherwise, we would have to do as for HTTPS, i.e. disallow
// different TLS configs for the same HostSNIs.
// This is only applicable if the muxer can decide about the routing _before_ telling the client about the tlsConf (i.e. before the TLS HandShake).
// This seems to be the case so far with the existing matchers (HostSNI, and ClientIP), so it's all good.
// Otherwise, we would have to do as for HTTPS, i.e. disallow different TLS configs for the same HostSNIs.
handler, err = m.buildTCPHandler(ctxRouter, routerConfig)
if err != nil {
routerConfig.AddError(err, true)
logger.Error().Err(err).Send()
continue
}
handler = &tcp.TLSHandler{
Next: handler,
Config: tlsConf,
}
logger.Debug().Msgf("Adding TLS route for %q", routerConfig.Rule)
if err := router.AddRouteTLS(routerConfig.Rule, routerConfig.Priority, handler, tlsConf); err != nil {
err = router.muxerTCPTLS.AddRoute(routerConfig.Rule, routerConfig.Priority, handler)
if err != nil {
routerConfig.AddError(err, true)
logger.Error().Err(err).Send()
}
}
return router, nil
}
func (m *Manager) buildTCPHandler(ctx context.Context, router *runtime.TCPRouterInfo) (tcp.Handler, error) {

View File

@@ -27,19 +27,20 @@ type Router struct {
muxerHTTPS tcpmuxer.Muxer
// Forwarder handlers.
// Handles all HTTP requests.
// httpForwarder handles all HTTP requests.
httpForwarder tcp.Handler
// Handles (indirectly through muxerHTTPS, or directly) all HTTPS requests.
// httpsForwarder handles (indirectly through muxerHTTPS, or directly) all HTTPS requests.
httpsForwarder tcp.Handler
// Neither is used directly, but they are held here, and recreated on config
// reload, so that they can be passed to the Switcher at the end of the config
// reload phase.
// Neither is used directly, but they are held here, and recreated on config reload,
// so that they can be passed to the Switcher at the end of the config reload phase.
httpHandler http.Handler
httpsHandler http.Handler
// TLS configs.
httpsTLSConfig *tls.Config // default TLS config
httpsTLSConfig *tls.Config // default TLS config
// hostHTTPTLSConfig contains TLS configs keyed by SNI.
// A nil config is the hint to set up a brokenTLSRouter.
hostHTTPTLSConfig map[string]*tls.Config // TLS configs keyed by SNI
}
@@ -80,11 +81,11 @@ func (r *Router) GetTLSGetClientInfo() func(info *tls.ClientHelloInfo) (*tls.Con
// ServeTCP forwards the connection to the right TCP/HTTP handler.
func (r *Router) ServeTCP(conn tcp.WriteCloser) {
// Handling Non-TLS TCP connection early if there is neither HTTP(S) nor TLS
// routers on the entryPoint, and if there is at least one non-TLS TCP router.
// In the case of a non-TLS TCP client (that does not "send" first), we would
// block forever on clientHelloInfo, which is why we want to detect and
// handle that case first and foremost.
// Handling Non-TLS TCP connection early if there is neither HTTP(S) nor TLS routers on the entryPoint,
// and if there is at least one non-TLS TCP router.
// In the case of a non-TLS TCP client (that does not "send" first),
// we would block forever on clientHelloInfo,
// which is why we want to detect and handle that case first and foremost.
if r.muxerTCP.HasRoutes() && !r.muxerTCPTLS.HasRoutes() && !r.muxerHTTPS.HasRoutes() {
connData, err := tcpmuxer.NewConnData("", conn, nil)
if err != nil {
@@ -163,9 +164,9 @@ func (r *Router) ServeTCP(conn tcp.WriteCloser) {
// (wrapped inside the returned handler) requested for the given HostSNI.
handlerHTTPS, catchAllHTTPS := r.muxerHTTPS.Match(connData)
if handlerHTTPS != nil && !catchAllHTTPS {
// In order not to depart from the behavior in 2.6, we only allow an HTTPS router
// to take precedence over a TCP-TLS router if it is _not_ an HostSNI(*) router (so
// basically any router that has a specific HostSNI based rule).
// In order not to depart from the behavior in 2.6,
// we only allow an HTTPS router to take precedence over a TCP-TLS router if it is _not_ an HostSNI(*) router
// (so basically any router that has a specific HostSNI based rule).
handlerHTTPS.ServeTCP(r.GetConn(conn, hello.peeked))
return
}
@@ -191,7 +192,7 @@ func (r *Router) ServeTCP(conn tcp.WriteCloser) {
return
}
// needed to handle 404s for HTTPS, as well as all non-Host (e.g. PathPrefix) matches.
// To handle 404s for HTTPS.
if r.httpsForwarder != nil {
r.httpsForwarder.ServeTCP(r.GetConn(conn, hello.peeked))
return
@@ -205,19 +206,6 @@ func (r *Router) AddRoute(rule string, priority int, target tcp.Handler) error {
return r.muxerTCP.AddRoute(rule, priority, target)
}
// AddRouteTLS defines a handler for a given rule and sets the matching tlsConfig.
func (r *Router) AddRouteTLS(rule string, priority int, target tcp.Handler, config *tls.Config) error {
// TLS PassThrough
if config == nil {
return r.muxerTCPTLS.AddRoute(rule, priority, target)
}
return r.muxerTCPTLS.AddRoute(rule, priority, &tcp.TLSHandler{
Next: target,
Config: config,
})
}
// AddHTTPTLSConfig defines a handler for a given sniHost and sets the matching tlsConfig.
func (r *Router) AddHTTPTLSConfig(sniHost string, config *tls.Config) {
if r.hostHTTPTLSConfig == nil {
@@ -253,20 +241,44 @@ func (r *Router) SetHTTPForwarder(handler tcp.Handler) {
r.httpForwarder = handler
}
// SetHTTPSForwarder sets the tcp handler that will forward the TLS connections to an http handler.
// brokenTLSRouter is associated to a Host(SNI) rule for which we know the TLS conf is broken.
// It is used to make sure any attempt to connect to that hostname is closed,
// since we cannot proceed with the intended TLS conf.
type brokenTLSRouter struct{}
// ServeTCP instantly closes the connection.
func (t *brokenTLSRouter) ServeTCP(conn tcp.WriteCloser) {
_ = conn.Close()
}
// SetHTTPSForwarder sets the tcp handler that will forward the TLS connections to an HTTP handler.
// It also sets up each TLS handler (with its TLS config) for each Host(SNI) rule we previously kept track of.
// It sets up a special handler that closes the connection if a TLS config is nil.
func (r *Router) SetHTTPSForwarder(handler tcp.Handler) {
for sniHost, tlsConf := range r.hostHTTPTLSConfig {
var tcpHandler tcp.Handler
if tlsConf == nil {
tcpHandler = &brokenTLSRouter{}
} else {
tcpHandler = &tcp.TLSHandler{
Next: handler,
Config: tlsConf,
}
}
// muxerHTTPS only contains single HostSNI rules (and no other kind of rules),
// so there's no need for specifying a priority for them.
err := r.muxerHTTPS.AddRoute("HostSNI(`"+sniHost+"`)", 0, &tcp.TLSHandler{
Next: handler,
Config: tlsConf,
})
err := r.muxerHTTPS.AddRoute("HostSNI(`"+sniHost+"`)", 0, tcpHandler)
if err != nil {
log.Error().Err(err).Msg("Error while adding route for host")
}
}
if r.httpsTLSConfig == nil {
r.httpsForwarder = &brokenTLSRouter{}
return
}
r.httpsForwarder = &tcp.TLSHandler{
Next: handler,
Config: r.httpsTLSConfig,
@@ -286,15 +298,14 @@ func (r *Router) SetHTTPSHandler(handler http.Handler, config *tls.Config) {
// Conn is a connection proxy that handles Peeked bytes.
type Conn struct {
// Peeked are the bytes that have been read from Conn for the
// purposes of route matching, but have not yet been consumed
// by Read calls. It is set to nil by Read when fully consumed.
// Peeked are the bytes that have been read from Conn for the purposes of route matching,
// but have not yet been consumed by Read calls.
// It set to nil by Read when fully consumed.
Peeked []byte
// Conn is the underlying connection.
// It can be type asserted against *net.TCPConn or other types
// as needed. It should not be read from directly unless
// Peeked is nil.
// It can be type asserted against *net.TCPConn or other types as needed.
// It should not be read from directly unless Peeked is nil.
tcp.WriteCloser
}
@@ -331,15 +342,14 @@ func clientHelloInfo(br *bufio.Reader) (*clientHello, error) {
return nil, err
}
// No valid TLS record has a type of 0x80, however SSLv2 handshakes
// start with a uint16 length where the MSB is set and the first record
// is always < 256 bytes long. Therefore typ == 0x80 strongly suggests
// an SSLv2 client.
// No valid TLS record has a type of 0x80, however SSLv2 handshakes start with an uint16 length
// where the MSB is set and the first record is always < 256 bytes long.
// Therefore, typ == 0x80 strongly suggests an SSLv2 client.
const recordTypeSSLv2 = 0x80
const recordTypeHandshake = 0x16
if hdr[0] != recordTypeHandshake {
if hdr[0] == recordTypeSSLv2 {
// we consider SSLv2 as TLS and it will be refused by real TLS handshake.
// we consider SSLv2 as TLS, and it will be refused by real TLS handshake.
return &clientHello{
isTLS: true,
peeked: getPeeked(br),

View File

@@ -930,7 +930,7 @@ func TestPostgres(t *testing.T) {
// This test requires to have a TLS route, but does not actually check the
// content of the handler. It would require to code a TLS handshake to
// check the SNI and content of the handlerFunc.
err = router.AddRouteTLS("HostSNI(`test.localhost`)", 0, nil, &tls.Config{})
err = router.muxerTCPTLS.AddRoute("HostSNI(`test.localhost`)", 0, nil)
require.NoError(t, err)
err = router.AddRoute("HostSNI(`*`)", 0, tcp2.HandlerFunc(func(conn tcp2.WriteCloser) {

View File

@@ -79,7 +79,7 @@ func (f *RouterFactory) CreateRouters(rtConf *runtime.Configuration) (map[string
middlewaresBuilder := middleware.NewBuilder(rtConf.Middlewares, serviceManager, f.pluginBuilder)
routerManager := router.NewManager(rtConf, serviceManager, middlewaresBuilder, f.chainBuilder, f.metricsRegistry)
routerManager := router.NewManager(rtConf, serviceManager, middlewaresBuilder, f.chainBuilder, f.metricsRegistry, f.tlsManager)
handlersNonTLS := routerManager.BuildHandlers(ctx, f.entryPointsTCP, false)
handlersTLS := routerManager.BuildHandlers(ctx, f.entryPointsTCP, true)

View File

@@ -158,19 +158,16 @@ func (m *Manager) Get(storeName, configName string) (*tls.Config, error) {
m.lock.RLock()
defer m.lock.RUnlock()
var tlsConfig *tls.Config
var err error
sniStrict := false
config, ok := m.configs[configName]
if ok {
sniStrict = config.SniStrict
tlsConfig, err = buildTLSConfig(config)
} else {
err = fmt.Errorf("unknown TLS options: %s", configName)
if !ok {
return nil, fmt.Errorf("unknown TLS options: %s", configName)
}
sniStrict = config.SniStrict
tlsConfig, err := buildTLSConfig(config)
if err != nil {
tlsConfig = &tls.Config{}
return nil, fmt.Errorf("building TLS config: %w", err)
}
store := m.getStore(storeName)
@@ -178,7 +175,7 @@ func (m *Manager) Get(storeName, configName string) (*tls.Config, error) {
err = fmt.Errorf("TLS store %s not found", storeName)
}
acmeTLSStore := m.getStore(tlsalpn01.ACMETLS1Protocol)
if acmeTLSStore == nil {
if acmeTLSStore == nil && err == nil {
err = fmt.Errorf("ACME TLS store %s not found", tlsalpn01.ACMETLS1Protocol)
}
@@ -189,15 +186,12 @@ func (m *Manager) Get(storeName, configName string) (*tls.Config, error) {
certificate := acmeTLSStore.GetBestCertificate(clientHello)
if certificate == nil {
log.Debug().Msgf("TLS: no certificate for TLSALPN challenge: %s", domainToCheck)
// We want the user to eventually get the (alertUnrecognizedName) "unrecognized
// name" error.
// Unfortunately, if we returned an error here, since we can't use
// the unexported error (errNoCertificates) that our caller (config.getCertificate
// in crypto/tls) uses as a sentinel, it would report an (alertInternalError)
// "internal error" instead of an alertUnrecognizedName.
// Which is why we return no error, and we let the caller detect that there's
// actually no certificate, and fall back into the flow that will report
// the desired error.
// We want the user to eventually get the (alertUnrecognizedName) "unrecognized name" error.
// Unfortunately, if we returned an error here,
// since we can't use the unexported error (errNoCertificates) that our caller (config.getCertificate in crypto/tls) uses as a sentinel,
// it would report an (alertInternalError) "internal error" instead of an alertUnrecognizedName.
// Which is why we return no error, and we let the caller detect that there's actually no certificate,
// and fall back into the flow that will report the desired error.
// https://cs.opensource.google/go/go/+/dev.boringcrypto.go1.17:src/crypto/tls/common.go;l=1058
return nil, nil
}

View File

@@ -119,8 +119,9 @@ func TestManager_Get(t *testing.T) {
}}
tlsConfigs := map[string]Options{
"foo": {MinVersion: "VersionTLS12"},
"bar": {MinVersion: "VersionTLS11"},
"foo": {MinVersion: "VersionTLS12"},
"bar": {MinVersion: "VersionTLS11"},
"invalid": {CurvePreferences: []string{"42"}},
}
testCases := []struct {
@@ -140,15 +141,20 @@ func TestManager_Get(t *testing.T) {
expectedMinVersion: uint16(tls.VersionTLS11),
},
{
desc: "Get an tls config from an invalid name",
desc: "Get a tls config from an invalid name",
tlsOptionsName: "unknown",
expectedError: true,
},
{
desc: "Get an tls config from unexisting 'default' name",
desc: "Get a tls config from unexisting 'default' name",
tlsOptionsName: "default",
expectedError: true,
},
{
desc: "Get an invalid tls config",
tlsOptionsName: "invalid",
expectedError: true,
},
}
tlsManager := NewManager()
@@ -161,42 +167,13 @@ func TestManager_Get(t *testing.T) {
config, err := tlsManager.Get("default", test.tlsOptionsName)
if test.expectedError {
assert.Error(t, err)
require.Nil(t, config)
require.Error(t, err)
return
}
assert.NoError(t, err)
assert.Equal(t, config.MinVersion, test.expectedMinVersion)
})
}
}
func TestManager_Get_GetCertificate(t *testing.T) {
testCases := []struct {
desc string
expectedGetConfigErr require.ErrorAssertionFunc
expectedCertificate assert.ValueAssertionFunc
}{
{
desc: "Get a default certificate from non-existing store",
expectedGetConfigErr: require.Error,
expectedCertificate: assert.Nil,
},
}
tlsManager := NewManager()
for _, test := range testCases {
test := test
t.Run(test.desc, func(t *testing.T) {
t.Parallel()
config, err := tlsManager.Get("default", "foo")
test.expectedGetConfigErr(t, err)
certificate, err := config.GetCertificate(&tls.ClientHelloInfo{})
require.NoError(t, err)
test.expectedCertificate(t, certificate)
assert.Equal(t, config.MinVersion, test.expectedMinVersion)
})
}
}

View File

@@ -4,11 +4,11 @@ RepositoryName = "traefik"
OutputType = "file"
FileName = "traefik_changelog.md"
# example new bugfix v2.9.5
# example new bugfix v2.9.6
CurrentRef = "v2.9"
PreviousRef = "v2.9.4"
PreviousRef = "v2.9.5"
BaseBranch = "v2.9"
FutureCurrentRefName = "v2.9.5"
FutureCurrentRefName = "v2.9.6"
ThresholdPreviousRef = 10
ThresholdCurrentRef = 10

View File

@@ -4,11 +4,11 @@ RepositoryName = "traefik"
OutputType = "file"
FileName = "traefik_changelog.md"
# example RC5 of v2.9.0
CurrentRef = "v2.9"
PreviousRef = "v2.9.0-rc4"
BaseBranch = "v2.9"
FutureCurrentRefName = "v2.9.0-rc5"
# example beta2 of v3.0.0
CurrentRef = "master"
PreviousRef = "v3.0.0-beta1"
BaseBranch = "master"
FutureCurrentRefName = "v3.0.0-beta2"
ThresholdPreviousRef = 10
ThresholdCurrentRef = 10