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
| import requests
import json
import sqlite3
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent
DB_FILE = BASE_DIR / "dns_categories.db"
STATE_FILE = BASE_DIR / "state.json"
CATEGORY_DIR = BASE_DIR / "categories"
UNKNOWN_FILE = BASE_DIR / "unknown_domains.json"
####
#### Create DB if needed ####
####
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS categorized_queries (
timestamp TEXT NOT NULL,
client TEXT NOT NULL,
domain TEXT NOT NULL,
category TEXT NOT NULL,
status TEXT NOT NULL,
reason TEXT NOT NULL,
UNIQUE(timestamp, client, domain, category, status, reason)
)
""")
cursor.execute("""
CREATE INDEX IF NOT EXISTS idx_client
ON categorized_queries(client)
""")
cursor.execute("""
CREATE INDEX IF NOT EXISTS idx_category
ON categorized_queries(category)
""")
cursor.execute("""
CREATE INDEX IF NOT EXISTS idx_domain
ON categorized_queries(domain)
""")
cursor.execute("""
CREATE INDEX IF NOT EXISTS idx_status
ON categorized_queries(status)
""")
cursor.execute("""
CREATE INDEX IF NOT EXISTS idx_reason
ON categorized_queries(reason)
""")
conn.commit()
#### End ####
####
#### - Hash sets - ####
####
CATEGORY_FILES = {
file.stem: file.name
for file in CATEGORY_DIR.glob("*.txt")
}
try:
with open(STATE_FILE) as f:
state = json.load(f)
except FileNotFoundError:
state = {"last_processed_time": ""}
try:
with open(UNKNOWN_FILE) as f:
unknown_domains = json.load(f)
except FileNotFoundError:
unknown_domains = {}
category_sets = {}
####
#### Read HaGeZi files ####
####
for category, filename in CATEGORY_FILES.items():
domains = set()
with open(CATEGORY_DIR / filename) as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
domains.add(line.lower())
category_sets[category] = domains
#### END ####
####
#### - Find matches - ####
####
def domain_match(domain, lookup_set):
domain = domain.lower()
while True:
if domain in lookup_set:
return True
if "." not in domain:
return False
domain = domain.split(".", 1)[1]
#### END ####
def normalize_domain(domain: str, depth: int = 3) -> str:
domain = domain.lower().rstrip(".")
parts = domain.split(".")
if len(parts) <= depth:
return domain
return ".".join(parts[-depth:])
####
#### - Adguard Home API - ####
####
response = requests.get(
"http://192.168.4.24/control/querylog?limit=5000",
params={"limit": 5000},
auth=("admin", "PASSWORD"),
timeout=30
)
queries = response.json()
#### END ####
domain_cache = {}
newest_seen = state['last_processed_time']
for line in queries["data"]:
timestamp = line['time']
if timestamp <= state['last_processed_time']:
break
raw_domain = line['question']['name'].lower().rstrip('.')
storage_domain = normalize_domain(raw_domain, depth=3)
client = line['client']
status = line['status']
reason = line['reason']
if raw_domain not in domain_cache:
categories = []
for category, lookup_set in category_sets.items():
if domain_match(raw_domain, lookup_set):
categories.append(category)
domain_cache[raw_domain] = categories
if domain_cache[raw_domain]:
for category in domain_cache[raw_domain]:
if category == "ignored":
continue
cursor.execute("""
INSERT OR IGNORE INTO categorized_queries
(timestamp, client, domain, category, status, reason)
VALUES (?, ?, ?, ?, ?, ?)
""", (
timestamp,
client,
storage_domain,
category,
status,
reason
))
else:
if storage_domain not in unknown_domains:
unknown_domains[storage_domain] = {
"hits": 0,
"clients": {},
"first_seen": timestamp,
"last_seen": timestamp,
}
unknown_domains[storage_domain]["hits"] += 1
unknown_domains[storage_domain]["last_seen"] = timestamp
unknown_domains[storage_domain]["clients"][client] = (
unknown_domains[storage_domain]["clients"].get(client, 0) + 1
)
if timestamp > newest_seen:
newest_seen = timestamp
conn.commit()
conn.close()
state["last_processed_time"] = newest_seen
sorted_unknown = dict(
sorted(
unknown_domains.items(),
key=lambda item: item[1]["hits"],
reverse=True
)
)
with open(UNKNOWN_FILE, "w") as f:
json.dump(sorted_unknown, f, indent=4)
with open(STATE_FILE, "w") as file:
json.dump(state, file) |