Skip to content

Commit

Permalink
Add validation for wildcard server names
Browse files Browse the repository at this point in the history
  • Loading branch information
aledbf committed Oct 26, 2020
1 parent cdd6437 commit d74ea25
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
13 changes: 13 additions & 0 deletions internal/ingress/controller/template/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@ var (
"buildMirrorLocations": buildMirrorLocations,
"shouldLoadAuthDigestModule": shouldLoadAuthDigestModule,
"shouldLoadInfluxDBModule": shouldLoadInfluxDBModule,
"buildServerName": buildServerName,
}
)

Expand Down Expand Up @@ -1459,3 +1460,15 @@ func shouldLoadInfluxDBModule(s interface{}) bool {

return false
}

// buildServerName ensures wildcard hostnames are valid
func buildServerName(hostname string) string {
if !strings.HasPrefix(hostname, "*") {
return hostname
}

hostname = strings.Replace(hostname, "*.", "", 1)
parts := strings.Split(hostname, ".")

return `~^(?<subdomain>[\w-]+)\.` + strings.Join(parts, "\\.") + `$`
}
21 changes: 21 additions & 0 deletions internal/ingress/controller/template/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1448,3 +1448,24 @@ func TestModSecurityForLocation(t *testing.T) {
}
}
}

func TestBuildServerName(t *testing.T) {

testCases := []struct {
title string
hostname string
expected string
}{
{"simple domain", "foo.bar", "foo.bar"},
{"simple www domain", "www.foo.bar", "www.foo.bar"},
{"wildcard domain", "*.foo.bar", "~^(?<subdomain>[\\w-]+)\\.foo\\.bar$"},
{"wildcard two levels domain", "*.sub.foo.bar", "~^(?<subdomain>[\\w-]+)\\.sub\\.foo\\.bar$"},
}

for _, testCase := range testCases {
result := buildServerName(testCase.hostname)
if result != testCase.expected {
t.Errorf("%v: expected '%v' but returned '%v'", testCase.title, testCase.expected, result)
}
}
}
2 changes: 1 addition & 1 deletion rootfs/etc/nginx/template/nginx.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -577,7 +577,7 @@ http {

## start server {{ $server.Hostname }}
server {
server_name {{ $server.Hostname }} {{range $server.Aliases }}{{ . }} {{ end }};
server_name {{ buildServerName $server.Hostname }} {{range $server.Aliases }}{{ . }} {{ end }};

{{ if gt (len $cfg.BlockUserAgents) 0 }}
if ($block_ua) {
Expand Down

0 comments on commit d74ea25

Please sign in to comment.