-
Notifications
You must be signed in to change notification settings - Fork 5
/
ncprop279.go
399 lines (314 loc) · 9.04 KB
/
ncprop279.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
package main
import (
"bufio"
"fmt"
"net"
"os"
"strconv"
"strings"
"github.com/btcsuite/btcd/rpcclient"
"github.com/hlandau/buildinfo"
"github.com/hlandau/xlog"
"github.com/miekg/dns"
"gopkg.in/hlandau/easyconfig.v1"
"gopkg.in/hlandau/madns.v2"
"github.com/namecoin/ncdns/backend"
"github.com/namecoin/ncdns/namecoin"
)
var prop279Reader *bufio.Reader
type Server struct {
cfg Config
engine madns.Engine
namecoinConn *namecoin.Client
}
type Config struct {
NamecoinRPCUsername string `default:"" usage:"Namecoin RPC username"`
NamecoinRPCPassword string `default:"" usage:"Namecoin RPC password"`
NamecoinRPCAddress string `default:"127.0.0.1:8336" usage:"Namecoin RPC server address"`
NamecoinRPCCookiePath string `default:"" usage:"Namecoin RPC cookie path (used if password is unspecified)"`
NamecoinRPCTimeout int `default:"1500" usage:"Timeout (in milliseconds) for Namecoin RPC requests"`
CacheMaxEntries int `default:"100" usage:"Maximum name cache entries"`
OnlyOnion bool `default:"false" usage:"Only return onion services?"`
}
var ncdnsVersion string
func New(cfg *Config) (*Server, error) {
ncdnsVersion = buildinfo.VersionSummary("github.com/namecoin/ncdns", "ncdns")
// Connect to local namecoin core RPC server using HTTP POST mode.
connCfg := &rpcclient.ConnConfig{
Host: cfg.NamecoinRPCAddress,
User: cfg.NamecoinRPCUsername,
Pass: cfg.NamecoinRPCPassword,
CookiePath: cfg.NamecoinRPCCookiePath,
HTTPPostMode: true, // Namecoin core only supports HTTP POST mode
DisableTLS: true, // Namecoin core does not provide TLS by default
}
// Notice the notification parameter is nil since notifications are
// not supported in HTTP POST mode.
client, err := namecoin.New(connCfg, nil)
if err != nil {
return nil, err
}
s := &Server{
cfg: *cfg,
namecoinConn: client,
}
b, err := backend.New(&backend.Config{
NamecoinConn: s.namecoinConn,
NamecoinTimeout: cfg.NamecoinRPCTimeout,
CacheMaxEntries: cfg.CacheMaxEntries,
SelfIP: "127.127.127.127",
Hostmaster: "",
CanonicalNameservers: []string{},
VanityIPs: []net.IP{},
})
if err != nil {
return nil, err
}
ecfg := &madns.EngineConfig{
Backend: b,
VersionString: ncdnsVersion,
}
s.engine, err = madns.NewEngine(ecfg)
if err != nil {
return nil, err
}
return s, nil
}
func createReqMsg(qname string, qtype uint16, streamID string) *dns.Msg {
m := &dns.Msg{
MsgHdr: dns.MsgHdr{
Authoritative: true,
AuthenticatedData: false,
CheckingDisabled: false,
RecursionDesired: true,
Opcode: dns.OpcodeQuery,
},
Question: make([]dns.Question, 1),
}
m.Question[0] = dns.Question{Name: dns.Fqdn(qname), Qtype: qtype, Qclass: dns.ClassINET}
// Pass EDNS0 stream isolation to madns, which will pass it onto ncdns
o := &dns.OPT{
Hdr: dns.RR_Header{
Name: ".",
Rrtype: dns.TypeOPT,
},
}
e := new(dns.EDNS0_LOCAL)
e.Code = madns.EDNS0STREAMISOLATION
e.Data = []byte(streamID)
o.Option = append(o.Option, e)
m.Extra = append(m.Extra, o)
m.Id = dns.Id()
return m
}
type prop279Status int
const (
StatusSuccess prop279Status = 0
StatusGenericFail prop279Status = 1
StatusNotInZone prop279Status = 2
StatusNxDomain prop279Status = 3
StatusTimeout prop279Status = 4
)
type prop279ResponseWriter struct {
queryID int
parseOnion bool
result *prop279Status
}
func (rw *prop279ResponseWriter) LocalAddr() net.Addr {
addr, _ := net.ResolveIPAddr("ip", "127.0.0.1")
return addr
}
func (rw *prop279ResponseWriter) RemoteAddr() net.Addr {
addr, _ := net.ResolveIPAddr("ip", "127.0.0.1")
return addr
}
func (rw *prop279ResponseWriter) WriteMsg(res *dns.Msg) error {
switch res.MsgHdr.Rcode {
case dns.RcodeNameError:
*rw.result = StatusNxDomain
case dns.RcodeRefused:
*rw.result = StatusNotInZone
case dns.RcodeSuccess:
if rw.parseOnion {
for _, answer := range res.Answer {
answerTXT, ok := answer.(*dns.TXT)
if ok {
onion := answerTXT.Txt[0]
_, isDomainName := dns.IsDomainName(onion)
if !isDomainName {
continue
}
if !strings.HasSuffix(onion, ".onion") {
continue
}
*rw.result = StatusSuccess
fmt.Printf("RESOLVED %d %d %s\n", rw.queryID, *rw.result, onion)
return nil
}
}
} else {
for _, answer := range res.Answer {
answerA, ok := answer.(*dns.A)
if ok {
*rw.result = StatusSuccess
fmt.Printf("RESOLVED %d %d %s\n", rw.queryID, *rw.result, answerA.A.String())
return nil
}
}
for _, answer := range res.Answer {
answerAAAA, ok := answer.(*dns.AAAA)
if ok {
*rw.result = StatusSuccess
fmt.Printf("RESOLVED %d %d %s\n", rw.queryID, *rw.result, answerAAAA.AAAA.String())
return nil
}
}
for _, answer := range res.Answer {
answerCNAME, ok := answer.(*dns.CNAME)
if !ok {
continue
}
target := answerCNAME.Target
if !dns.IsFqdn(target) {
continue
}
target = strings.TrimSuffix(target, ".")
*rw.result = StatusSuccess
fmt.Printf("RESOLVED %d %d %s\n", rw.queryID, *rw.result, target)
return nil
}
}
*rw.result = StatusNxDomain
default:
*rw.result = StatusGenericFail
fmt.Printf("RESOLVED %d %d %s\n", rw.queryID, *rw.result, "\"Server failure\"")
}
return nil
}
func (rw *prop279ResponseWriter) Write(rawMsg []byte) (int, error) {
return 0, fmt.Errorf("Unimplemented")
}
func (rw *prop279ResponseWriter) Close() error {
return nil
}
func (rw *prop279ResponseWriter) TsigStatus() error {
return nil
}
func (rw *prop279ResponseWriter) TsigTimersOnly(t bool) {
}
func (rw *prop279ResponseWriter) Hijack() {
}
func (s *Server) doResolve(queryID int, qname string, qtype uint16, parseOnion bool, streamID string) prop279Status {
var result prop279Status
reqMsg := createReqMsg(qname, qtype, streamID)
responseWriter := &prop279ResponseWriter{queryID: queryID, parseOnion: parseOnion, result: &result}
s.engine.ServeDNS(responseWriter, reqMsg)
return result
}
func runResolveCommand(args []string, cfg *Config, s *Server) {
if len(args) < 2 {
fmt.Fprintf(os.Stderr, "Not enough arguments to RESOLVE command.\n")
return
}
queryIDStr := args[0]
queryID, err := strconv.Atoi(queryIDStr)
if err != nil {
fmt.Fprintf(os.Stderr, "Query ID '%s' was not an integer.\n", queryIDStr)
return
}
name := args[1]
originalName := name
onlyOnion := cfg.OnlyOnion
if strings.HasSuffix(name, ".onion") {
name = strings.TrimSuffix(name, ".onion")
onlyOnion = true
}
streamID := ""
if len(args) >= 3 {
streamID = args[2]
}
if streamID == "" {
fmt.Fprintf(os.Stderr, "WARNING: Missing stream isolation ID from Prop279 client; stream isolation won't work properly. Maybe your Prop279 client is outdated?\n")
}
result := StatusNxDomain
if result == StatusNxDomain {
result = s.doResolve(queryID, "_tor."+name, dns.TypeTXT, true, streamID)
}
if !onlyOnion {
if result == StatusNxDomain {
result = s.doResolve(queryID, name, dns.TypeA, false, streamID)
}
if result == StatusNxDomain {
result = s.doResolve(queryID, name, dns.TypeAAAA, false, streamID)
}
if result == StatusNxDomain {
result = s.doResolve(queryID, name, dns.TypeCNAME, false, streamID)
}
}
if result == StatusNxDomain {
fmt.Printf("RESOLVED %d %d \"%s is not registered\"\n", queryID, result, originalName)
}
if result == StatusNotInZone {
fmt.Printf("RESOLVED %d %d \"%s is not a Namecoin domain\"\n", queryID, result, originalName)
}
}
func runCancelCommand(args []string, cfg *Config, s *Server) {
if len(args) < 1 {
fmt.Fprintf(os.Stderr, "Not enough arguments to CANCEL command.\n")
return
}
queryIDStr := args[0]
queryID, err := strconv.Atoi(queryIDStr)
if err != nil {
fmt.Fprintf(os.Stderr, "Query ID '%s' was not an integer.\n", queryIDStr)
return
}
fmt.Printf("CANCELED %d\n", queryID)
}
func runCommand(words []string, cfg *Config, s *Server) {
if len(words) < 1 {
return
}
if words[0] == "RESOLVE" {
runResolveCommand(words[1:], cfg, s)
} else if words[0] == "CANCEL" {
runCancelCommand(words[1:], cfg, s)
}
}
func main() {
cfg := &Config{}
config := easyconfig.Configurator{
ProgramName: "ncprop279",
}
config.ParseFatal(cfg)
// Avoid verbose logging that might leak private data
// (Copied from dexlogconfig)
sev := xlog.SevWarn
xlog.Root.SetSeverity(sev)
err := xlog.VisitSites(func(s xlog.Site) error {
s.SetSeverity(sev)
return nil
})
if err != nil {
fmt.Fprintf(os.Stderr, "Couldn't set xlog severity: %s\n", err)
os.Exit(3)
}
s, err := New(cfg)
if err != nil {
fmt.Fprintf(os.Stderr, "Couldn't create server: %s\n", err)
os.Exit(3)
}
prop279Reader = bufio.NewReader(os.Stdin)
fmt.Println("INIT 1 0")
for {
// Prop279 Sec. 2.9.1 (2016 Oct 04) specifies LF as the line
// ending, even on OS's where CRLF is typical.
line, err := prop279Reader.ReadString('\n')
if err != nil {
fmt.Fprintf(os.Stderr, "Couldn't read stdin: %s\n", err)
os.Exit(3)
}
words := strings.Fields(line)
runCommand(words, cfg, s)
}
}