Skip to content

Commit b9c43c8

Browse files
committed
Add the ability to log blocked queries
1 parent 9f8bce2 commit b9c43c8

6 files changed

Lines changed: 115 additions & 30 deletions

File tree

dnscrypt-proxy/common.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"encoding/binary"
55
"errors"
66
"net"
7+
"strconv"
78
"strings"
89
"unicode"
910
)
@@ -97,3 +98,8 @@ func StringTwoFields(str string) (string, string, bool) {
9798
}
9899
return a, b, true
99100
}
101+
102+
func StringQuote(str string) string {
103+
str = strconv.QuoteToGraphic(str)
104+
return str[1 : len(str)-1]
105+
}

dnscrypt-proxy/config.go

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ type Config struct {
2525
CacheMinTTL uint32 `toml:"cache_min_ttl"`
2626
CacheMaxTTL uint32 `toml:"cache_max_ttl"`
2727
QueryLog QueryLogConfig `toml:"query_log"`
28-
BlockName BlockNameConfig `toml:"block_name"`
28+
BlockName BlockNameConfig `toml:"blacklist"`
2929
ForwardFile string `toml:"forwarding_rules"`
3030
ServersConfig map[string]ServerConfig `toml:"servers"`
3131
SourcesConfig map[string]SourceConfig `toml:"sources"`
@@ -67,7 +67,9 @@ type QueryLogConfig struct {
6767
}
6868

6969
type BlockNameConfig struct {
70-
File string
70+
File string `toml:"blacklist_file"`
71+
LogFile string `toml:"log_file"`
72+
Format string `toml:"log_format"`
7173
}
7274

7375
func ConfigLoad(proxy *Proxy, svcFlag *string, config_file string) error {
@@ -97,6 +99,7 @@ func ConfigLoad(proxy *Proxy, svcFlag *string, config_file string) error {
9799
proxy.cacheNegTTL = config.CacheNegTTL
98100
proxy.cacheMinTTL = config.CacheMinTTL
99101
proxy.cacheMaxTTL = config.CacheMaxTTL
102+
100103
if len(config.QueryLog.Format) == 0 {
101104
config.QueryLog.Format = "tsv"
102105
} else {
@@ -107,7 +110,19 @@ func ConfigLoad(proxy *Proxy, svcFlag *string, config_file string) error {
107110
}
108111
proxy.queryLogFile = config.QueryLog.File
109112
proxy.queryLogFormat = config.QueryLog.Format
113+
114+
if len(config.BlockName.Format) == 0 {
115+
config.BlockName.Format = "tsv"
116+
} else {
117+
config.BlockName.Format = strings.ToLower(config.BlockName.Format)
118+
}
119+
if config.BlockName.Format != "tsv" && config.BlockName.Format != "ltsv" {
120+
return errors.New("Unsupported block log format")
121+
}
110122
proxy.blockNameFile = config.BlockName.File
123+
proxy.blockNameFormat = config.BlockName.Format
124+
proxy.blockNameLogFile = config.BlockName.LogFile
125+
111126
proxy.forwardFile = config.ForwardFile
112127
if len(config.ServerNames) == 0 {
113128
for serverName := range config.ServersConfig {

dnscrypt-proxy/dnscrypt-proxy.toml

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -127,11 +127,21 @@ format = "tsv"
127127
## ads*.example.*
128128
## ads*.example[0-9]*.com
129129

130-
[block_name]
130+
[blacklist]
131131

132132
## Full path to the file of blocking rules
133133

134-
# file = "blacklist.txt"
134+
# blacklist_file = "blacklist.txt"
135+
136+
137+
## Optional path to a file logging blocked queries
138+
139+
# log_file = "blocked.log"
140+
141+
142+
## Optional log format: tsv or ltsv (default: tsv)
143+
144+
# log_format = "tsv"
135145

136146

137147

dnscrypt-proxy/main.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ type Proxy struct {
3535
queryLogFile string
3636
queryLogFormat string
3737
blockNameFile string
38+
blockNameLogFile string
39+
blockNameFormat string
3840
forwardFile string
3941
pluginsGlobals PluginsGlobals
4042
}

dnscrypt-proxy/plugin_block_name.go

Lines changed: 75 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,15 @@
11
package main
22

33
import (
4+
"errors"
5+
"fmt"
46
"io/ioutil"
7+
"net"
8+
"os"
59
"path/filepath"
610
"strings"
11+
"sync"
12+
"time"
713
"unicode"
814

915
"github.com/hashicorp/go-immutable-radix"
@@ -22,10 +28,13 @@ const (
2228
)
2329

2430
type PluginBlockName struct {
31+
sync.Mutex
2532
blockedPrefixes *iradix.Tree
2633
blockedSuffixes *iradix.Tree
2734
blockedSubstrings []string
2835
blockedPatterns []string
36+
outFd *os.File
37+
format string
2938
}
3039

3140
func (plugin *PluginBlockName) Name() string {
@@ -100,6 +109,17 @@ func (plugin *PluginBlockName) Init(proxy *Proxy) error {
100109
dlog.Fatal("Unexpected block type")
101110
}
102111
}
112+
if len(proxy.blockNameLogFile) == 0 {
113+
return nil
114+
}
115+
plugin.Lock()
116+
defer plugin.Unlock()
117+
outFd, err := os.OpenFile(proxy.blockNameLogFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
118+
if err != nil {
119+
return err
120+
}
121+
plugin.outFd = outFd
122+
plugin.format = proxy.blockNameFormat
103123
return nil
104124
}
105125

@@ -116,30 +136,66 @@ func (plugin *PluginBlockName) Eval(pluginsState *PluginsState, msg *dns.Msg) er
116136
if len(questions) != 1 {
117137
return nil
118138
}
119-
question := strings.ToLower(StripTrailingDot(questions[0].Name))
120-
revQuestion := StringReverse(question)
121-
match, _, found := plugin.blockedSuffixes.Root().LongestPrefix([]byte(revQuestion))
122-
if found {
123-
if len(match) == len(question) || question[len(match)] == '.' {
124-
pluginsState.action = PluginsActionReject
125-
return nil
139+
qName := strings.ToLower(StripTrailingDot(questions[0].Name))
140+
revQname := StringReverse(qName)
141+
reject, reason := false, ""
142+
if !reject {
143+
match, _, found := plugin.blockedSuffixes.Root().LongestPrefix([]byte(revQname))
144+
if found {
145+
if len(match) == len(qName) || qName[len(match)] == '.' {
146+
reject, reason = true, "*"+string(match)
147+
}
126148
}
127149
}
128-
_, _, found = plugin.blockedPrefixes.Root().LongestPrefix([]byte(question))
129-
if found {
130-
pluginsState.action = PluginsActionReject
131-
return nil
150+
if !reject {
151+
match, _, found := plugin.blockedPrefixes.Root().LongestPrefix([]byte(qName))
152+
if found {
153+
reject, reason = true, string(match)+"*"
154+
}
132155
}
133-
for _, substring := range plugin.blockedSubstrings {
134-
if strings.Contains(substring, question) {
135-
pluginsState.action = PluginsActionReject
136-
return nil
156+
if !reject {
157+
for _, substring := range plugin.blockedSubstrings {
158+
if strings.Contains(substring, qName) {
159+
reject, reason = true, "*"+substring+"*"
160+
break
161+
}
162+
}
163+
}
164+
if !reject {
165+
for _, pattern := range plugin.blockedPatterns {
166+
if found, _ := filepath.Match(pattern, qName); found {
167+
reject, reason = true, pattern
168+
break
169+
}
137170
}
138171
}
139-
for _, pattern := range plugin.blockedPatterns {
140-
if found, _ := filepath.Match(pattern, question); found {
141-
pluginsState.action = PluginsActionReject
142-
return nil
172+
if reject {
173+
pluginsState.action = PluginsActionReject
174+
if plugin.outFd != nil {
175+
var clientIPStr string
176+
if pluginsState.clientProto == "udp" {
177+
clientIPStr = (*pluginsState.clientAddr).(*net.UDPAddr).IP.String()
178+
} else {
179+
clientIPStr = (*pluginsState.clientAddr).(*net.TCPAddr).IP.String()
180+
}
181+
var line string
182+
if plugin.format == "tsv" {
183+
now := time.Now()
184+
year, month, day := now.Date()
185+
hour, minute, second := now.Clock()
186+
tsStr := fmt.Sprintf("[%d-%02d-%02d %02d:%02d:%02d]", year, int(month), day, hour, minute, second)
187+
line = fmt.Sprintf("%s\t%s\t%s\t%s\n", tsStr, clientIPStr, StringQuote(qName), StringQuote(reason))
188+
} else if plugin.format == "ltsv" {
189+
line = fmt.Sprintf("time:%d\thost:%s\tqname:%s\tmessage:%s\n", time.Now().Unix(), clientIPStr, StringQuote(qName), StringQuote(reason))
190+
} else {
191+
dlog.Fatalf("Unexpected log format: [%s]", plugin.format)
192+
}
193+
plugin.Lock()
194+
if plugin.outFd == nil {
195+
return errors.New("Log file not initialized")
196+
}
197+
plugin.outFd.WriteString(line)
198+
defer plugin.Unlock()
143199
}
144200
}
145201
return nil

dnscrypt-proxy/plugin_query_log.go

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import (
55
"fmt"
66
"net"
77
"os"
8-
"strings"
98
"sync"
109
"time"
1110

@@ -60,10 +59,7 @@ func (plugin *PluginQueryLog) Eval(pluginsState *PluginsState, msg *dns.Msg) err
6059
} else {
6160
clientIPStr = (*pluginsState.clientAddr).(*net.TCPAddr).IP.String()
6261
}
63-
qName := question.Name
64-
if len(qName) > 1 && strings.HasSuffix(qName, ".") {
65-
qName = qName[0 : len(qName)-1]
66-
}
62+
qName := StripTrailingDot(question.Name)
6763
qType, ok := dns.TypeToString[question.Qtype]
6864
if !ok {
6965
qType = string(qType)
@@ -74,10 +70,10 @@ func (plugin *PluginQueryLog) Eval(pluginsState *PluginsState, msg *dns.Msg) err
7470
year, month, day := now.Date()
7571
hour, minute, second := now.Clock()
7672
tsStr := fmt.Sprintf("[%d-%02d-%02d %02d:%02d:%02d]", year, int(month), day, hour, minute, second)
77-
line = fmt.Sprintf("%s\t%s\t%s\t%s\n", tsStr, clientIPStr, qName, qType)
73+
line = fmt.Sprintf("%s\t%s\t%s\t%s\n", tsStr, clientIPStr, StringQuote(qName), qType)
7874
} else if plugin.format == "ltsv" {
7975
line = fmt.Sprintf("time:%d\thost:%s\tmessage:%s\ttype:%s\n",
80-
time.Now().Unix(), clientIPStr, qName, qType)
76+
time.Now().Unix(), clientIPStr, StringQuote(qName), qType)
8177
} else {
8278
dlog.Fatalf("Unexpected log format: [%s]", plugin.format)
8379
}

0 commit comments

Comments
 (0)