From 18e254ac710480212a5a5aefd27a5f225ba6dbde Mon Sep 17 00:00:00 2001 From: Ruslan Date: Mon, 16 Dec 2024 16:50:25 +0200 Subject: [PATCH] feat: add domain validation to prevent parsing of non-valid domains --- internal/hostsfile/processor.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/internal/hostsfile/processor.go b/internal/hostsfile/processor.go index 71ad68a..d9eac73 100644 --- a/internal/hostsfile/processor.go +++ b/internal/hostsfile/processor.go @@ -2,6 +2,7 @@ package hostsfile import ( "fmt" + "regexp" "slices" "strings" "sync" @@ -13,6 +14,10 @@ import ( const localhost = "127.0.0.1" +// first part (before +): subdomain pattern. +// second part (after +): top level domain (TLD) pattern. +var validDomainRegexp = regexp.MustCompile(`^([a-z0-9_-]{0,63}\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$`) + // Processor is a structure that is responsible for processing blocklists, // whitelists and preparing the result to save to hosts file. type Processor struct { @@ -187,6 +192,10 @@ func (p *Processor) processContent(content string) map[string]LineContent { continue } + if !p.isValidDomain(domainName) { + continue + } + lineContent := LineContent{ ipAddress: localhost, domainName: domainName, @@ -298,6 +307,10 @@ func (p *Processor) IsSkippedDomain(domain string) bool { return slices.Contains(skipList, domain) } +func (p *Processor) isValidDomain(domain string) bool { + return validDomainRegexp.MatchString(domain) +} + func (r Result) FormatToHostsfile() string { var builder strings.Builder