or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

dns-client.mddns-core.mddns-records.mddns-resolvers.mddns-server.mddns-utils.mdindex.md

dns-utils.mddocs/

0

# DNS Utilities

1

2

Additional utilities for DNS development including intercepting proxy functionality, helper functions for TCP/UDP communication, and specialized request handlers for advanced use cases.

3

4

## Capabilities

5

6

### Intercepting Resolver

7

8

Advanced resolver that can intercept specific queries locally while proxying others to upstream servers.

9

10

```python { .api }

11

class InterceptResolver(BaseResolver):

12

"""

13

Intercepting resolver that matches queries against patterns and handles

14

them locally or forwards to upstream server.

15

16

Args:

17

address (str): Upstream DNS server address

18

port (int, optional): Upstream DNS server port (default: 53)

19

ttl (int, optional): TTL for intercepted responses (default: 60)

20

intercept (list, optional): List of domains/patterns to intercept

21

skip (list, optional): List of domains/patterns to skip interception

22

nxdomain (list, optional): List of domains to return NXDOMAIN

23

forward (list, optional): List of domains to always forward

24

all_qtypes (bool, optional): Intercept all query types (default: False)

25

timeout (int, optional): Upstream timeout in seconds (default: 5)

26

"""

27

def __init__(self, address, port, ttl, intercept, skip, nxdomain, forward, all_qtypes, timeout=0): ...

28

29

def resolve(self, request, handler):

30

"""

31

Resolve query with interception logic.

32

33

Args:

34

request (DNSRecord): DNS query to resolve

35

handler (DNSHandler): Request handler instance

36

37

Returns:

38

DNSRecord: DNS response (intercepted or proxied)

39

"""

40

```

41

42

### Passthrough Handler

43

44

Specialized DNS handler that passes requests directly to upstream server without decoding/encoding for maximum performance.

45

46

```python { .api }

47

class PassthroughDNSHandler(DNSHandler):

48

"""

49

DNS handler that forwards requests directly to upstream server

50

without parsing DNS packets for improved performance.

51

"""

52

def get_reply(self, data):

53

"""

54

Forward raw DNS packet to upstream server.

55

56

Args:

57

data (bytes): Raw DNS query packet

58

59

Returns:

60

bytes: Raw DNS response packet from upstream

61

"""

62

```

63

64

### Network Utilities

65

66

Helper functions for TCP and UDP DNS communication.

67

68

```python { .api }

69

def send_tcp(data, host, port):

70

"""

71

Send DNS query over TCP and return response.

72

73

Args:

74

data (bytes): DNS query packet

75

host (str): Target server address

76

port (int): Target server port

77

78

Returns:

79

bytes: DNS response packet

80

"""

81

82

def send_udp(data, host, port):

83

"""

84

Send DNS query over UDP and return response.

85

86

Args:

87

data (bytes): DNS query packet

88

host (str): Target server address

89

port (int): Target server port

90

91

Returns:

92

bytes: DNS response packet

93

"""

94

```

95

96

### DiG Parser

97

98

Parser for DiG output format for compatibility with standard DNS tools.

99

100

```python { .api }

101

class DigParser:

102

"""

103

Parser for DiG (Domain Information Groper) output format.

104

Enables parsing of DiG command output for DNS record extraction.

105

"""

106

def __init__(self): ...

107

108

def parse(self, dig_output):

109

"""

110

Parse DiG output and extract DNS records.

111

112

Args:

113

dig_output (str): DiG command output

114

115

Returns:

116

DNSRecord: Parsed DNS record from DiG output

117

"""

118

119

def parse_response(self, response_text):

120

"""

121

Parse DiG response section.

122

123

Args:

124

response_text (str): DiG response section text

125

126

Returns:

127

list[RR]: List of parsed resource records

128

"""

129

```

130

131

### Exception Classes

132

133

Exception classes for error handling in DNS utilities.

134

135

```python { .api }

136

class DNSError(Exception):

137

"""Base exception class for DNS-related errors."""

138

139

class DNSLabelError(Exception):

140

"""Exception for DNS label processing errors."""

141

142

class BufferError(Exception):

143

"""Exception for buffer operation errors."""

144

145

class BimapError(Exception):

146

"""Exception for bidirectional mapping errors."""

147

```

148

149

## Usage Examples

150

151

### Setting up Intercepting Resolver

152

153

```python

154

from dnslib import *

155

from dnslib.server import DNSServer

156

from dnslib.intercept import InterceptResolver

157

158

# Create intercepting resolver

159

resolver = InterceptResolver(

160

address="8.8.8.8",

161

port=53,

162

ttl=300,

163

intercept=["example.com", "*.local"],

164

nxdomain=["blocked.com"],

165

forward=["important.com"],

166

all_qtypes=True,

167

timeout=5

168

)

169

170

# Start DNS server with intercepting resolver

171

server = DNSServer(resolver, port=5353, address="127.0.0.1")

172

server.start_thread()

173

174

print("Intercepting DNS server running on 127.0.0.1:5353")

175

```

176

177

### Using Network Utilities

178

179

```python

180

from dnslib import *

181

from dnslib.proxy import send_tcp, send_udp

182

183

# Create DNS query

184

query = DNSRecord.question("example.com", "A")

185

query_data = query.pack()

186

187

# Send via UDP

188

try:

189

response_data = send_udp(query_data, "8.8.8.8", 53)

190

response = DNSRecord.parse(response_data)

191

print(f"UDP Response: {response.a}")

192

except Exception as e:

193

print(f"UDP query failed: {e}")

194

195

# Send via TCP for large responses

196

try:

197

response_data = send_tcp(query_data, "8.8.8.8", 53)

198

response = DNSRecord.parse(response_data)

199

print(f"TCP Response: {response.a}")

200

except Exception as e:

201

print(f"TCP query failed: {e}")

202

```

203

204

### Using Passthrough Handler

205

206

```python

207

from dnslib import *

208

from dnslib.server import DNSServer

209

from dnslib.proxy import ProxyResolver, PassthroughDNSHandler

210

211

# Create proxy resolver

212

resolver = ProxyResolver("8.8.8.8", 53, timeout=5)

213

214

# Use passthrough handler for maximum performance

215

server = DNSServer(

216

resolver=resolver,

217

port=5353,

218

address="127.0.0.1",

219

handler=PassthroughDNSHandler

220

)

221

222

server.start_thread()

223

print("High-performance proxy server running on 127.0.0.1:5353")

224

```

225

226

### Working with DiG Parser

227

228

```python

229

from dnslib.digparser import DigParser

230

import subprocess

231

232

# Run DiG command and capture output

233

dig_cmd = ["dig", "@8.8.8.8", "example.com", "A"]

234

result = subprocess.run(dig_cmd, capture_output=True, text=True)

235

236

# Parse DiG output

237

parser = DigParser()

238

try:

239

dns_record = parser.parse(result.stdout)

240

print(f"Parsed from DiG: {dns_record}")

241

242

# Extract answer records

243

for rr in dns_record.rr:

244

print(f"Answer: {rr}")

245

except Exception as e:

246

print(f"Failed to parse DiG output: {e}")

247

```

248

249

### Error Handling

250

251

```python

252

from dnslib import *

253

from dnslib.label import DNSLabelError

254

255

try:

256

# Try to create DNS record with invalid data

257

query = DNSRecord.question("invalid..domain", "A")

258

response_data = query.send("8.8.8.8", 53)

259

response = DNSRecord.parse(response_data)

260

261

except DNSError as e:

262

print(f"DNS error: {e}")

263

except DNSLabelError as e:

264

print(f"DNS label error: {e}")

265

except BufferError as e:

266

print(f"Buffer error: {e}")

267

except Exception as e:

268

print(f"Unexpected error: {e}")

269

```