Skip to content

Commit

Permalink
Improve domain validation function
Browse files Browse the repository at this point in the history
Now FQDNs are accepted as well (with trailing dot).
Empty strings are not considered valid.
Label length for IDNs is checked using Punycode form as it should.

See #554
  • Loading branch information
foxcpp committed Jan 8, 2023
1 parent 99a60e5 commit e6518a0
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
14 changes: 11 additions & 3 deletions framework/address/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ package address

import (
"strings"

"golang.org/x/net/idna"
)

/*
Expand Down Expand Up @@ -109,17 +111,23 @@ func ValidMailboxName(mbox string) bool {

// ValidDomain checks whether the specified string is a valid DNS domain.
func ValidDomain(domain string) bool {
if len(domain) > 255 {
if len(domain) > 255 || len(domain) == 0 {
return false
}
if strings.HasPrefix(domain, ".") || strings.HasSuffix(domain, ".") {
if strings.HasPrefix(domain, ".") {
return false
}
if strings.Contains(domain, "..") {
return false
}

labels := strings.Split(domain, ".")
// Length checks are to be applied to A-labels form.
// maddy uses U-labels representation across the code (for lookups, etc).
domainASCII, err := idna.ToASCII(domain)
if err != nil {
return false
}
labels := strings.Split(domainASCII, ".")
for _, label := range labels {
if len(label) > 64 {
return false
Expand Down
20 changes: 20 additions & 0 deletions framework/address/validation_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package address_test

import (
"strings"
"testing"

"github.com/foxcpp/maddy/framework/address"
Expand All @@ -11,3 +12,22 @@ func TestValidMailboxName(t *testing.T) {
t.Error("caddy.bug should be valid mailbox name")
}
}

func TestValidDomain(t *testing.T) {
for _, c := range []struct {
Domain string
Valid bool
}{
{Domain: "maddy.email", Valid: true},
{Domain: "", Valid: false},
{Domain: "maddy.email.", Valid: true},
{Domain: "..", Valid: false},
{Domain: strings.Repeat("a", 256), Valid: false},
{Domain: "äõäoaõoäaõaäõaoäaoaäõoaäooaoaoiuaiauäõiuüõaõäiauõaaa.tld", Valid: true}, // https://github.com/foxcpp/maddy/issues/554
{Domain: "xn--oaoaaaoaoaoaooaoaoiuaiauiuaiauaaa-f1cadccdcmd01eddchqcbe07a.tld", Valid: true}, // https://github.com/foxcpp/maddy/issues/554
} {
if actual := address.ValidDomain(c.Domain); actual != c.Valid {
t.Errorf("expected domain %v to be valid=%v, but got %v", c.Domain, c.Valid, actual)
}
}
}

0 comments on commit e6518a0

Please sign in to comment.