Skip to content

Commit

Permalink
feat: add domain validation to prevent parsing of non-valid domains
Browse files Browse the repository at this point in the history
  • Loading branch information
WIttyJudge committed Dec 16, 2024
1 parent 1e060cb commit 18e254a
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions internal/hostsfile/processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package hostsfile

import (
"fmt"
"regexp"
"slices"
"strings"
"sync"
Expand All @@ -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 {
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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

Expand Down

0 comments on commit 18e254a

Please sign in to comment.