Add validation for wildcard server names

This commit is contained in:
Manuel Alejandro de Brito Fontes 2020-10-19 19:40:06 -03:00
parent cdd6437380
commit d74ea25df8
3 changed files with 35 additions and 1 deletions

View file

@ -182,6 +182,7 @@ var (
"buildMirrorLocations": buildMirrorLocations, "buildMirrorLocations": buildMirrorLocations,
"shouldLoadAuthDigestModule": shouldLoadAuthDigestModule, "shouldLoadAuthDigestModule": shouldLoadAuthDigestModule,
"shouldLoadInfluxDBModule": shouldLoadInfluxDBModule, "shouldLoadInfluxDBModule": shouldLoadInfluxDBModule,
"buildServerName": buildServerName,
} }
) )
@ -1459,3 +1460,15 @@ func shouldLoadInfluxDBModule(s interface{}) bool {
return false 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, "\\.") + `$`
}

View file

@ -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)
}
}
}

View file

@ -577,7 +577,7 @@ http {
## start server {{ $server.Hostname }} ## start server {{ $server.Hostname }}
server { 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 gt (len $cfg.BlockUserAgents) 0 }}
if ($block_ua) { if ($block_ua) {