Che237 commited on
Commit
e49ba7b
·
verified ·
1 Parent(s): 8377638

Upload dns_tunneling dataset

Browse files
Files changed (32) hide show
  1. dns_tunneling/dns_tunneling_processed.csv +0 -0
  2. dns_tunneling/metadata.json +24 -0
  3. dns_tunneling/passivedns-master/.gitignore +28 -0
  4. dns_tunneling/passivedns-master/Makefile.am +3 -0
  5. dns_tunneling/passivedns-master/README +90 -0
  6. dns_tunneling/passivedns-master/bootstrap +19 -0
  7. dns_tunneling/passivedns-master/configure.ac +293 -0
  8. dns_tunneling/passivedns-master/doc/AUTHORS +27 -0
  9. dns_tunneling/passivedns-master/doc/ChangeLog +52 -0
  10. dns_tunneling/passivedns-master/doc/How-it-works.txt +37 -0
  11. dns_tunneling/passivedns-master/doc/INSTALL +74 -0
  12. dns_tunneling/passivedns-master/doc/ISSUES +9 -0
  13. dns_tunneling/passivedns-master/doc/LICENSE +339 -0
  14. dns_tunneling/passivedns-master/doc/README +38 -0
  15. dns_tunneling/passivedns-master/doc/README.upgrading +18 -0
  16. dns_tunneling/passivedns-master/doc/ROADMAP +62 -0
  17. dns_tunneling/passivedns-master/doc/TODO +12 -0
  18. dns_tunneling/passivedns-master/etc/default/passivedns-debian +44 -0
  19. dns_tunneling/passivedns-master/etc/init.d/passivedns-debian +66 -0
  20. dns_tunneling/passivedns-master/etc/init.d/passivedns-redhat +129 -0
  21. dns_tunneling/passivedns-master/etc/logrotate.d/passivedns +13 -0
  22. dns_tunneling/passivedns-master/etc/sysconfig/passivedns-redhat +66 -0
  23. dns_tunneling/passivedns-master/pdns.patch +57 -0
  24. dns_tunneling/passivedns-master/src/Makefile.am +17 -0
  25. dns_tunneling/passivedns-master/src/dns.c +1886 -0
  26. dns_tunneling/passivedns-master/src/dns.h +187 -0
  27. dns_tunneling/passivedns-master/src/passivedns.c +1603 -0
  28. dns_tunneling/passivedns-master/src/passivedns.h +580 -0
  29. dns_tunneling/passivedns-master/tools/README.skip_white_black-list.txt +37 -0
  30. dns_tunneling/passivedns-master/tools/pdns2db.pl +531 -0
  31. dns_tunneling/passivedns-master/tools/search-pdns.pl +201 -0
  32. dns_tunneling/passivedns-master/www/index.php +177 -0
dns_tunneling/dns_tunneling_processed.csv ADDED
The diff for this file is too large to render. See raw diff
 
dns_tunneling/metadata.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset_id": "dns_tunneling",
3
+ <<<<<<< Updated upstream
4
+ "processed_at": "2025-08-24T04:17:07.693713",
5
+ "samples": 10000,
6
+ =======
7
+ "processed_at": "2025-08-24T03:09:42.416761",
8
+ "samples": 150000,
9
+ >>>>>>> Stashed changes
10
+ "features": [
11
+ "query_name",
12
+ "query_type",
13
+ "response_code",
14
+ "query_length",
15
+ <<<<<<< Updated upstream
16
+ "subdomain_count",
17
+ "is_tunneling"
18
+ =======
19
+ "subdomain_count"
20
+ >>>>>>> Stashed changes
21
+ ],
22
+ "type": "dns",
23
+ "file_path": "..\\datasets\\dns_tunneling\\dns_tunneling_processed.csv"
24
+ }
dns_tunneling/passivedns-master/.gitignore ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Binaries
2
+ src/passivedns
3
+
4
+ # Object files
5
+ *.o
6
+
7
+ # Autotools files
8
+ *.swp
9
+ aclocal.m4
10
+ autom4te.cache/
11
+ compile
12
+ config.guess
13
+ config.log
14
+ config.sub
15
+ config.status
16
+ configure
17
+ depcomp
18
+ install-sh
19
+ missing
20
+ Makefile
21
+ Makefile.in
22
+ src/config.h
23
+ src/config.h.in
24
+ src/.deps/
25
+ src/Makefile
26
+ src/Makefile.in
27
+ src/stamp-h1
28
+
dns_tunneling/passivedns-master/Makefile.am ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ AUTOMAKE_OPTIONS = foreign
2
+ SUBDIRS = src
3
+
dns_tunneling/passivedns-master/README ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # ______ ____ __ __ _____
3
+ # | __ | @ | \ | \ | || ___| (TM)
4
+ # | _____|.------. .-----. .-----. _ -. .-.------. | |\ || \| ||___ |
5
+ # | | | __ ||__ --'|__ --'| |\ Y /| _--__|_| |/ || || \_| |
6
+ # |__| |____|_||______||______||_| \_/ |_______/|____/ |__|\__||_____|
7
+ #
8
+ #
9
+
10
+ A tool to collect DNS records passively to aid Incident handling, Network
11
+ Security Monitoring (NSM) and general digital forensics.
12
+
13
+ PassiveDNS sniffs traffic from an interface or reads a pcap-file and outputs
14
+ the DNS-server answers to a log file. PassiveDNS can cache/aggregate duplicate
15
+ DNS answers in-memory, limiting the amount of data in the logfile without
16
+ losing the essense in the DNS answer.
17
+
18
+ Example output from version 1.0.0->Current in the log file (/var/log/passivedns.log):
19
+
20
+ #timestamp||dns-client ||dns-server||RR class||Query||Query Type||Answer||TTL||Count
21
+ 1322849924.408856||10.1.1.1||8.8.8.8||IN||upload.youtube.com.||A||74.125.43.117||46587||5
22
+ 1322849924.408857||10.1.1.1||8.8.8.8||IN||upload.youtube.com.||A||74.125.43.116||420509||5
23
+ 1322849924.408858||10.1.1.1||8.8.8.8||IN||www.adobe.com.||CNAME||www.wip4.adobe.com.||43200||8
24
+ 1322849924.408859||10.1.1.1||8.8.8.8||IN||www.adobe.com.||A||193.104.215.61||43200||8
25
+ 1322849924.408860||10.1.1.1||8.8.8.8||IN||i1.ytimg.com.||CNAME||ytimg.l.google.com.||43200||3
26
+ 1322849924.408861||10.1.1.1||8.8.8.8||IN||clients1.google.com.||A||173.194.32.3||43200||2
27
+
28
+ PassiveDNS works on IPv4 and IPv6 traffic and parse DNS traffic over TCP and UDP.
29
+
30
+ ** How can PassiveDNS be used: **
31
+
32
+ Typical usages:
33
+
34
+ 1) Search for domain or IP history when working on an incident.
35
+ Example:
36
+ Company has malware talking to bad.twittertoday.com.
37
+ At current time, the domain is resolving to say 202.29.94.200
38
+ You search your Flowdata and find the clients talking to that IP and
39
+ remidate. You look at the Flowdata, and you discover that the date
40
+ and time the clients first talked to that IP, and concludes that as
41
+ the time of infection...
42
+
43
+ But using PassiveDNS data, quering the domain, you get following history:
44
+
45
+ FirstSeen | LastSeen | TYPE | TTL | Query | Answer
46
+ ----------------------------------------------------------------------------
47
+ 2011-12-01 | 2011-12-11 | A | 60 | bad.twittertoday.com | 71.51.115.11
48
+ 2011-12-11 | 2011-12-18 | A | 60 | bad.twittertoday.com | 127.0.0.1
49
+ 2011-12-18 | 2012-01-14 | A | 60 | bad.twittertoday.com | 202.29.94.200
50
+
51
+ Going back and searching for 71.51.115.11 in your Flowdata, you find
52
+ traffic back to the FirstSeen data, and you also see more clients
53
+ initially infected (so you did not manage to remidate/check out all your
54
+ clients in the first run by just looking at IP 202.29.94.200). Doing
55
+ forensics on the the clients you missed in the first run, reveals that
56
+ they have downloaded a different malware and deleted the initial one,
57
+ that beeing the reason you did not see flows from them to 202.29.94.200.
58
+ The new malware gives you new domains and IPs to go look for...
59
+
60
+ 2) Say you have an indication of malicious C&C traffic going to an IP on
61
+ port 80. The domain used by the alleged malware is supposed to be
62
+ cc.twittertoday.com. Searching you Flowdata, reveals lots of clients
63
+ talking to that IP, and you might think that the whole company is p0wned.
64
+ A quick search in your PassiveDNS DB shows you that the IP in question is
65
+ also hosting 300 + websites and you might even spot a website hosted on
66
+ that IP that you are familiar with and that you know lots of people in the
67
+ company would legit visit daily.
68
+ Searching your PassiveDNS DB gives you no hits for the domain in question,
69
+ hopefully meaning that you dont have that malware talking to that domain
70
+ in your network.
71
+
72
+ 3) You know that *.twittertoday.com are often used in malware and the
73
+ subdomains change randomly. Many have rules for such domains in their
74
+ IDS/IPS, sucking up unnecessary juice from the systems. Having a script
75
+ pre-loaded with a list of regexp of domains and subdomains to watch for
76
+ and giving you an alert when they hit will give you much better detection
77
+ on threat based on domains.
78
+
79
+ You can also do a whois for all new top domains seen, correlate the whois
80
+ info with a list of know bad info, such as the name of the person or
81
+ company that has registered the domain, telephone/fax numbers, address
82
+ and so on, ending up with a score that might be high enough for triggering
83
+ an alert to you :)
84
+
85
+
86
+ Questions, suggestions, sugar or flame is always welcome :)
87
+
88
+ I hope PassiveDNS gives you a new tool to fight malware and its herders...
89
+
90
+ (c)2011-2020 - Edward Bjarte Fjellskål
dns_tunneling/passivedns-master/bootstrap ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/sh
2
+ #
3
+ # desc: simple script to run all auto commands
4
+ #
5
+ ####
6
+
7
+ # defines needed for OpenBSD
8
+ AUTOMAKE_VERSION=1.15;export AUTOMAKE_VERSION
9
+ AUTOCONF_VERSION=2.69;export AUTOCONF_VERSION
10
+
11
+ if [ ! -d config ]; then
12
+ mkdir config
13
+ fi
14
+
15
+ aclocal
16
+ automake --gnu --add-missing
17
+ autoconf
18
+ autoheader
19
+
dns_tunneling/passivedns-master/configure.ac ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- Autoconf -*-
2
+ # Process this file with autoconf to produce a configure script.
3
+
4
+ AC_INIT([passivedns], [1.2.1])
5
+ AM_INIT_AUTOMAKE
6
+ AC_USE_SYSTEM_EXTENSIONS
7
+ AC_CONFIG_SRCDIR([src/passivedns.h])
8
+ AC_CONFIG_HEADERS([src/config.h])
9
+
10
+ # Checks for programs.
11
+ AC_PROG_CC
12
+
13
+ AC_CANONICAL_HOST
14
+
15
+ dnl Checks for OS type.
16
+ case "$host" in
17
+ *-freebsd*)
18
+ AC_DEFINE([BSD_DERIVED],1,BSD_DERIVED)
19
+ AC_DEFINE([FREEBSD],1,FREEBSD)
20
+ LDFLAGS="${LDFLAGS}"
21
+ ;;
22
+ *-netbsd*)
23
+ AC_DEFINE([BSD_DERIVED],1,BSD_DERIVED)
24
+ AC_DEFINE([NETBSD],1,NETBSD)
25
+ ;;
26
+ *-openbsd*)
27
+ AC_DEFINE([BSD_DERIVED],1,BSD_DERIVED)
28
+ AC_DEFINE([OPENBSD],1,OPENBSD)
29
+ CFLAGS="${CFLAGS} -Wbounded"
30
+ LDFLAGS="${LDFLAGS}"
31
+ ;;
32
+ *-apple*)
33
+ AC_DEFINE([BSD_DERIVED],1,BSD_DERIVED)
34
+ AC_DEFINE([MACOS],1,MACOS)
35
+ LDFLAGS="${LDFLAGS} -L/sw/lib"
36
+ AC_SUBST(more_incl)
37
+ more_incl=-I/sw/include
38
+ ;;
39
+ *-linux*)
40
+ AC_DEFINE([SYSV_DERIVED],1,SYSV_DERIVED)
41
+ AC_DEFINE([LINUX],1,LINUX)
42
+ LDFLAGS="${LDFLAGS}"
43
+ ;;
44
+ *-solaris*)
45
+ AC_DEFINE([SYSV_DERIVED],1,SYSV_DERIVED)
46
+ AC_DEFINE([SOLARIS],1,SOLARIS)
47
+ LDFLAGS="${LDFLAGS}"
48
+ ;;
49
+ *-aix*)
50
+ AC_DEFINE([SYSV_DERIVED],1,SYSV_DERIVED)
51
+ AC_DEFINE([AIX],1,AIX)
52
+ ;;
53
+ *-hpux*)
54
+ AC_DEFINE([SYSV_DERIVED],1,SYSV_DERIVED)
55
+ AC_DEFINE([HPUX],1,HPUX)
56
+ ;;
57
+ esac
58
+
59
+ # Enable debug output.
60
+ AC_ARG_ENABLE(debug,
61
+ AS_HELP_STRING([--enable-debug], [Enable debug output]))
62
+
63
+ AS_IF([test "x$enable_debug" = "xyes"], [
64
+ CPPFLAGS="${CPPFLAGS} -Wall -g -DDEBUG"
65
+ ])
66
+
67
+ # Enable gcc profile info.
68
+ AC_ARG_ENABLE(gccprofile,
69
+ AS_HELP_STRING([--enable-gccprofile], [Enable gcc profile info (set -pg flag)]))
70
+
71
+ AS_IF([test "x$enable_gccprofile" = "xyes"], [
72
+ CPPFLAGS="${CPPFLAGS} -g -pg"
73
+ ])
74
+
75
+ # Checks for libpcap.
76
+ AC_ARG_WITH(libpcap_includes,
77
+ [ --with-libpcap-includes=DIR libpcap include directory],
78
+ [with_libpcap_includes="$withval"],[with_libpcap_includes="no"])
79
+
80
+ AC_ARG_WITH(libpcap_libraries,
81
+ [ --with-libpcap-libraries=DIR libpcap library directory],
82
+ [with_libpcap_libraries="$withval"],[with_libpcap_libraries="no"])
83
+
84
+ if test "$with_libpcap_includes" != "no"; then
85
+ CPPFLAGS="${CPPFLAGS} -I${with_libpcap_includes}"
86
+ fi
87
+
88
+ if test "$with_libpcap_libraries" != "no"; then
89
+ LDFLAGS="${LDFLAGS} -L${with_libpcap_libraries}"
90
+ fi
91
+
92
+ LDFLAGS="${LDFLAGS} -lpcap"
93
+
94
+ # Check for libpcap headers
95
+ AC_CHECK_HEADER(pcap.h,,LIBPCAP_H="no")
96
+
97
+ if test "$LIBPCAP_H" = "no"; then
98
+ echo -e "\n ERROR! libpcap headers not found\n"
99
+ exit 1
100
+ fi
101
+
102
+ # Check for libpcap library
103
+ AC_CHECK_LIB(pcap,pcap_loop,,LIBPCAP_L="no")
104
+
105
+ if test "$LIBPCAP_L" = "no"; then
106
+ echo -e "\n ERROR! libpcap library not found\n"
107
+ exit 1
108
+ fi
109
+
110
+ # Checks for OpenSSL (newer versions of ldns require OpenSSL).
111
+ AC_ARG_ENABLE(openssl,
112
+ AS_HELP_STRING([--disable-openssl],
113
+ [Requires ldns library compiled without OpenSSL]),
114
+ [enable_openssl=no], [enable_openssl=yes])
115
+
116
+ AC_ARG_WITH(openssl_includes,
117
+ [ --with-openssl-includes=DIR OpenSSL include directory],
118
+ [with_openssl_includes="$withval"],[with_openssl_includes="no"])
119
+
120
+ AC_ARG_WITH(openssl_libraries,
121
+ [ --with-openssl-libraries=DIR OpenSSL library directory],
122
+ [with_openssl_libraries="$withval"],[with_openssl_libraries="no"])
123
+
124
+ AS_IF([test "x$enable_openssl" = "xyes"], [
125
+ if test "$with_openssl_includes" != "no"; then
126
+ CPPFLAGS="${CPPFLAGS} -I${with_openssl_includes}"
127
+ fi
128
+
129
+ if test "$with_openssl_libraries" != "no"; then
130
+ LDFLAGS="${LDFLAGS} -L${with_openssl_libraries}"
131
+ fi
132
+
133
+ # Check for OpenSSL headers
134
+ AC_CHECK_HEADER(openssl/ssl.h,,LIBOPENSSL_H="no")
135
+
136
+ if test "$LIBOPENSSL_H" = "no"; then
137
+ echo -e "\n ERROR! OpenSSL headers not found\n"
138
+ exit 1
139
+ fi
140
+ ])
141
+
142
+ # Checks for ldns.
143
+ AC_ARG_WITH(ldns_includes,
144
+ [ --with-ldns-includes=DIR ldns include directory],
145
+ [with_ldns_includes="$withval"],[with_ldns_includes="no"])
146
+
147
+ AC_ARG_WITH(ldns_libraries,
148
+ [ --with-ldns-libraries=DIR ldns library directory],
149
+ [with_ldns_libraries="$withval"],[with_ldns_libraries="no"])
150
+
151
+ if test "$with_ldns_includes" != "no"; then
152
+ CPPFLAGS="${CPPFLAGS} -I${with_ldns_includes}"
153
+ fi
154
+
155
+ if test "$with_ldns_libraries" != "no"; then
156
+ LDFLAGS="${LDFLAGS} -L${with_ldns_libraries}"
157
+ fi
158
+
159
+ LDFLAGS="${LDFLAGS} -lldns"
160
+
161
+ # Check or ldns headers
162
+ AC_CHECK_HEADER(ldns/ldns.h,,LIBLDNS_H="no")
163
+
164
+ if test "$LIBLDNS_H" = "no"; then
165
+ echo -e "\n ERROR! ldns headers not found\n"
166
+ exit 1
167
+ fi
168
+
169
+ # Check for ldns library
170
+ AC_CHECK_LIB(ldns,ldns_pkt_get_rcode,,LIBLDNS_L="no")
171
+
172
+ if test "$LIBLDNS_L" = "no"; then
173
+ echo -e "\n ERROR! ldns library not found\n"
174
+ exit 1
175
+ fi
176
+
177
+ # Checks for PF_RING.
178
+ AC_ARG_ENABLE(pfring,
179
+ AS_HELP_STRING([--enable-pfring], [Enable PF_RING support]))
180
+
181
+ AC_ARG_WITH(pfring_includes,
182
+ [ --with-pfring-includes=DIR PF_RING include directory],
183
+ [with_pfring_includes="$withval"],[with_pfring_includes="no"])
184
+
185
+ AC_ARG_WITH(pfring_libraries,
186
+ [ --with-pfring-libraries=DIR PF_RING library directory],
187
+ [with_pfring_libraries="$withval"],[with_pfring_libraries="no"])
188
+
189
+ AS_IF([test "x$enable_pfring" = "xyes"], [
190
+ AC_DEFINE([HAVE_PFRING],[1],[PF_RING support enabled])
191
+
192
+ if test "$with_pfring_includes" != "no"; then
193
+ CPPFLAGS="${CPPFLAGS} -I${with_pfring_includes}"
194
+ fi
195
+
196
+ if test "$with_pfring_libraries" != "no"; then
197
+ LDFLAGS="${LDFLAGS} -L${with_pfring_libraries}"
198
+ fi
199
+
200
+ LDFLAGS="${LDFLAGS} -lpfring -lnuma -lrt"
201
+
202
+ # Checks for libnuma
203
+ AC_CHECK_HEADER(numa.h,,LIBNUMA="no")
204
+ AC_CHECK_LIB(numa,numa_available,,LIBNUMA="no")
205
+
206
+ if test "$LIBNUMA" = "no"; then
207
+ echo -e "\n ERROR! libnuma not found (PF_RING requirement)\n"
208
+ exit 1
209
+ fi
210
+
211
+ # Check for PF_RING headers
212
+ AC_CHECK_HEADER(pfring.h,,LIBPFRING_H="no")
213
+
214
+ if test "$LIBPFRING_H" = "no"; then
215
+ echo -e "\n ERROR! PF_RING headers not found\n"
216
+ exit 1
217
+ fi
218
+
219
+ # Check for PF_RING library
220
+ AC_CHECK_LIB(pfring,pfring_stats,,LIBPFRING_L="no")
221
+
222
+ if test "$LIBPFRING_L" = "no"; then
223
+ echo -e "\n ERROR! PF_RING library not found\n"
224
+ exit 1
225
+ fi
226
+
227
+ # Check for PF_RING BPF support
228
+ AC_CHECK_LIB(pfring,pfring_set_bpf_filter,,LIBPFRING_BPF="no")
229
+
230
+ if test "$LIBPFRING_BPF" != "no"; then
231
+ AC_DEFINE([HAVE_PFRING_BPF],[1],[PF_RING BPF support])
232
+ fi
233
+ ])
234
+
235
+ # Checks for libjansson.
236
+ AC_ARG_ENABLE(json,
237
+ AS_HELP_STRING([--enable-json], [Enable JSON support]))
238
+
239
+ AC_ARG_WITH(jansson_includes,
240
+ [ --with-jansson-includes=DIR libjansson include directory],
241
+ [with_jansson_includes="$withval"],[with_jansson_includes="no"])
242
+
243
+ AC_ARG_WITH(jansson_libraries,
244
+ [ --with-jansson-libraries=DIR libjansson library directory],
245
+ [with_jansson_libraries="$withval"],[with_jansson_libraries="no"])
246
+
247
+ AS_IF([test "x$enable_json" = "xyes"], [
248
+ AC_DEFINE([HAVE_JSON],[1],[JSON support enabled])
249
+
250
+ if test "$with_jansson_includes" != "no"; then
251
+ CPPFLAGS="${CPPFLAGS} -I${with_jansson_includes}"
252
+ fi
253
+
254
+ if test "$with_jansson_libraries" != "no"; then
255
+ LDFLAGS="${LDFLAGS} -L${with_jansson_libraries}"
256
+ fi
257
+
258
+ LDFLAGS="${LDFLAGS} -ljansson"
259
+
260
+ # Check for jansson headers
261
+ AC_CHECK_HEADER(jansson.h,,LIBJANSSON_H="no")
262
+
263
+ if test "$LIBJANSSON_H" = "no"; then
264
+ echo -e "\n ERROR! Jansson headers not found\n"
265
+ exit 1
266
+ fi
267
+
268
+ # Check for jansson library
269
+ AC_CHECK_LIB(jansson,json_delete,,LIBJANSSON_L="no")
270
+
271
+ if test "$LIBJANSSON_L" = "no"; then
272
+ echo -e "\n ERROR! Jansson library not found\n"
273
+ exit 1
274
+ fi
275
+ ])
276
+
277
+ # Checks for header files.
278
+ AC_CHECK_HEADERS([arpa/inet.h fcntl.h netinet/in.h stdlib.h string.h syslog.h unistd.h])
279
+
280
+ # Checks for typedefs, structures, and compiler characteristics.
281
+ AC_TYPE_PID_T
282
+ AC_TYPE_UINT16_T
283
+ AC_TYPE_UINT32_T
284
+ AC_TYPE_UINT64_T
285
+ AC_TYPE_UINT8_T
286
+
287
+ # Checks for library functions.
288
+ AC_FUNC_FORK
289
+ AC_FUNC_STRNLEN
290
+ AC_CHECK_FUNCS([alarm dup2 endgrent endpwent ftruncate getcwd memset strdup strerror strtol strtoul])
291
+
292
+ AC_OUTPUT(Makefile src/Makefile)
293
+
dns_tunneling/passivedns-master/doc/AUTHORS ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Primary authors:
2
+ Edward Fjellskål <edwardfjellskaal@gmail.com>
3
+
4
+ Co-Maintainer:
5
+ Mats Klepsland <mats.klepsland@gmail.com>
6
+
7
+ Code from earlier projects:
8
+ Kacper Wysocki <kacper.wysocki@redpill-linpro.com>
9
+
10
+ Some initially code ideas/borrowed from (Changes has been made):
11
+ DNS parsing with lib ldns:
12
+ www.nlnetlabs.nl (https://www.nlnetlabs.nl/projects/ldns/)
13
+ Mark Ellzey (https://github.com/ellzey/dns-archiver)
14
+
15
+ Contributions (In no particular order!):
16
+ Eric Kollman
17
+ Henrik Ramberg
18
+ Joe Moore
19
+ kevin branch
20
+ David André
21
+ PingTrip
22
+ Sony Security Development Team
23
+ gavinspearhead
24
+
25
+ If you've been left off the list, it's not intentional. Please let us know!
26
+
27
+ Thanks!
dns_tunneling/passivedns-master/doc/ChangeLog ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Changes with PassiveDNS 1.2.0
2
+
3
+ - Added enhancements to better handle high volume traffic
4
+ - Added support for LOC records
5
+ - Added support for DNSSEC records
6
+ - Added support for HINFO records
7
+ - Added support for SPF records
8
+ - Added support for SSHFP records
9
+ - Support for DLT_RAW pcap files
10
+ - Added support for LINKTYPE_LINUX_SLL
11
+ - Added autotools support
12
+ - Better OSX support
13
+ - Added pf_ring support
14
+ - Added support for SIGHUP to reopen log files
15
+ - Added support for JSON output
16
+ - Added syslog output option
17
+ - Added support for expire_all_dns_records on SIGUSR2
18
+
19
+ Changes with PassiveDNS 1.1.3
20
+
21
+ - Added a fix for correct CNAME handling
22
+ - Makefile improvements
23
+
24
+ Changes with PassiveDNS 1.1.2
25
+
26
+ - Zero padding to microseconds
27
+ - Added a simple webui in php for searching the pdns mysql db.
28
+
29
+ Changes with PassiveDNS 1.1.1
30
+
31
+ - Added stats output to stdout with SIGUSR1 signal
32
+ - Added support for more Server Return Codes
33
+
34
+ Changes with PassiveDNS 1.0.0
35
+
36
+ - Added microseconds to unix timestamps in log output
37
+ - Added "count" field in log output.
38
+ - Added more stat fields when exiting
39
+
40
+ Changes with PassiveDNS 0.5.1
41
+
42
+ - Fixed an issue of lost dns_records (memleak and finally a cpu spinn)
43
+ - Fixed segfault when unable to read pcap
44
+ - Fixed segfault when packet payload was only one byte
45
+
46
+ Changes with PassiveDNS 0.5.0
47
+
48
+ - Cleaned up unused code
49
+
50
+ Changes with PassiveDNS 0.3.4
51
+
52
+ - Added NXDOMAIN support
dns_tunneling/passivedns-master/doc/How-it-works.txt ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #### PassiveDNS internals
2
+
3
+ ## Packet capture
4
+ * Uses libpcap
5
+ * Decodes packets as they come in.
6
+ * Handles vlan (looks inside vlan packets, but does not
7
+ currently print out the vlan tag seen)
8
+ * Handles IPv4 and IPv6 packets
9
+ * We look at DNS on UDP and TCP
10
+
11
+ ## Connection Tracking
12
+ * Same connection tracking as in cxtracker
13
+ ** When used with a propper BPF (filter),
14
+ it only tracks traffic on port 53.
15
+ * Connection tracking is used to make sure
16
+ that a client asked for a domain, so that
17
+ there will not be any tracking of domains,
18
+ if a client did not request one. A bit spoof
19
+ protection. In the connection data, the
20
+ DNS Transaction ID is also stored, to verify
21
+ that the client sent a request, and that the
22
+ server answered the right TID request :)
23
+
24
+ ## Domain caching
25
+ * When a DNS question and answer is recieved, it
26
+ is stored in an internal linked list. If its new,
27
+ we will print the info to the logfile, and we will
28
+ not print it again befor it has gone 12 hours or
29
+ the record has changed. This is to provent flooding
30
+ of data to the log file, and serving you much duplicat
31
+ info.
32
+ * If we have not seen any activity agains a domain in 24h,
33
+ it will be deleted from the internal cache.
34
+ * If we have not seen any activity of any related entries
35
+ within 24h, it will be deleted...
36
+
37
+
dns_tunneling/passivedns-master/doc/INSTALL ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # General:
2
+ # PassiveDNS was initially developed on a Ubuntu 10.04 platform, and later on Ubuntu 12.04, so all
3
+ # main testing was done on Ubuntu. I have compiled passivedns static and dynamic
4
+ # and tried it out on different linux OSes with great luck.
5
+ # I try to keep the git tags "stable" and the master branch might be under development.
6
+ # If you have issues with the current master, please read doc/ISSUES
7
+
8
+ FreeBSD Install
9
+ $ pkg_add -r gmake git ldns
10
+ $ rehash
11
+ $ mkdir /usr/local/src/; cd /usr/local/src
12
+ $ git clone git://github.com/gamelinux/passivedns.git
13
+ $ cd passivedns/
14
+ $ autoreconf --install
15
+ $ ./configure
16
+ $ gmake
17
+
18
+ OS X (using Homebrew for dependencies)
19
+ $ brew install automake autoconf ldns jansson
20
+ $ git clone git://github.com/gamelinux/passivedns.git
21
+ $ cd passivedns/
22
+ $ autoreconf --install
23
+ $ ./configure
24
+ $ make
25
+
26
+ Macbook Pro 2023 running Sonoma 14.4.1 (using Homebrew for dependencies)
27
+ $ brew install automake autoconf ldns jansson openssl
28
+ $ export LDFLAGS="-L$(brew --prefix openssl)/lib $LDFLAGS"
29
+ $ export CPPFLAGS="-I$(brew --prefix openssl)/include $CPPFLAGS"
30
+ $ export LDFLAGS="-L$(brew --prefix ldns)/lib $LDFLAGS"
31
+ $ export CPPFLAGS="-I$(brew --prefix ldns)/include $CPPFLAGS"
32
+ $ git clone git://github.com/gamelinux/passivedns.git
33
+ $ cd passivedns/
34
+ $ autoreconf --install
35
+ $ ./configure
36
+ $ make
37
+
38
+ Ubuntu
39
+ $ sudo apt-get install git-core binutils-dev libldns1 libldns-dev libpcap-dev
40
+ # libdate-simple-perl is also needed for pdns2db.pl
41
+ $ git clone git://github.com/gamelinux/passivedns.git
42
+ $ cd passivedns/
43
+ $ autoreconf --install
44
+ $ ./configure
45
+ $ make
46
+
47
+ Debian 12 (Bookworm)
48
+ $ sudo apt install git build-essential libldns-dev libpcap-dev automake autoconf
49
+ # libdate-simple-perl might be needed for pdns2db.pl if you're using it
50
+ $ sudo apt install libdate-simple-perl
51
+ $ git clone git://github.com/gamelinux/passivedns.git
52
+ $ cd passivedns/
53
+ $ autoreconf --install
54
+ $ ./configure
55
+ $ make
56
+
57
+ RedHat (RHEL 6u2 x86_64)
58
+ $ yum groupinstall "Development tools"
59
+ # EPEL : http://fedora.uib.no/epel/6/x86_64/
60
+ $ rpm -Uvh http://download.fedoraproject.org/pub/epel/6/x86_64/ldns-devel-1.6.11-2.el6.x86_64.rpm
61
+ $ rpm -Uvh http://download.fedoraproject.org/pub/epel/6/x86_64/ldns-1.6.11-2.el6.x86_64.rpm
62
+ # perl-DateTime is also needed for pdns2db.pl
63
+ $ wget http://www.tcpdump.org/release/libpcap-1.2.1.tar.gz
64
+ $ tar zxf libpcap-1.2.1.tar.gz; cd libpcap-1.2.1; ./configure; make && make install
65
+ $ git clone git://github.com/gamelinux/passivedns.git
66
+ $ cd passivedns/
67
+ $ autoreconf --install
68
+ $ ./configure
69
+ $ make
70
+
71
+
72
+
73
+
74
+
dns_tunneling/passivedns-master/doc/ISSUES ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # You will find all known issues here:
2
+ # - https://github.com/gamelinux/passivedns/issues
3
+ #
4
+ # If you encounter an issue, please add them using the above link.
5
+
6
+ By trying out passivedns, and giving feedback (Good or Bad), you can help make passivedns better.
7
+
8
+ # If you want to discuss with a broader audience:
9
+ # https://groups.google.com/forum/?fromgroups#!forum/passivedns
dns_tunneling/passivedns-master/doc/LICENSE ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 2, June 1991
3
+
4
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6
+ Everyone is permitted to copy and distribute verbatim copies
7
+ of this license document, but changing it is not allowed.
8
+
9
+ Preamble
10
+
11
+ The licenses for most software are designed to take away your
12
+ freedom to share and change it. By contrast, the GNU General Public
13
+ License is intended to guarantee your freedom to share and change free
14
+ software--to make sure the software is free for all its users. This
15
+ General Public License applies to most of the Free Software
16
+ Foundation's software and to any other program whose authors commit to
17
+ using it. (Some other Free Software Foundation software is covered by
18
+ the GNU Lesser General Public License instead.) You can apply it to
19
+ your programs, too.
20
+
21
+ When we speak of free software, we are referring to freedom, not
22
+ price. Our General Public Licenses are designed to make sure that you
23
+ have the freedom to distribute copies of free software (and charge for
24
+ this service if you wish), that you receive source code or can get it
25
+ if you want it, that you can change the software or use pieces of it
26
+ in new free programs; and that you know you can do these things.
27
+
28
+ To protect your rights, we need to make restrictions that forbid
29
+ anyone to deny you these rights or to ask you to surrender the rights.
30
+ These restrictions translate to certain responsibilities for you if you
31
+ distribute copies of the software, or if you modify it.
32
+
33
+ For example, if you distribute copies of such a program, whether
34
+ gratis or for a fee, you must give the recipients all the rights that
35
+ you have. You must make sure that they, too, receive or can get the
36
+ source code. And you must show them these terms so they know their
37
+ rights.
38
+
39
+ We protect your rights with two steps: (1) copyright the software, and
40
+ (2) offer you this license which gives you legal permission to copy,
41
+ distribute and/or modify the software.
42
+
43
+ Also, for each author's protection and ours, we want to make certain
44
+ that everyone understands that there is no warranty for this free
45
+ software. If the software is modified by someone else and passed on, we
46
+ want its recipients to know that what they have is not the original, so
47
+ that any problems introduced by others will not reflect on the original
48
+ authors' reputations.
49
+
50
+ Finally, any free program is threatened constantly by software
51
+ patents. We wish to avoid the danger that redistributors of a free
52
+ program will individually obtain patent licenses, in effect making the
53
+ program proprietary. To prevent this, we have made it clear that any
54
+ patent must be licensed for everyone's free use or not licensed at all.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ GNU GENERAL PUBLIC LICENSE
60
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61
+
62
+ 0. This License applies to any program or other work which contains
63
+ a notice placed by the copyright holder saying it may be distributed
64
+ under the terms of this General Public License. The "Program", below,
65
+ refers to any such program or work, and a "work based on the Program"
66
+ means either the Program or any derivative work under copyright law:
67
+ that is to say, a work containing the Program or a portion of it,
68
+ either verbatim or with modifications and/or translated into another
69
+ language. (Hereinafter, translation is included without limitation in
70
+ the term "modification".) Each licensee is addressed as "you".
71
+
72
+ Activities other than copying, distribution and modification are not
73
+ covered by this License; they are outside its scope. The act of
74
+ running the Program is not restricted, and the output from the Program
75
+ is covered only if its contents constitute a work based on the
76
+ Program (independent of having been made by running the Program).
77
+ Whether that is true depends on what the Program does.
78
+
79
+ 1. You may copy and distribute verbatim copies of the Program's
80
+ source code as you receive it, in any medium, provided that you
81
+ conspicuously and appropriately publish on each copy an appropriate
82
+ copyright notice and disclaimer of warranty; keep intact all the
83
+ notices that refer to this License and to the absence of any warranty;
84
+ and give any other recipients of the Program a copy of this License
85
+ along with the Program.
86
+
87
+ You may charge a fee for the physical act of transferring a copy, and
88
+ you may at your option offer warranty protection in exchange for a fee.
89
+
90
+ 2. You may modify your copy or copies of the Program or any portion
91
+ of it, thus forming a work based on the Program, and copy and
92
+ distribute such modifications or work under the terms of Section 1
93
+ above, provided that you also meet all of these conditions:
94
+
95
+ a) You must cause the modified files to carry prominent notices
96
+ stating that you changed the files and the date of any change.
97
+
98
+ b) You must cause any work that you distribute or publish, that in
99
+ whole or in part contains or is derived from the Program or any
100
+ part thereof, to be licensed as a whole at no charge to all third
101
+ parties under the terms of this License.
102
+
103
+ c) If the modified program normally reads commands interactively
104
+ when run, you must cause it, when started running for such
105
+ interactive use in the most ordinary way, to print or display an
106
+ announcement including an appropriate copyright notice and a
107
+ notice that there is no warranty (or else, saying that you provide
108
+ a warranty) and that users may redistribute the program under
109
+ these conditions, and telling the user how to view a copy of this
110
+ License. (Exception: if the Program itself is interactive but
111
+ does not normally print such an announcement, your work based on
112
+ the Program is not required to print an announcement.)
113
+
114
+ These requirements apply to the modified work as a whole. If
115
+ identifiable sections of that work are not derived from the Program,
116
+ and can be reasonably considered independent and separate works in
117
+ themselves, then this License, and its terms, do not apply to those
118
+ sections when you distribute them as separate works. But when you
119
+ distribute the same sections as part of a whole which is a work based
120
+ on the Program, the distribution of the whole must be on the terms of
121
+ this License, whose permissions for other licensees extend to the
122
+ entire whole, and thus to each and every part regardless of who wrote it.
123
+
124
+ Thus, it is not the intent of this section to claim rights or contest
125
+ your rights to work written entirely by you; rather, the intent is to
126
+ exercise the right to control the distribution of derivative or
127
+ collective works based on the Program.
128
+
129
+ In addition, mere aggregation of another work not based on the Program
130
+ with the Program (or with a work based on the Program) on a volume of
131
+ a storage or distribution medium does not bring the other work under
132
+ the scope of this License.
133
+
134
+ 3. You may copy and distribute the Program (or a work based on it,
135
+ under Section 2) in object code or executable form under the terms of
136
+ Sections 1 and 2 above provided that you also do one of the following:
137
+
138
+ a) Accompany it with the complete corresponding machine-readable
139
+ source code, which must be distributed under the terms of Sections
140
+ 1 and 2 above on a medium customarily used for software interchange; or,
141
+
142
+ b) Accompany it with a written offer, valid for at least three
143
+ years, to give any third party, for a charge no more than your
144
+ cost of physically performing source distribution, a complete
145
+ machine-readable copy of the corresponding source code, to be
146
+ distributed under the terms of Sections 1 and 2 above on a medium
147
+ customarily used for software interchange; or,
148
+
149
+ c) Accompany it with the information you received as to the offer
150
+ to distribute corresponding source code. (This alternative is
151
+ allowed only for noncommercial distribution and only if you
152
+ received the program in object code or executable form with such
153
+ an offer, in accord with Subsection b above.)
154
+
155
+ The source code for a work means the preferred form of the work for
156
+ making modifications to it. For an executable work, complete source
157
+ code means all the source code for all modules it contains, plus any
158
+ associated interface definition files, plus the scripts used to
159
+ control compilation and installation of the executable. However, as a
160
+ special exception, the source code distributed need not include
161
+ anything that is normally distributed (in either source or binary
162
+ form) with the major components (compiler, kernel, and so on) of the
163
+ operating system on which the executable runs, unless that component
164
+ itself accompanies the executable.
165
+
166
+ If distribution of executable or object code is made by offering
167
+ access to copy from a designated place, then offering equivalent
168
+ access to copy the source code from the same place counts as
169
+ distribution of the source code, even though third parties are not
170
+ compelled to copy the source along with the object code.
171
+
172
+ 4. You may not copy, modify, sublicense, or distribute the Program
173
+ except as expressly provided under this License. Any attempt
174
+ otherwise to copy, modify, sublicense or distribute the Program is
175
+ void, and will automatically terminate your rights under this License.
176
+ However, parties who have received copies, or rights, from you under
177
+ this License will not have their licenses terminated so long as such
178
+ parties remain in full compliance.
179
+
180
+ 5. You are not required to accept this License, since you have not
181
+ signed it. However, nothing else grants you permission to modify or
182
+ distribute the Program or its derivative works. These actions are
183
+ prohibited by law if you do not accept this License. Therefore, by
184
+ modifying or distributing the Program (or any work based on the
185
+ Program), you indicate your acceptance of this License to do so, and
186
+ all its terms and conditions for copying, distributing or modifying
187
+ the Program or works based on it.
188
+
189
+ 6. Each time you redistribute the Program (or any work based on the
190
+ Program), the recipient automatically receives a license from the
191
+ original licensor to copy, distribute or modify the Program subject to
192
+ these terms and conditions. You may not impose any further
193
+ restrictions on the recipients' exercise of the rights granted herein.
194
+ You are not responsible for enforcing compliance by third parties to
195
+ this License.
196
+
197
+ 7. If, as a consequence of a court judgment or allegation of patent
198
+ infringement or for any other reason (not limited to patent issues),
199
+ conditions are imposed on you (whether by court order, agreement or
200
+ otherwise) that contradict the conditions of this License, they do not
201
+ excuse you from the conditions of this License. If you cannot
202
+ distribute so as to satisfy simultaneously your obligations under this
203
+ License and any other pertinent obligations, then as a consequence you
204
+ may not distribute the Program at all. For example, if a patent
205
+ license would not permit royalty-free redistribution of the Program by
206
+ all those who receive copies directly or indirectly through you, then
207
+ the only way you could satisfy both it and this License would be to
208
+ refrain entirely from distribution of the Program.
209
+
210
+ If any portion of this section is held invalid or unenforceable under
211
+ any particular circumstance, the balance of the section is intended to
212
+ apply and the section as a whole is intended to apply in other
213
+ circumstances.
214
+
215
+ It is not the purpose of this section to induce you to infringe any
216
+ patents or other property right claims or to contest validity of any
217
+ such claims; this section has the sole purpose of protecting the
218
+ integrity of the free software distribution system, which is
219
+ implemented by public license practices. Many people have made
220
+ generous contributions to the wide range of software distributed
221
+ through that system in reliance on consistent application of that
222
+ system; it is up to the author/donor to decide if he or she is willing
223
+ to distribute software through any other system and a licensee cannot
224
+ impose that choice.
225
+
226
+ This section is intended to make thoroughly clear what is believed to
227
+ be a consequence of the rest of this License.
228
+
229
+ 8. If the distribution and/or use of the Program is restricted in
230
+ certain countries either by patents or by copyrighted interfaces, the
231
+ original copyright holder who places the Program under this License
232
+ may add an explicit geographical distribution limitation excluding
233
+ those countries, so that distribution is permitted only in or among
234
+ countries not thus excluded. In such case, this License incorporates
235
+ the limitation as if written in the body of this License.
236
+
237
+ 9. The Free Software Foundation may publish revised and/or new versions
238
+ of the General Public License from time to time. Such new versions will
239
+ be similar in spirit to the present version, but may differ in detail to
240
+ address new problems or concerns.
241
+
242
+ Each version is given a distinguishing version number. If the Program
243
+ specifies a version number of this License which applies to it and "any
244
+ later version", you have the option of following the terms and conditions
245
+ either of that version or of any later version published by the Free
246
+ Software Foundation. If the Program does not specify a version number of
247
+ this License, you may choose any version ever published by the Free Software
248
+ Foundation.
249
+
250
+ 10. If you wish to incorporate parts of the Program into other free
251
+ programs whose distribution conditions are different, write to the author
252
+ to ask for permission. For software which is copyrighted by the Free
253
+ Software Foundation, write to the Free Software Foundation; we sometimes
254
+ make exceptions for this. Our decision will be guided by the two goals
255
+ of preserving the free status of all derivatives of our free software and
256
+ of promoting the sharing and reuse of software generally.
257
+
258
+ NO WARRANTY
259
+
260
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261
+ FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262
+ OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263
+ PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264
+ OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265
+ MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266
+ TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267
+ PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268
+ REPAIR OR CORRECTION.
269
+
270
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272
+ REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273
+ INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274
+ OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275
+ TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276
+ YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277
+ PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278
+ POSSIBILITY OF SUCH DAMAGES.
279
+
280
+ END OF TERMS AND CONDITIONS
281
+
282
+ How to Apply These Terms to Your New Programs
283
+
284
+ If you develop a new program, and you want it to be of the greatest
285
+ possible use to the public, the best way to achieve this is to make it
286
+ free software which everyone can redistribute and change under these terms.
287
+
288
+ To do so, attach the following notices to the program. It is safest
289
+ to attach them to the start of each source file to most effectively
290
+ convey the exclusion of warranty; and each file should have at least
291
+ the "copyright" line and a pointer to where the full notice is found.
292
+
293
+ <one line to give the program's name and a brief idea of what it does.>
294
+ Copyright (C) <year> <name of author>
295
+
296
+ This program is free software; you can redistribute it and/or modify
297
+ it under the terms of the GNU General Public License as published by
298
+ the Free Software Foundation; either version 2 of the License, or
299
+ (at your option) any later version.
300
+
301
+ This program is distributed in the hope that it will be useful,
302
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
303
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304
+ GNU General Public License for more details.
305
+
306
+ You should have received a copy of the GNU General Public License along
307
+ with this program; if not, write to the Free Software Foundation, Inc.,
308
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309
+
310
+ Also add information on how to contact you by electronic and paper mail.
311
+
312
+ If the program is interactive, make it output a short notice like this
313
+ when it starts in an interactive mode:
314
+
315
+ Gnomovision version 69, Copyright (C) year name of author
316
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317
+ This is free software, and you are welcome to redistribute it
318
+ under certain conditions; type `show c' for details.
319
+
320
+ The hypothetical commands `show w' and `show c' should show the appropriate
321
+ parts of the General Public License. Of course, the commands you use may
322
+ be called something other than `show w' and `show c'; they could even be
323
+ mouse-clicks or menu items--whatever suits your program.
324
+
325
+ You should also get your employer (if you work as a programmer) or your
326
+ school, if any, to sign a "copyright disclaimer" for the program, if
327
+ necessary. Here is a sample; alter the names:
328
+
329
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
331
+
332
+ <signature of Ty Coon>, 1 April 1989
333
+ Ty Coon, President of Vice
334
+
335
+ This General Public License does not permit incorporating your program into
336
+ proprietary programs. If your program is a subroutine library, you may
337
+ consider it more useful to permit linking proprietary applications with the
338
+ library. If this is what you want to do, use the GNU Lesser General
339
+ Public License instead of this License.
dns_tunneling/passivedns-master/doc/README ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+ # ______ ____ __ __ _____
3
+ # | __ | @ | \ | \ | || ___| (TM)
4
+ # | _____|.------. .-----. .-----. _ -. .-.------. | |\ || \| ||___ |
5
+ # | | | __ ||__ --'|__ --'| |\ Y /| _--__|_| |/ || || \_| |
6
+ # |__| |____|_||______||______||_| \_/ |_______/|____/ |__|\__||_____|
7
+ #
8
+ #
9
+
10
+ # Usage
11
+ ########
12
+
13
+ # passivedns
14
+ root@localhost: ./passivedns -i eth1 -l /var/log/passivedns.log
15
+
16
+ # pdns2db.pl
17
+ root@localhost: apt-get install libdatetime-perl
18
+ (Redhat/CentOS: yum install perl-DateTime)
19
+
20
+ First you need to add a user to the mysql db:
21
+
22
+ mysql> GRANT USAGE ON *.* TO 'pdns'@'localhost' IDENTIFIED BY 'pdns';
23
+ mysql> GRANT SELECT,CREATE,INSERT,UPDATE ON pdns.* TO 'pdns'@'localhost';
24
+ mysql> flush privileges;
25
+ mysql> CREATE DATABASE pdns;
26
+
27
+ Then you need to start up pdns2db.pl
28
+
29
+ root@localhost: perl pdns2db.pl --file /var/log/passivedns.log
30
+
31
+ # Old School archiving of passivedns.log
32
+ # While passivedns is running;
33
+ $ mkdir /var/log/passivedns-archive/
34
+ $ mv /var/log/passivedns.log /var/log/passivedns-archive/
35
+ $ gzip -S ".`date +%s`.gz" /var/log/passivedns-archive/passivedns.log
36
+ # Searching
37
+ $ zgrep "gamelinux.org" /var/log/passivedns-archive/*
38
+
dns_tunneling/passivedns-master/doc/README.upgrading ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Upgrade from PassiveDNS < 1.0 to 1.0:
2
+
3
+ - If you are using custom tools to process the passivedns.log files,
4
+ you need to be aware of the new output filed added (count). Also
5
+ be aware of the unix timestamp now has microseconds!
6
+
7
+ - If you are using pdns2db.pl you need to do the following:
8
+
9
+ 1) Stop current passivedns.
10
+ Make sure that pdns2db.pl has processed passivedns.log
11
+ Move the old passivedns.log away to archive.
12
+
13
+ 2) Then, in mysql:
14
+ mysql> ALTER TABLE pdns ADD COUNT BIGINT(20) UNSIGNED NOT NULL DEFAULT '1' AFTER TTL;
15
+
16
+ 3) Install (build) the lastest passivedns and pdns2db.pl
17
+ Start passivedns && pdns2db.pl
18
+
dns_tunneling/passivedns-master/doc/ROADMAP ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Version 2+
2
+ - Slackspace inspection:
3
+ * inside dns packet
4
+ * outside dns packet
5
+ - Entropy checkin on fqdn, TLD, LLD, SLD etc
6
+ - detect clients that has many NXDOMAIN responces
7
+ - Look at cxt when timing out that has no Client Transaction ID
8
+ but a Server Transaction ID.
9
+
10
+ # Version 2.0.0
11
+ == Production ready and stable ==
12
+ - Customizable output of fields
13
+
14
+ # Version 1.5.0
15
+ == Production ready and stable ==
16
+ - Reads passivedns.log file on startup
17
+ populating the cache with objects seen
18
+ less than cache-timeout.
19
+ - Support NXDOMAIN via cmdline switch.
20
+
21
+ # Version 1.0.0
22
+ == Production ready and stable ==
23
+ - Tested/protected for:
24
+ * hardening:
25
+ - spoofing
26
+ - poisoning
27
+ - other
28
+ * evation ?
29
+ * flooding ?
30
+ * BOF (fuzz the crap out of it)
31
+ - some stats when exiting
32
+ * max concurrent records cached
33
+ * max concurrent sessions (cxt)
34
+ * max session memory usage (cxt)
35
+ * DNS counts:
36
+ - how many was IPv6
37
+ - how many was IPv4
38
+ - how many was TCP
39
+ - how many was UDP
40
+
41
+ # Version 0.5.0
42
+ == Production ready and stable ==
43
+ - support specifying RR types via switch:
44
+ A, AAAA, PTR, CNAME, DNAME, NAPTR,
45
+ RP, SRV, TXT, SOA, MX and NS
46
+ - soft memory limiting for caching of DNS objects
47
+ - cmdline switch for specifying print-time
48
+ - cmdline switch for specifying cache-time
49
+ - cmdline for chroot
50
+ - cmdline for drop privs
51
+ - cmdline for specifying log file
52
+ - sniff traffic from an interface
53
+ - process pcap files
54
+ - cmdline for specifying BPF filter
55
+ - cmdline for specifying pidfile
56
+ - daemon mode
57
+ - output fields:
58
+ timestamp||dns-client||dns-server||RR class||Query||Query Type||Answer||TTL
59
+
60
+
61
+
62
+
dns_tunneling/passivedns-master/doc/TODO ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # PassiveDNS
3
+
4
+ * Add some stats
5
+ * Add abuility to read log file when starting up
6
+ - Import domains that has timestamp less then "$cachetimeout" ago
7
+ -- It will reduce the "noize" at startups.
8
+
9
+ * Evaluate pdns hardening methods
10
+
11
+ * Adding abuility for custom output formating
12
+
dns_tunneling/passivedns-master/etc/default/passivedns-debian ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # OPTIONS:
2
+ #
3
+ # -i <iface> Network device <iface> (default: eth0).
4
+ # -r <file> Read pcap <file>.
5
+ # -l <file> Name of the logfile (default: /var/log/passivedns.log).
6
+ # -L <file> Name of NXDOMAIN logfile (default: /var/log/passivedns.log).
7
+ # -b 'BPF' Berkley Packet Filter (default: 'port 53').
8
+ # -p <file> Name of pid file (default: /var/run/passivedns.pid).
9
+ # -S <mem> Soft memory limit in MB (default: 256).
10
+ # -C <sec> Seconds to cache DNS objects in memory (default 43200).
11
+ # -P <sec> Seconds between printing duplicate DNS info (default 86400).
12
+ # -X <flags> Manually set DNS RR Types to care about(Default -X 46CDNPRS).
13
+ # -u <uid> User ID to drop privileges to.
14
+ # -g <gid> Group ID to drop privileges to.
15
+ # -T <dir> Directory to chroot into.
16
+ # -D Run as daemon.
17
+ # -V Show version and exit.
18
+ # -h This help message.
19
+ #
20
+ # FLAGS:
21
+ #
22
+ # 4:A 6:AAAA C:CNAME D:DNAME N:NAPTR O:SOA
23
+ # P:PTR R:RP S:SRV T:TXT M:MX n:NS
24
+ # x:NXD
25
+ #
26
+ ## Default values
27
+ NAME=passivedns
28
+ PIDFILE=/var/run/passivedns.pid
29
+ DAEMON=/usr/bin/$NAME
30
+
31
+ ## Quick and dirty:
32
+ INTERFACE="-i eth0"
33
+ LOGFILE="-l /var/log/passivedns.log"
34
+ NXLOGFILE="-L /var/log/passivedns-nx.log"
35
+ LOGSYSLOG=""
36
+ NXSYSLOG=""
37
+ MAXMEM="-S 256"
38
+ PRINT="-P 86400"
39
+ RRTYPES="-X 46CDNOPRSTMnx"
40
+ #UID="-u 1"
41
+ #GID="-g 1"
42
+ #CHROOT="/usr/lib/passivedns/"
43
+ DEAMON="-D"
44
+ ARGS="$INTERFACE $LOGFILE $NXLOGFILE $LOGSYSLOG $NXSYSLOG $MAXMEM $PRINT $RRTYPES $DEAMON"
dns_tunneling/passivedns-master/etc/init.d/passivedns-debian ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ #
3
+ ### BEGIN INIT INFO
4
+ # Provides: passivedns
5
+ # Required-Start: $network
6
+ # Required-Stop: $network
7
+ # Default-Start: 2 3 4 5
8
+ # Default-Stop: 0 1 6
9
+ # Short-Description: Passive DNS collector
10
+ # Description: This is a network (security) tool designed to
11
+ # collect DNS information for troubleshooting or
12
+ # security related work
13
+ ### END INIT INFO
14
+
15
+ NAME=passivedns
16
+ PIDFILE=/var/run/passivedns.pid
17
+ DAEMON=/usr/bin/$NAME
18
+ ARGS="-i eth0 -D"
19
+
20
+ # Source default configs.
21
+ if [ -r /etc/default/passivedns ]; then
22
+ . /etc/default/passivedns
23
+ fi
24
+
25
+ # See how we were called.
26
+ case "$1" in
27
+ start)
28
+ echo -n "Starting $NAME ..."
29
+ $DAEMON $ARGS > /dev/null 2>&1
30
+ echo " done."
31
+ ;;
32
+ stop)
33
+ echo -n "Stopping $NAME ..."
34
+ start-stop-daemon --oknodo --stop --quiet --pidfile=$PIDFILE --exec $DAEMON
35
+ rm -f $PIDFILE > /dev/null 2>&1
36
+ echo " done."
37
+ ;;
38
+ restart)
39
+ $0 stop
40
+ $0 start
41
+ ;;
42
+ status)
43
+ if [ -f $PIDFILE ]; then
44
+ PID=`cat $PIDFILE`
45
+ ps -p $PID > /dev/null 2>&1
46
+ RC=$?
47
+ if [ "$RC" == "0" ]; then
48
+ echo "PassiveDNS is running with PID $PID..."
49
+ else
50
+ echo "PassiveDNS is not running..."
51
+ fi
52
+ else
53
+ echo "PassiveDNS is not running..."
54
+ fi
55
+ ;;
56
+ force-reload)
57
+ $0 stop
58
+ $0 start
59
+ ;;
60
+ *)
61
+ echo "Usage: $0 {start|stop|restart|force-reload|status}"
62
+ exit 1
63
+ esac
64
+
65
+ exit 0
66
+
dns_tunneling/passivedns-master/etc/init.d/passivedns-redhat ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/sh
2
+ # $Id$
3
+ #
4
+ # passivednsd Start/Stop the passivedns daemon.
5
+ #
6
+ # chkconfig: 2345 40 60
7
+ # description: passivedns rocks
8
+ #
9
+
10
+ # Quick and Dirty script by Eric Kollmann xnih13@gmail.com
11
+
12
+ lock=/var/lock/subsys/passivedns
13
+ prog=passivedns
14
+
15
+ # Source function library.
16
+ . /etc/rc.d/init.d/functions
17
+
18
+ # Source the local configuration file
19
+ . /etc/sysconfig/passivedns
20
+
21
+ # if there are any non blank values coming from the sysconfig file we'll change them to commands now
22
+
23
+ if [ "$INTERFACE" != "" ] ; then
24
+ INTERFACE="-i $INTERFACE"
25
+ fi
26
+
27
+ if [ "$PIDFILE" != "" ] ; then
28
+ PIDFILE="-p $PIDFILE"
29
+ fi
30
+
31
+ if [ "$LOGFILE" != "" ] ; then
32
+ LOGFILE="-l $LOGFILE"
33
+ fi
34
+
35
+ if [ "$LOGFIELDS" != "" ] ; then
36
+ LOGFIELDS="-f $LOGFIELDS"
37
+ fi
38
+
39
+ if [ "$NXDOMAINLOGFILE" != "" ] ; then
40
+ NXDOMAINLOGFILE="-L $NXDOMAINLOGFILE"
41
+ fi
42
+
43
+ if [ "$LOGSYSLOG" != "" ] ; then
44
+ LOGSYSLOG="-y"
45
+ fi
46
+
47
+ if [ "$NXSYSLOG" != "" ] ; then
48
+ NXSYSLOG="-Y"
49
+ fi
50
+
51
+ if [ "$BPF" != "" ] ; then
52
+ BPF="-b \"$BPF\""
53
+ fi
54
+
55
+ if [ "$SOFTMEM" != "" ] ; then
56
+ SOFTMEM="-S $SOFTMEM"
57
+ fi
58
+
59
+ if [ "$DNSCACHE" != "" ] ; then
60
+ DNSCACHE="-C $DNSCACHE"
61
+ fi
62
+
63
+ if [ "$DNSDUPE" != "" ] ; then
64
+ DNSDUPE="-P $DNSDUPE"
65
+ fi
66
+
67
+ if [ "$DNSRRTYPES" != "" ] ; then
68
+ DNSRRTYPES="-X $DNSRRTYPES"
69
+ fi
70
+
71
+ if [ "$USER" != "" ] ; then
72
+ USER="-u $USER"
73
+ fi
74
+
75
+ if [ "$GROUP" != "" ] ; then
76
+ GROUP="-g $GROUP"
77
+ fi
78
+
79
+ if [ "$DIRCHROOT" != "" ] ; then
80
+ DIRCHROOT="-T $DIRCHROOT"
81
+ fi
82
+
83
+ ######################################
84
+
85
+ RETVAL=0
86
+
87
+ function start(){
88
+ daemon $prog -D $INTERFACE $PIDFILE $LOGFILE $NXDOMAINLOGFILE $LOGSYSLOG $NXSYSLOG $LOGFIELDS $BPF $SOFTMEM $DNSCACHE $DNSDUPE $DNSRRTYPES $USER $GROUP $DIRCHROOT
89
+ RETVAL=$?
90
+ echo
91
+ [ $RETVAL -eq 0 ] && touch $lock
92
+ return $RETVAL
93
+ }
94
+
95
+ stop(){
96
+ killproc $prog
97
+ RETVAL=$?
98
+ echo
99
+ [ $RETVAL -eq 0 ] && rm -f $lock
100
+ return $RETVAL
101
+ }
102
+
103
+ case "$1" in
104
+ start)
105
+ echo -n "Starting $prog: "
106
+ start
107
+ ;;
108
+ stop)
109
+ echo -n "Stopping $prog: "
110
+ stop
111
+ ;;
112
+ restart)
113
+ stop
114
+ start
115
+ ;;
116
+ condrestart)
117
+ [ -e $lock ] && stop && start
118
+ ;;
119
+ status)
120
+ status passivedns
121
+ RETVAL=$?
122
+ ;;
123
+
124
+ *)
125
+ echo "Usage: $0 {start|stop|restart|condrestart|status}"
126
+ RETVAL=2
127
+ esac
128
+
129
+ exit $RETVAL
dns_tunneling/passivedns-master/etc/logrotate.d/passivedns ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /var/log/passivedns.log {
2
+ daily
3
+ rotate 30
4
+ missingok
5
+ notifempty
6
+ compress
7
+ delaycompress
8
+ postrotate
9
+ /bin/kill -HUP `pgrep passivedns 2>/dev/null` 2>/dev/null || true
10
+ endscript
11
+ su root syslog
12
+ }
13
+
dns_tunneling/passivedns-master/etc/sysconfig/passivedns-redhat ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /etc/sysconfig/passivedns
2
+ # $Id$
3
+ # Quick and Dirty Script by Eric Kollmann xnih13@gmail.com
4
+
5
+ # What interface should passivedns listen on?
6
+ INTERFACE=
7
+
8
+ # What user and group should passivedns drop to after starting?
9
+ # leave blank if you do not want to change privs
10
+ # if you do change privs you will need to provide that user with writes
11
+ # on the $PIDFILE directory below
12
+ USER=
13
+ GROUP=
14
+
15
+ # Name of passivedns log?
16
+ LOGFILE=
17
+
18
+ # Name of NXDOMAIN log?
19
+ NXDOMAINLOGFILE=
20
+
21
+ # Log to syslog? (set to "1" to enable)
22
+ LOGSYSLOG=
23
+
24
+ # Log NXDOMAIN to syslog? (set to "1" to enable)
25
+ NXSYSLOG=
26
+
27
+ # To add a BPF filter to the command line uncomment the following variable
28
+ # syntax corresponds to tcpdump(8)
29
+ # default is "port 53"
30
+ BPF=
31
+
32
+ # Name of PID file
33
+ # If you are dropping from root create the /var/run/passivedns folder
34
+ # and give rights to the $USER $GROUP defined above example:
35
+ # chown pdns:pdns /var/run/passivedns
36
+ # otherwise if staying as root just let it be written to /var/run/
37
+ #PIDFILE=/var/run/passivedns/passivedns.pid
38
+ #PIDFILE=/var/run/passivedns.pid
39
+ PIDFILE=
40
+
41
+ #Soft Memory Limit in MB
42
+ SOFTMEM=
43
+
44
+ #Seconds to cache DNS objects in memory
45
+ DNSCACHE=
46
+
47
+ #Seconds between printing duplicate DNS info
48
+ DNSDUPE=
49
+
50
+ #Manually set the values to log:
51
+ # FIELDS:
52
+ # H: YMD-HMS Stamp S: Timestamp(s) M: Timestamp(ms) c: Client IP
53
+ # s: Server IP C: Class Q: Query T: Type
54
+ # A: Answer t: TTL n: Count
55
+ LOGFIELDS=SMcsCQTAtn
56
+
57
+ #Manually set DNS RR Types to care about
58
+ # FLAGS:
59
+ # 4:A 6:AAAA C:CNAME D:DNAME N:NAPTR O:SOA
60
+ # P:PTR R:RP S:SRV T:TXT M:MX n:NS
61
+ # x:NXD
62
+ DNSRRTYPES=
63
+
64
+ #Directory to chroot into
65
+ DIRCHROOT=
66
+
dns_tunneling/passivedns-master/pdns.patch ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --- search-pdns-original.pl 2017-08-24 19:18:52.859541254 -0400
2
+ +++ /usr/local/bin/search-pdns.pl 2018-03-21 14:49:24.217877474 -0400
3
+ @@ -18,6 +18,7 @@
4
+ # along with this program; if not, write to the Free Software
5
+ # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
6
+ # ----------------------------------------------------------------------
7
+ +# Added Resource Record Type : PJN 20180321
8
+
9
+ use strict;
10
+ use warnings;
11
+ @@ -40,7 +41,7 @@
12
+
13
+ =head1 VERSION
14
+
15
+ - 0.1.0
16
+ + 0.1.1
17
+
18
+ =head1 SYNOPSIS
19
+
20
+ @@ -50,6 +51,7 @@
21
+
22
+ -s : %IP/Domain%
23
+ -r : Enables raw search
24
+ + -t : Resource Record Type (A, NS, MX, SOA, etc.)
25
+ --first-seen : Date to search from in iso format (2010-01-01 etc.)
26
+ --last-seen : Date to search to in iso format (2020-01-01 etc.)
27
+ --limit : Limit on search results (100)
28
+ @@ -73,6 +75,7 @@
29
+ our $FROM_DATE;
30
+ our $TO_DATE;
31
+ our $LIMIT;
32
+ +our $TYPE;
33
+
34
+ GetOptions(
35
+ 'd=s' => \$DEBUG,
36
+ @@ -81,6 +84,7 @@
37
+ 'first-seen=s' => \$FROM_DATE,
38
+ 'last-seen=s' => \$TO_DATE,
39
+ 'limit=s' => \$LIMIT,
40
+ + 't=s' => \$TYPE,
41
+ );
42
+
43
+ if ($SEARCH eq "") {
44
+ @@ -131,6 +135,13 @@
45
+ }
46
+ }
47
+
48
+ +
49
+ +if (defined $TYPE) {
50
+ + $QUERY1 = $QUERY1 . qq[AND maptype = '$TYPE' ];
51
+ + $QUERY2 = $QUERY2 . qq[AND maptype = '$TYPE' ];
52
+ +}
53
+ +
54
+ +
55
+ $QUERY = $QUERY1 . qq[ UNION ] . $QUERY2;
56
+
57
+ if (defined $LIMIT && $LIMIT =~ /^([\d])+$/) {
dns_tunneling/passivedns-master/src/Makefile.am ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #Makefile
2
+ AUTOMAKE_OPTIONS = -Wno-portability
3
+
4
+ OBJECTS=passivedns.o dns.o
5
+ bin_PROGRAMS=passivedns
6
+
7
+ all: $(bin_PROGRAMS)
8
+
9
+ %.o: %.c
10
+ $(CC) -O3 $(CPPFLAGS) -c $< -o $@
11
+
12
+ passivedns$(EXEEXT): $(OBJECTS)
13
+ $(CC) -o passivedns $(OBJECTS) $(LDFLAGS)
14
+
15
+ clean:
16
+ -rm -v passivedns *.o 2>/dev/null || true
17
+
dns_tunneling/passivedns-master/src/dns.c ADDED
@@ -0,0 +1,1886 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ ** This file is a part of PassiveDNS.
3
+ **
4
+ ** Copyright (C) 2010-2013, Edward Fjellskål <edwardfjellskaal@gmail.com>
5
+ **
6
+ ** This program is free software; you can redistribute it and/or modify
7
+ ** it under the terms of the GNU General Public License as published by
8
+ ** the Free Software Foundation; either version 2 of the License, or
9
+ ** (at your option) any later version.
10
+ **
11
+ ** This program is distributed in the hope that it will be useful,
12
+ ** but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ ** GNU General Public License for more details.
15
+ **
16
+ ** You should have received a copy of the GNU General Public License
17
+ ** along with this program; if not, write to the Free Software
18
+ ** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19
+ **
20
+ */
21
+
22
+ #include <stdio.h>
23
+ #include <stdlib.h>
24
+ #include <string.h>
25
+ #include <time.h>
26
+ #include <sys/types.h>
27
+ #include <arpa/inet.h>
28
+ #include <netinet/in.h>
29
+ #include <syslog.h>
30
+ #include <pcap.h>
31
+ #include "passivedns.h"
32
+ #include "dns.h"
33
+
34
+ #ifdef HAVE_JSON
35
+ #include <jansson.h>
36
+ #endif /* HAVE_JSON */
37
+
38
+ extern globalconfig config;
39
+
40
+ /* The 12th Carol number and 7th Carol prime, 16769023, is also a Carol emirp */
41
+ //#define DBUCKET_SIZE 16769023
42
+ #define DBUCKET_SIZE 3967 /* Carol that is primes */
43
+
44
+ pdns_record *dbucket[DBUCKET_SIZE];
45
+
46
+ uint64_t hash(unsigned char *str)
47
+ {
48
+ uint64_t hash = 5381;
49
+ uint64_t c;
50
+
51
+ while ((c = *str++))
52
+ hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
53
+ return hash % DBUCKET_SIZE;
54
+ }
55
+
56
+ void dns_parser(packetinfo *pi)
57
+ {
58
+ ldns_status status;
59
+ ldns_pkt *dns_pkt;
60
+
61
+ status = LDNS_STATUS_ERR;
62
+
63
+ /* In DNS tcp messages, the first 2 bytes signal the
64
+ * amount of data to expect. So we need to skip them in the read. */
65
+ if (pi->plen <= 2)
66
+ return; /* The minimum bytes in a packet, else return */
67
+
68
+ if (pi->af == AF_INET) {
69
+ switch (pi->ip4->ip_p) {
70
+ case IP_PROTO_TCP:
71
+ status = ldns_wire2pkt(&dns_pkt,pi->payload + 2, pi->plen - 2);
72
+ break;
73
+ case IP_PROTO_UDP:
74
+ status = ldns_wire2pkt(&dns_pkt,pi->payload, pi->plen);
75
+ break;
76
+ default:
77
+ break;
78
+ }
79
+ }
80
+ else if (pi->af == AF_INET6) {
81
+ switch (pi->ip6->next) {
82
+ case IP_PROTO_TCP:
83
+ status = ldns_wire2pkt(&dns_pkt,pi->payload + 2, pi->plen - 2);
84
+ break;
85
+ case IP_PROTO_UDP:
86
+ status = ldns_wire2pkt(&dns_pkt,pi->payload, pi->plen);
87
+ break;
88
+ default:
89
+ break;
90
+ }
91
+ }
92
+
93
+ if (status != LDNS_STATUS_OK) {
94
+ dlog("[D] ldns_wire2pkt status: %d\n", status);
95
+ update_dns_stats(pi,ERROR);
96
+ return;
97
+ }
98
+
99
+ /* We don't want to process truncated packets */
100
+ if (ldns_pkt_tc(dns_pkt)) {
101
+ dlog("[D] DNS packet with Truncated (TC) bit set! Skipping!\n");
102
+ ldns_pkt_free(dns_pkt);
103
+ update_dns_stats(pi, ERROR);
104
+ return;
105
+ }
106
+
107
+ /* We only care about answers when we record data */
108
+ if (ldns_pkt_qr(dns_pkt)) {
109
+ /* In situations where the first packet seen is a server response, the
110
+ client/server determination is incorrectly marked as an SC_CLIENT session
111
+ prior to the parsing of the DNS payload. In high bandwidth data centers
112
+ when running against millions of packet capture files, port reuse in the
113
+ span of a few minutes is not uncommon. This results in all subsequent
114
+ responses on the reused port being thrown out as if they came from a client. */
115
+ if (pi->sc == SC_UNKNOWN || pi->cxt->s_total_pkts == 0) {
116
+ dlog("[D] DNS Answer without a Question?: Query TID = %d and Answer TID = %d\n",
117
+ pi->cxt->plid, ldns_pkt_id(dns_pkt));
118
+ ldns_pkt_free(dns_pkt);
119
+ update_dns_stats(pi, ERROR);
120
+ return;
121
+ }
122
+ dlog("[D] DNS Answer\n");
123
+ /* Check the DNS TID */
124
+ if (pi->cxt->plid == ldns_pkt_id(dns_pkt)) {
125
+ dlog("[D] DNS Query TID match Answer TID: %d\n", pi->cxt->plid);
126
+ }
127
+ else {
128
+ dlog("[D] DNS Query TID did not match Answer TID: %d != %d - Skipping!\n",
129
+ pi->cxt->plid, ldns_pkt_id(dns_pkt));
130
+ ldns_pkt_free(dns_pkt);
131
+ update_dns_stats(pi,ERROR);
132
+ return;
133
+ }
134
+
135
+ /* From isc.org wording:
136
+ * We do not collect any of the query-response traffic that
137
+ * occurs when the client sets the RD or "Recursion Desired"
138
+ * bit to 1, that is, the traffic that occurs between DNS
139
+ * "stub" clients and the caching server itself, since only the
140
+ * traffic generated in response to a cache miss (RD bit set to 0)
141
+ * is strictly needed in order to build a passive DNS database.
142
+ */
143
+ if (ldns_pkt_rd(dns_pkt)) {
144
+ dlog("[D] DNS packet with Recursion Desired (RD) bit set!\n");
145
+ /* Between DNS-server to DNS-server, we should drop this kind
146
+ * of traffic if we are thinking hardening and correctness!
147
+ * But for people trying this out in a corporate network etc,
148
+ * between a client and a DNS proxy, will need this most likely
149
+ * to see any traffic at all. In the future, this might be
150
+ * controlled by a cmdline switch.
151
+ */
152
+ //ldns_pkt_free(decoded_dns);
153
+ //return;
154
+ }
155
+
156
+ if (!ldns_pkt_qdcount(dns_pkt)) {
157
+ /* No questions or answers */
158
+ dlog("[D] DNS packet did not contain a question. Skipping!\n");
159
+ ldns_pkt_free(dns_pkt);
160
+ update_dns_stats(pi, ERROR);
161
+ return;
162
+ }
163
+
164
+ /* Send it off for processing */
165
+ if (process_dns_answer(pi, dns_pkt) < 0)
166
+ dlog("[D] process_dns_answer() returned -1\n");
167
+ }
168
+ else {
169
+ /* We need to get the DNS TID from the Query to later match with the
170
+ * DNS TID in the answer - to harden the implementation.
171
+ */
172
+
173
+ /* With the new SC_UNKNOWN state, only responses from an SC_SERVER should be ignored. */
174
+ if (pi->sc == SC_SERVER) {
175
+ dlog("[D] DNS Query not from a client? Skipping!\n");
176
+ ldns_pkt_free(dns_pkt);
177
+ update_dns_stats(pi, ERROR);
178
+ return;
179
+ }
180
+
181
+ /* Check for reuse of a session and a hack for
182
+ * no timeout of sessions when reading pcaps atm. :/
183
+ * 60 Secs are default UDP timeout in cxt, and should
184
+ * be enough for a TCP session of DNS too.
185
+ */
186
+ if ((pi->cxt->plid != 0 && pi->cxt->plid != ldns_pkt_id(dns_pkt)) &&
187
+ ((pi->cxt->last_pkt_time - pi->cxt->start_time) <= 60)) {
188
+ dlog("[D] DNS Query on an established DNS session - TID: Old:%d New:%d\n",
189
+ pi->cxt->plid, ldns_pkt_id(dns_pkt));
190
+ /* Some clients have bad or strange random src
191
+ * port generator and will gladly reuse the same
192
+ * src port several times in a short time period.
193
+ * To implement this fully, each cxt should be include
194
+ * the TID in its tuple, but still this will make a mess :/
195
+ */
196
+ }
197
+ else
198
+ dlog("[D] New DNS Query\n");
199
+
200
+ if (!ldns_pkt_qdcount(dns_pkt)) {
201
+ /* No questions or answers */
202
+ dlog("[D] DNS Query packet did not contain a question? Skipping!\n");
203
+ ldns_pkt_free(dns_pkt);
204
+ update_dns_stats(pi, ERROR);
205
+ return;
206
+ }
207
+
208
+ if ((pi->cxt->plid = ldns_pkt_id(dns_pkt)))
209
+ dlog("[D] DNS Query with TID = %d\n", pi->cxt->plid);
210
+
211
+ else {
212
+ dlog("[E] Error getting DNS TID from Query!\n");
213
+ ldns_pkt_free(dns_pkt);
214
+ update_dns_stats(pi, ERROR);
215
+ return;
216
+ }
217
+ }
218
+
219
+ ldns_pkt_free(dns_pkt);
220
+ }
221
+
222
+ int process_dns_answer(packetinfo *pi, ldns_pkt *dns_pkt)
223
+ {
224
+ int rrcount_query;
225
+ int j;
226
+ ldns_rr_list *dns_query_domains;
227
+ ldns_buffer *dns_buff;
228
+
229
+ dns_query_domains = ldns_pkt_question(dns_pkt);
230
+ rrcount_query = ldns_rr_list_rr_count(dns_query_domains);
231
+ dns_buff = ldns_buffer_new(LDNS_MIN_BUFLEN);
232
+ dlog("[*] rrcount_query: %d\n", rrcount_query);
233
+
234
+ /* Do we ever have more than one question?
235
+ If we do, are we handling it correctly? */
236
+ for (j = 0; j < rrcount_query; j++)
237
+ {
238
+ ldns_rdf *rdf_data;
239
+
240
+ rdf_data = ldns_rr_owner(ldns_rr_list_rr(dns_query_domains, j));
241
+ dlog("[D] rdf_data: %p\n", rdf_data);
242
+
243
+ if (cache_dns_objects(pi, rdf_data, dns_buff, dns_pkt) != 0)
244
+ dlog("[D] cache_dns_objects() returned error\n");
245
+ }
246
+
247
+ ldns_buffer_free(dns_buff);
248
+ update_dns_stats(pi, SUCCESS);
249
+ return 0;
250
+ }
251
+
252
+ int cache_dns_objects(packetinfo *pi, ldns_rdf *rdf_data,
253
+ ldns_buffer *buff, ldns_pkt *dns_pkt)
254
+ {
255
+ int j;
256
+ int dns_answer_domain_cnt;
257
+ uint64_t dnshash;
258
+ ldns_status status;
259
+ pdns_record *pr = NULL;
260
+ ldns_rr_list *dns_answer_domains;
261
+ unsigned char *domain_name = 0;
262
+
263
+ ldns_buffer_clear(buff);
264
+ status = ldns_rdf2buffer_str(buff, rdf_data);
265
+
266
+ if (status != LDNS_STATUS_OK) {
267
+ dlog("[D] Error in ldns_rdf2buffer_str(): %d\n", status);
268
+ return -1;
269
+ }
270
+
271
+ dns_answer_domains = ldns_pkt_answer(dns_pkt);
272
+ dns_answer_domain_cnt = ldns_rr_list_rr_count(dns_answer_domains);
273
+ domain_name = (unsigned char *) ldns_buffer2str(buff);
274
+
275
+ if (domain_name == NULL) {
276
+ dlog("[D] Error in ldns_buffer2str(%p)\n", buff);
277
+ return -1;
278
+ }
279
+ else {
280
+ dlog("[D] domain_name: %s\n", domain_name);
281
+ dlog("[D] dns_answer_domain_cnt: %d\n",dns_answer_domain_cnt);
282
+ }
283
+
284
+ if (dns_answer_domain_cnt == 0 && ldns_pkt_get_rcode(dns_pkt) != 0) {
285
+ uint16_t rcode = ldns_pkt_get_rcode(dns_pkt);
286
+ dlog("[D] Error return code: %d\n", rcode);
287
+
288
+ /* PROBLEM:
289
+ * As there is no valid ldns_rr here and we can't fake one that will
290
+ * be very unique, we cant push this to the normal
291
+ * bucket[hash->linked_list]. We should probably allocate a static
292
+ * bucket[MAX_NXDOMAIN] to hold NXDOMAINS, and when that is full, pop
293
+ * out the oldest (LRU). A simple script querying for random non-existing
294
+ * domains could easily put stress on passivedns (think conficker etc.)
295
+ * if the bucket is to big or non-efficient. We would still store data
296
+ * such as: firstseen,lastseen,client_ip,server_ip,class,query,NXDOMAIN
297
+ */
298
+ if (config.dnsfe & (pdns_chk_dnsfe(rcode))) {
299
+ ldns_rr_list *dns_query_domains;
300
+ ldns_rr *rr;
301
+
302
+ dnshash = hash(domain_name);
303
+ dlog("[D] Hash: %lu\n", dnshash);
304
+ /* Check if the node exists, if not, make it */
305
+ pr = get_pdns_record(dnshash, pi, domain_name);
306
+
307
+ /* Set the SRC flag: */
308
+ //lname_node->srcflag |= pdns_chk_dnsfe(rcode);
309
+ dns_query_domains = ldns_pkt_question(dns_pkt);
310
+ rr = ldns_rr_list_rr(dns_query_domains, 0);
311
+ if ((pr->last_seen.tv_sec - pr->last_print.tv_sec) >= config.dnsprinttime) {
312
+ /* Print the SRC Error record */
313
+ print_passet(pr, NULL, rr, rdf_data, rcode);
314
+ }
315
+ }
316
+ else
317
+ dlog("[D] Error return code %d was not processed:%d\n",
318
+ pdns_chk_dnsfe(rcode), config.dnsfe);
319
+
320
+ free(domain_name);
321
+ return 0;
322
+ }
323
+
324
+ for (j = 0; j < dns_answer_domain_cnt; j++)
325
+ {
326
+ int offset = -1;
327
+ int to_offset = -1;
328
+ int len;
329
+ ldns_rr *rr;
330
+ ldns_rdf *rname;
331
+ char *rdomain_name = NULL;
332
+ char *tmp1 = NULL;
333
+ char *tmp2 = NULL;
334
+
335
+ rr = ldns_rr_list_rr(dns_answer_domains, j);
336
+
337
+ switch (ldns_rr_get_type(rr)) {
338
+ case LDNS_RR_TYPE_LOC:
339
+ if (config.dnsf & DNS_CHK_LOC)
340
+ offset = 0;
341
+ break;
342
+ case LDNS_RR_TYPE_GPOS:
343
+ if (config.dnsf & DNS_CHK_LOC) {
344
+ offset = 0;
345
+ to_offset = 3;
346
+ }
347
+ break;
348
+ case LDNS_RR_TYPE_RRSIG:
349
+ if (config.dnsf & DNS_CHK_DNSSEC) {
350
+ offset = 0;
351
+ to_offset = 9;
352
+ }
353
+ break;
354
+ case LDNS_RR_TYPE_DNSKEY:
355
+ if (config.dnsf & DNS_CHK_DNSSEC) {
356
+ offset = 0;
357
+ to_offset = 4;
358
+ }
359
+ break;
360
+
361
+ #ifdef LDNS_RR_TYPE_NSEC3PARAM
362
+ case LDNS_RR_TYPE_NSEC3PARAM:
363
+ if (config.dnsf & DNS_CHK_DNSSEC) {
364
+ offset = 0;
365
+ to_offset = 4;
366
+ }
367
+ break;
368
+ #endif /* LDNS_RR_TYPE_NSEC3PARAM */
369
+ case LDNS_RR_TYPE_NSEC3:
370
+ if (config.dnsf & DNS_CHK_DNSSEC) {
371
+ offset = 0;
372
+ to_offset = 5;
373
+ }
374
+ break;
375
+
376
+ case LDNS_RR_TYPE_NSEC:
377
+ if (config.dnsf & DNS_CHK_DNSSEC) {
378
+ offset = 0;
379
+ to_offset = 2;
380
+ }
381
+ break;
382
+ case LDNS_RR_TYPE_HINFO:
383
+ if (config.dnsf & DNS_CHK_HINFO) {
384
+ offset = 0;
385
+ to_offset = 2;
386
+ }
387
+ break;
388
+ case LDNS_RR_TYPE_DS:
389
+ if (config.dnsf & DNS_CHK_DNSSEC) {
390
+ offset = 0;
391
+ to_offset = 4;
392
+ }
393
+ break;
394
+ case LDNS_RR_TYPE_SSHFP:
395
+ if (config.dnsf & DNS_CHK_SSHFP) {
396
+ offset = 0;
397
+ to_offset = 3;
398
+ }
399
+ break;
400
+ case LDNS_RR_TYPE_AAAA:
401
+ if (config.dnsf & DNS_CHK_AAAA)
402
+ offset = 0;
403
+ break;
404
+ case LDNS_RR_TYPE_A:
405
+ if (config.dnsf & DNS_CHK_A)
406
+ offset = 0;
407
+ break;
408
+ case LDNS_RR_TYPE_PTR:
409
+ if (config.dnsf & DNS_CHK_PTR)
410
+ offset = 0;
411
+ break;
412
+ case LDNS_RR_TYPE_CNAME:
413
+ if (config.dnsf & DNS_CHK_CNAME)
414
+ offset = 0;
415
+ break;
416
+ case LDNS_RR_TYPE_DNAME:
417
+ if (config.dnsf & DNS_CHK_DNAME)
418
+ offset = 0;
419
+ break;
420
+ case LDNS_RR_TYPE_NAPTR:
421
+ if (config.dnsf & DNS_CHK_NAPTR) {
422
+ offset = 0;
423
+ to_offset = 6;
424
+ }
425
+ break;
426
+ case LDNS_RR_TYPE_RP:
427
+ if (config.dnsf & DNS_CHK_RP)
428
+ offset = 0;
429
+ break;
430
+ case LDNS_RR_TYPE_SRV:
431
+ if (config.dnsf & DNS_CHK_SRV)
432
+ offset = 3;
433
+ break;
434
+ case LDNS_RR_TYPE_TXT:
435
+ if (config.dnsf & DNS_CHK_TXT)
436
+ offset = 0;
437
+ break;
438
+ case LDNS_RR_TYPE_SPF:
439
+ if (config.dnsf & DNS_CHK_SPF)
440
+ offset = 0;
441
+ break;
442
+ case LDNS_RR_TYPE_SOA:
443
+ if (config.dnsf & DNS_CHK_SOA)
444
+ offset = 0;
445
+ break;
446
+ case LDNS_RR_TYPE_MX:
447
+ if (config.dnsf & DNS_CHK_MX)
448
+ offset = 1;
449
+ break;
450
+ case LDNS_RR_TYPE_NS:
451
+ if (config.dnsf & DNS_CHK_NS)
452
+ offset = 0;
453
+ break;
454
+ default:
455
+ offset = -1;
456
+ dlog("[D] ldns_rr_get_type: %d\n", ldns_rr_get_type(rr));
457
+ break;
458
+ }
459
+
460
+ if (offset == -1) {
461
+ dlog("[D] LDNS_RR_TYPE not enabled/supported: %d\n",
462
+ ldns_rr_get_type(rr));
463
+ continue;
464
+ }
465
+ do {
466
+ /* Get the rdf data from the rr */
467
+ ldns_buffer_clear(buff);
468
+ rname = ldns_rr_rdf(rr, offset);
469
+
470
+ if (rname == NULL) {
471
+ dlog("[D] ldns_rr_rdf returned: NULL\n");
472
+ break;
473
+ }
474
+
475
+ ldns_rdf2buffer_str(buff, rname);
476
+ rdomain_name = (char *) ldns_buffer2str(buff);
477
+
478
+ if (rdomain_name == NULL)
479
+ continue;
480
+ len = strlen(rdomain_name) + 5;
481
+
482
+ if (tmp1 != NULL)
483
+ len += strlen(tmp1);
484
+ tmp2 = malloc(len);
485
+
486
+ if (tmp1 != NULL) {
487
+ tmp2 = strcpy(tmp2, tmp1);
488
+ tmp2 = strcat(tmp2, " ");
489
+ }
490
+ else
491
+ tmp2 = strcpy(tmp2, "");
492
+
493
+ free(tmp1);
494
+ tmp2 = strcat(tmp2, rdomain_name);
495
+ tmp1 = tmp2;
496
+ free(rdomain_name);
497
+ offset ++;
498
+ } while (offset < to_offset);
499
+
500
+ rdomain_name = tmp1;
501
+
502
+ if (rname == NULL)
503
+ continue;
504
+
505
+ if (rdomain_name == NULL && offset <= 1) {
506
+ dlog("[D] ldns_buffer2str returned: NULL\n");
507
+ continue;
508
+ }
509
+ dlog("[D] rdomain_name: %s\n", rdomain_name);
510
+
511
+ if (pr == NULL) {
512
+ dnshash = hash(domain_name);
513
+ dlog("[D] Hash: %lu\n", dnshash);
514
+ /* Check if the node exists, if not, make it */
515
+ pr = get_pdns_record(dnshash, pi, domain_name);
516
+ }
517
+
518
+ /* Update the pdns record with the pdns asset */
519
+ update_pdns_record_asset(pi, pr, rr, (unsigned char*)rdomain_name);
520
+
521
+ /* If CNAME, free domain_name, and cp rdomain_name to domain_name */
522
+ if (ldns_rr_get_type(rr) == LDNS_RR_TYPE_CNAME) {
523
+ if (config.dnsf & DNS_CHK_CNAME) {
524
+ int len;
525
+ free(domain_name);
526
+ len = strlen((char *)rdomain_name);
527
+ domain_name = calloc(1, (len + 1));
528
+ strncpy((char *)domain_name, (char *)rdomain_name, len);
529
+ dnshash = hash(domain_name);
530
+ dlog("[D] Hash: %lu\n", dnshash);
531
+ pr = get_pdns_record(dnshash, pi, domain_name);
532
+ }
533
+ }
534
+
535
+ /* Free the rdomain_name */
536
+ free(rdomain_name);
537
+ }
538
+ free(domain_name);
539
+ return 0;
540
+ }
541
+
542
+ void update_pdns_record_asset(packetinfo *pi, pdns_record *pr,
543
+ ldns_rr *rr, unsigned char *rdomain_name)
544
+ {
545
+ pdns_asset *passet = pr->passet;
546
+ pdns_asset *head = passet;
547
+ ldns_rr *prr = NULL;
548
+ uint32_t len = 0;
549
+
550
+ dlog("Searching: %u, %s, %s\n", rr->_rr_type, pr->qname, rdomain_name);
551
+
552
+ while (passet != NULL)
553
+ {
554
+ /* If found, update */
555
+ dlog("Matching: %u, %s, %s\n",passet->rr->_rr_type, pr->qname,
556
+ passet->answer);
557
+ dlog("[*] RR:%u, %u\n", passet->rr->_rr_type, rr->_rr_type);
558
+ if (passet->rr->_rr_type == rr->_rr_type) {
559
+ dlog("[*] rr match\n");
560
+ dlog("r:%s == a:%s\n", rdomain_name, passet->answer);
561
+ if (strcmp((const char *)rdomain_name,
562
+ (const char *)passet->answer) == 0 ) {
563
+ dlog("[*] rname/answer match\n");
564
+ /* We have this, update and if its over 24h since last print -
565
+ print it, then return */
566
+ passet->seen++;
567
+ memcpy( &passet->last_seen, &pi->pheader->ts, sizeof( struct timeval ) );
568
+ passet->af = pi->cxt->af;
569
+ passet->cip = pi->cxt->s_ip; /* This should always be the client IP */
570
+ passet->sip = pi->cxt->d_ip; /* This should always be the server IP */
571
+ if (rr->_ttl > passet->rr->_ttl)
572
+ passet->rr->_ttl = rr->_ttl; /* Catch the highest TTL seen */
573
+ dlog("[*] DNS asset updated...\n");
574
+ if ((passet->last_seen.tv_sec -
575
+ passet->last_print.tv_sec) >= config.dnsprinttime)
576
+ print_passet(pr, passet, passet->rr, NULL, 0);
577
+ return;
578
+ }
579
+ }
580
+ passet = passet->next;
581
+ }
582
+
583
+ /* Else, we got a new passet :) */
584
+ if (passet == NULL) {
585
+ passet = (pdns_asset*) calloc(1, sizeof(pdns_asset));
586
+ dlog("[*] Allocated a new dns asset...\n");
587
+ config.p_s.dns_assets++;
588
+ config.dns_assets++;
589
+ prr = (ldns_rr*) calloc(1, sizeof(ldns_rr));
590
+ prr->_owner = rr->_owner;
591
+ prr->_ttl = rr->_ttl;
592
+ prr->_rd_count = rr->_rd_count;
593
+ prr->_rr_type = rr->_rr_type;
594
+ prr->_rr_class = rr->_rr_class;
595
+ prr->_rdata_fields = rr->_rdata_fields;
596
+ passet->seen = 1;
597
+ passet->rr = prr;
598
+ }
599
+ else
600
+ dlog("[D] BAD\n");
601
+
602
+ if (head != NULL ) {
603
+ head->prev = passet;
604
+ passet->next = head;
605
+ }
606
+ else
607
+ passet->next = NULL;
608
+
609
+ /* Populate new values */
610
+ memcpy( &passet->first_seen, &pi->pheader->ts, sizeof( struct timeval ) );
611
+ memcpy( &passet->last_seen, &pi->pheader->ts, sizeof( struct timeval ) );
612
+ passet->af = pi->cxt->af;
613
+ passet->cip = pi->cxt->s_ip; /* This should always be the client IP */
614
+ passet->sip = pi->cxt->d_ip; /* This should always be the server IP */
615
+ if (pi-> eth_hdr) {
616
+ memcpy(passet->cmac, pi->eth_hdr->ether_dst, 6 * sizeof(u_char));
617
+ memcpy(passet->smac, pi->eth_hdr->ether_src, 6 * sizeof(u_char));
618
+ }
619
+ passet->prev = NULL;
620
+ len = strlen((char *)rdomain_name);
621
+ passet->answer = calloc(1, (len + 1));
622
+ strncpy((char *)passet->answer, (char *)rdomain_name, len);
623
+
624
+ dlog("[D] Adding: %u, %s, %s\n",passet->rr->_rr_type, pr->qname,
625
+ rdomain_name);
626
+
627
+ pr->passet = passet;
628
+
629
+ print_passet(pr, passet, passet->rr, NULL, 0);
630
+ }
631
+
632
+ const char *u_ntop(const struct in6_addr ip_addr, int af, char *dest)
633
+ {
634
+ if (af == AF_INET) {
635
+ if (!inet_ntop(AF_INET, &IP4ADDR(&ip_addr), dest,
636
+ INET_ADDRSTRLEN + 1)) {
637
+ dlog("[E] Something died in inet_ntop\n");
638
+ return NULL;
639
+ }
640
+ }
641
+ else if (af == AF_INET6) {
642
+ if (!inet_ntop(AF_INET6, &ip_addr, dest, INET6_ADDRSTRLEN + 1)) {
643
+ dlog("[E] Something died in inet_ntop\n");
644
+ return NULL;
645
+ }
646
+ }
647
+ return dest;
648
+ }
649
+
650
+ void print_passet(pdns_record *l, pdns_asset *p, ldns_rr *rr,
651
+ ldns_rdf *lname, uint16_t rcode)
652
+ {
653
+ FILE *fd = NULL;
654
+ static char ip_addr_s[INET6_ADDRSTRLEN];
655
+ static char ip_addr_c[INET6_ADDRSTRLEN];
656
+ char *d = config.log_delimiter;
657
+ char *proto;
658
+ char *rr_class;
659
+ char *rr_type;
660
+ char *rr_rcode;
661
+ char buffer[1000] = "";
662
+ char *output = buffer;
663
+ int offset = 0;
664
+ uint8_t is_err_record = 0;
665
+
666
+ #ifdef HAVE_JSON
667
+ json_t *jdata;
668
+ json_t *json_timestamp_ymdhms;
669
+ json_t *json_timestamp_s;
670
+ json_t *json_timestamp_ms;
671
+ json_t *json_hostname;
672
+ json_t *json_client;
673
+ json_t *json_server;
674
+ json_t *json_proto;
675
+ json_t *json_class;
676
+ json_t *json_query;
677
+ json_t *json_query_len;
678
+ json_t *json_type;
679
+ json_t *json_answer;
680
+ json_t *json_answer_len;
681
+ json_t *json_ttl;
682
+ json_t *json_count;
683
+ size_t data_flags = 0;
684
+
685
+ /* Print in the same order as inserted */
686
+ data_flags |= JSON_PRESERVE_ORDER;
687
+
688
+ /* No whitespace between fields */
689
+ data_flags |= JSON_COMPACT;
690
+ #endif /* HAVE_JSON */
691
+
692
+ /* If pdns_asset is not defined, then this is a NXD record */
693
+ if (p == NULL)
694
+ is_err_record = 1;
695
+
696
+ /* Use the correct file descriptor */
697
+ if (is_err_record && config.output_log_nxd) {
698
+ if (config.logfile_all)
699
+ fd = config.logfile_fd;
700
+ else
701
+ fd = config.logfile_nxd_fd;
702
+ if (fd == NULL)
703
+ return;
704
+ }
705
+ else if (!is_err_record && config.output_log) {
706
+ fd = config.logfile_fd;
707
+ if (fd == NULL) return;
708
+ }
709
+
710
+ if (is_err_record) {
711
+ u_ntop(l->sip, l->af, ip_addr_s);
712
+ u_ntop(l->cip, l->af, ip_addr_c);
713
+ }
714
+ else {
715
+ u_ntop(p->sip, p->af, ip_addr_s);
716
+ u_ntop(p->cip, p->af, ip_addr_c);
717
+ }
718
+
719
+ proto = malloc(4);
720
+ rr_class = malloc(10);
721
+ rr_type = malloc(12);
722
+ rr_rcode = malloc(20);
723
+
724
+ switch (l->proto) {
725
+ case IP_PROTO_TCP:
726
+ snprintf(proto, 4, "tcp");
727
+ break;
728
+ case IP_PROTO_UDP:
729
+ snprintf(proto, 4, "udp");
730
+ break;
731
+ default:
732
+ snprintf(proto, 4, "%d", l->proto);
733
+ break;
734
+ }
735
+
736
+ switch (ldns_rr_get_class(rr)) {
737
+ case LDNS_RR_CLASS_IN:
738
+ snprintf(rr_class, 10, "IN");
739
+ break;
740
+ case LDNS_RR_CLASS_CH:
741
+ snprintf(rr_class, 10, "CH");
742
+ break;
743
+ case LDNS_RR_CLASS_HS:
744
+ snprintf(rr_class, 10, "HS");
745
+ break;
746
+ case LDNS_RR_CLASS_NONE:
747
+ snprintf(rr_class, 10, "NONE");
748
+ break;
749
+ case LDNS_RR_CLASS_ANY:
750
+ snprintf(rr_class, 10, "ANY");
751
+ break;
752
+ default:
753
+ snprintf(rr_class, 10, "%d", ldns_rr_get_class(rr));
754
+ break;
755
+ }
756
+
757
+ switch (ldns_rr_get_type(rr)) {
758
+ case LDNS_RR_TYPE_HINFO:
759
+ snprintf(rr_type, 10, "HINFO");
760
+ break;
761
+ case LDNS_RR_TYPE_SSHFP:
762
+ snprintf(rr_type, 10, "SSHFP");
763
+ break;
764
+ case LDNS_RR_TYPE_GPOS:
765
+ snprintf(rr_type, 10, "GPOS");
766
+ break;
767
+ case LDNS_RR_TYPE_LOC:
768
+ snprintf(rr_type, 10, "LOC");
769
+ break;
770
+ case LDNS_RR_TYPE_DNSKEY:
771
+ snprintf(rr_type, 10, "DNSKEY");
772
+ break;
773
+ #ifdef LDNS_RR_TYPE_NSEC3PARAM
774
+ case LDNS_RR_TYPE_NSEC3PARAM:
775
+ snprintf(rr_type, 11, "NSEC3PARAM");
776
+ break;
777
+ #endif /* LDNS_RR_TYPE_NSEC3PARAM */
778
+ case LDNS_RR_TYPE_NSEC3:
779
+ snprintf(rr_type, 10, "NSEC3");
780
+ break;
781
+ case LDNS_RR_TYPE_NSEC:
782
+ snprintf(rr_type, 10, "NSEC");
783
+ break;
784
+ case LDNS_RR_TYPE_RRSIG:
785
+ snprintf(rr_type, 10, "RRSIG");
786
+ break;
787
+ case LDNS_RR_TYPE_DS:
788
+ snprintf(rr_type, 10, "DS");
789
+ break;
790
+ case LDNS_RR_TYPE_PTR:
791
+ snprintf(rr_type, 10, "PTR");
792
+ break;
793
+ case LDNS_RR_TYPE_A:
794
+ snprintf(rr_type, 10, "A");
795
+ break;
796
+ case LDNS_RR_TYPE_AAAA:
797
+ snprintf(rr_type, 10, "AAAA");
798
+ break;
799
+ case LDNS_RR_TYPE_CNAME:
800
+ snprintf(rr_type, 10, "CNAME");
801
+ break;
802
+ case LDNS_RR_TYPE_DNAME:
803
+ snprintf(rr_type, 10, "DNAME");
804
+ break;
805
+ case LDNS_RR_TYPE_NAPTR:
806
+ snprintf(rr_type, 10, "NAPTR");
807
+ break;
808
+ case LDNS_RR_TYPE_RP:
809
+ snprintf(rr_type, 10, "RP");
810
+ break;
811
+ case LDNS_RR_TYPE_SRV:
812
+ snprintf(rr_type, 10, "SRV");
813
+ break;
814
+ case LDNS_RR_TYPE_TXT:
815
+ snprintf(rr_type, 10, "TXT");
816
+ break;
817
+ case LDNS_RR_TYPE_SPF:
818
+ snprintf(rr_type, 10, "SPF");
819
+ break;
820
+ case LDNS_RR_TYPE_SOA:
821
+ snprintf(rr_type, 10, "SOA");
822
+ break;
823
+ case LDNS_RR_TYPE_NS:
824
+ snprintf(rr_type, 10, "NS");
825
+ break;
826
+ case LDNS_RR_TYPE_MX:
827
+ snprintf(rr_type, 10, "MX");
828
+ break;
829
+ default:
830
+ if (is_err_record)
831
+ snprintf(rr_type, 10, "%d", ldns_rdf_get_type(lname));
832
+ else
833
+ snprintf(rr_type, 10, "%d", p->rr->_rr_type);
834
+ break;
835
+ }
836
+
837
+ if (is_err_record) {
838
+ switch (rcode) {
839
+ case 1:
840
+ snprintf(rr_rcode, 20, "FORMERR");
841
+ break;
842
+ case 2:
843
+ snprintf(rr_rcode, 20, "SERVFAIL");
844
+ break;
845
+ case 3:
846
+ snprintf(rr_rcode, 20, "NXDOMAIN");
847
+ break;
848
+ case 4:
849
+ snprintf(rr_rcode, 20, "NOTIMPL");
850
+ break;
851
+ case 5:
852
+ snprintf(rr_rcode, 20, "REFUSED");
853
+ break;
854
+ case 6:
855
+ snprintf(rr_rcode, 20, "YXDOMAIN");
856
+ break;
857
+ case 7:
858
+ snprintf(rr_rcode, 20, "YXRRSET");
859
+ break;
860
+ case 8:
861
+ snprintf(rr_rcode, 20, "NXRRSET");
862
+ break;
863
+ case 9:
864
+ snprintf(rr_rcode, 20, "NOTAUTH");
865
+ break;
866
+ case 10:
867
+ snprintf(rr_rcode, 20, "NOTZONE");
868
+ break;
869
+ default:
870
+ snprintf(rr_rcode, 20, "UNKNOWN-ERROR-%d", rcode);
871
+ break;
872
+ }
873
+ }
874
+
875
+ #ifdef HAVE_JSON
876
+ if ((is_err_record && config.use_json_nxd) ||
877
+ (!is_err_record && config.use_json)) {
878
+ jdata = json_object();
879
+
880
+ /* Print timestamp(ymdhms) */
881
+ if (config.fieldsf & FIELD_TIMESTAMP_YMDHMS) {
882
+ struct tm *tmpTime;
883
+ char timestr[200];
884
+ tmpTime = localtime(&l->last_seen.tv_sec);
885
+ strftime(timestr, sizeof(timestr), "%Y-%m-%d %H:%M:%S", tmpTime);
886
+ json_timestamp_ymdhms = json_string(timestr);
887
+ json_object_set(jdata, JSON_TIMESTAMP, json_timestamp_ymdhms);
888
+ json_decref(json_timestamp_ymdhms);
889
+ }
890
+
891
+ /* Print timestamp(s) */
892
+ if (config.fieldsf & FIELD_TIMESTAMP_S) {
893
+ json_timestamp_s = json_integer(l->last_seen.tv_sec);
894
+ json_object_set(jdata, JSON_TIMESTAMP_S, json_timestamp_s);
895
+ json_decref(json_timestamp_s);
896
+ }
897
+
898
+ /* Print timestamp(ms) */
899
+ if (config.fieldsf & FIELD_TIMESTAMP_MS) {
900
+ json_timestamp_ms = json_integer(l->last_seen.tv_usec);
901
+ json_object_set(jdata, JSON_TIMESTAMP_MS, json_timestamp_ms);
902
+ json_decref(json_timestamp_ms);
903
+ }
904
+
905
+ /* Print hostname */
906
+ if (config.fieldsf & FIELD_HOSTNAME) {
907
+ json_hostname = json_string(config.hostname);
908
+ json_object_set(jdata, JSON_HOSTNAME, json_hostname);
909
+ json_decref(json_hostname);
910
+ }
911
+
912
+ /* Print client IP */
913
+ if (config.fieldsf & FIELD_CLIENT) {
914
+ json_client = json_string(ip_addr_c);
915
+ json_object_set(jdata, JSON_CLIENT, json_client);
916
+ json_decref(json_client);
917
+ }
918
+
919
+ /* Print server IP */
920
+ if (config.fieldsf & FIELD_SERVER) {
921
+ json_server = json_string(ip_addr_s);
922
+ json_object_set(jdata, JSON_SERVER, json_server);
923
+ json_decref(json_server);
924
+ }
925
+
926
+ /* Print protocol */
927
+ if (config.fieldsf & FIELD_PROTO) {
928
+ json_proto = json_string(proto);
929
+ json_object_set(jdata, JSON_PROTO, json_proto);
930
+ json_decref(json_proto);
931
+ }
932
+
933
+ /* Print class */
934
+ if (config.fieldsf & FIELD_CLASS) {
935
+ json_class = json_string(rr_class);
936
+ json_object_set(jdata, JSON_CLASS, json_class);
937
+ json_decref(json_class);
938
+ }
939
+
940
+ /* Print query */
941
+ if (config.fieldsf & FIELD_QUERY) {
942
+ json_query = json_string((const char *)l->qname);
943
+ json_object_set(jdata, JSON_QUERY, json_query);
944
+ json_decref(json_query);
945
+ }
946
+
947
+ /* Print query length */
948
+ if (config.fieldsf & FIELD_QUERY_LEN) {
949
+ json_query_len = json_integer(strlen(l->qname));
950
+ json_object_set(jdata, JSON_QUERY_LEN, json_query_len);
951
+ json_decref(json_query_len);
952
+ }
953
+
954
+ /* Print type */
955
+ if (config.fieldsf & FIELD_TYPE) {
956
+ json_type = json_string(rr_type);
957
+ json_object_set(jdata, JSON_TYPE, json_type);
958
+ json_decref(json_type);
959
+ }
960
+
961
+ if (is_err_record) {
962
+ /* Print answer */
963
+ if (config.fieldsf & FIELD_ANSWER) {
964
+ json_answer = json_string(rr_rcode);
965
+ json_object_set(jdata, JSON_ANSWER, json_answer);
966
+ json_decref(json_answer);
967
+ }
968
+
969
+ /* Print answer length */
970
+ if (config.fieldsf & FIELD_ANSWER_LEN) {
971
+ json_answer_len = json_integer(strlen(rr_rcode));
972
+ json_object_set(jdata, JSON_ANSWER_LEN, json_answer_len);
973
+ json_decref(json_answer_len);
974
+ }
975
+
976
+ /* Print TTL */
977
+ if (config.fieldsf & FIELD_TTL) {
978
+ json_ttl = json_integer(PASSET_ERR_TTL);
979
+ json_object_set(jdata, JSON_TTL, json_ttl);
980
+ json_decref(json_ttl);
981
+ }
982
+
983
+ /* Print count */
984
+ if (config.fieldsf & FIELD_COUNT) {
985
+ json_count = json_integer(PASSET_ERR_COUNT);
986
+ json_object_set(jdata, JSON_COUNT, json_count);
987
+ json_decref(json_count);
988
+ }
989
+ }
990
+ else {
991
+ /* Print answer */
992
+ if (config.fieldsf & FIELD_ANSWER) {
993
+ json_answer = json_string((const char *)p->answer);
994
+ json_object_set(jdata, JSON_ANSWER, json_answer);
995
+ json_decref(json_answer);
996
+ }
997
+
998
+ /* Print answer length */
999
+ if (config.fieldsf & FIELD_ANSWER_LEN) {
1000
+ json_answer_len = json_integer(strlen(p->answer));
1001
+ json_object_set(jdata, JSON_ANSWER_LEN, json_answer_len);
1002
+ json_decref(json_answer_len);
1003
+ }
1004
+
1005
+ /* Print TTL */
1006
+ if (config.fieldsf & FIELD_TTL) {
1007
+ json_ttl = json_integer(p->rr->_ttl);
1008
+ json_object_set(jdata, JSON_TTL, json_ttl);
1009
+ json_decref(json_ttl);
1010
+ }
1011
+
1012
+ /* Print count */
1013
+ if (config.fieldsf & FIELD_COUNT) {
1014
+ json_count = json_integer(p->seen);
1015
+ json_object_set(jdata, JSON_COUNT, json_count);
1016
+ json_decref(json_count);
1017
+ }
1018
+ }
1019
+
1020
+ output = json_dumps(jdata, data_flags);
1021
+ json_decref(jdata);
1022
+ if (output == NULL)
1023
+ return;
1024
+ }
1025
+ else {
1026
+ #endif /* HAVE_JSON */
1027
+ /* Print timestamp */
1028
+ if ((config.fieldsf & FIELD_TIMESTAMP_YMDHMS)) {
1029
+ struct tm *tmpTime;
1030
+ char timestr[200];
1031
+ tmpTime = localtime(&l->last_seen.tv_sec);
1032
+ strftime(timestr, sizeof(timestr), "%Y-%m-%d %H:%M:%S", tmpTime);
1033
+ if (is_err_record)
1034
+ offset += snprintf(output, sizeof(buffer) - offset, "%s.%06lu",
1035
+ timestr, l->last_seen.tv_usec);
1036
+ else
1037
+ offset += snprintf(output, sizeof(buffer) - offset, "%s.%06lu",
1038
+ timestr, p->last_seen.tv_usec);
1039
+ }
1040
+ else if ((config.fieldsf & FIELD_TIMESTAMP_S) &&
1041
+ (config.fieldsf & FIELD_TIMESTAMP_MS)) {
1042
+ if (is_err_record)
1043
+ offset += snprintf(output, sizeof(buffer) - offset, "%lu.%06lu",
1044
+ l->last_seen.tv_sec, l->last_seen.tv_usec);
1045
+ else
1046
+ offset += snprintf(output, sizeof(buffer) - offset, "%lu.%06lu",
1047
+ p->last_seen.tv_sec, p->last_seen.tv_usec);
1048
+ }
1049
+ else if (config.fieldsf & FIELD_TIMESTAMP_S) {
1050
+ if (is_err_record)
1051
+ offset += snprintf(output, sizeof(buffer) - offset, "%lu", l->last_seen.tv_sec);
1052
+ else
1053
+ offset += snprintf(output, sizeof(buffer) - offset, "%lu", p->last_seen.tv_sec);
1054
+ }
1055
+ else if (config.fieldsf & FIELD_TIMESTAMP_MS) {
1056
+ if (is_err_record)
1057
+ offset += snprintf(output, sizeof(buffer) - offset, "%06lu", l->last_seen.tv_usec);
1058
+ else
1059
+ offset += snprintf(output, sizeof(buffer) - offset, "%06lu", p->last_seen.tv_usec);
1060
+ }
1061
+
1062
+ /* Print hostname */
1063
+ if (config.fieldsf & FIELD_HOSTNAME) {
1064
+ if (offset != 0)
1065
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", d);
1066
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", config.hostname);
1067
+ }
1068
+
1069
+ /* Print client IP */
1070
+ if (config.fieldsf & FIELD_CLIENT) {
1071
+ if (offset != 0)
1072
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", d);
1073
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", ip_addr_c);
1074
+ }
1075
+
1076
+ /* Print client hardware address */
1077
+ if (config.fieldsf & FIELD_CLT_HWADDR) {
1078
+ char buf[128];
1079
+ if (offset != 0)
1080
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", d);
1081
+ snprintf(buf, 128, "%02x:%02x:%02x:%02x:%02x:%02x",
1082
+ p->cmac[0], p->cmac[1], p->cmac[2],
1083
+ p->cmac[3], p->cmac[4], p->cmac[5]);
1084
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", buf);
1085
+ }
1086
+
1087
+ /* Print server IP */
1088
+ if (config.fieldsf & FIELD_SERVER) {
1089
+ if (offset != 0)
1090
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", d);
1091
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", ip_addr_s);
1092
+ }
1093
+
1094
+ /* Print server hardware address */
1095
+ if (config.fieldsf & FIELD_SRV_HWADDR) {
1096
+ char buf[128];
1097
+ if (offset != 0)
1098
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", d);
1099
+ snprintf(buf, 128, "%02x:%02x:%02x:%02x:%02x:%02x",
1100
+ p->smac[0], p->smac[1], p->smac[2],
1101
+ p->smac[3], p->smac[4], p->smac[5]);
1102
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", buf);
1103
+ }
1104
+
1105
+ /* Print protocol */
1106
+ if (config.fieldsf & FIELD_PROTO) {
1107
+ if (offset != 0)
1108
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", d);
1109
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", proto);
1110
+ }
1111
+
1112
+ /* Print class */
1113
+ if (config.fieldsf & FIELD_CLASS) {
1114
+ if (offset != 0)
1115
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", d);
1116
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", rr_class);
1117
+ }
1118
+
1119
+ /* Print query */
1120
+ if (config.fieldsf & FIELD_QUERY) {
1121
+ if (offset != 0)
1122
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", d);
1123
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", l->qname);
1124
+ }
1125
+
1126
+ /* Print query length */
1127
+ if (config.fieldsf & FIELD_QUERY_LEN) {
1128
+ if (offset != 0)
1129
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", d);
1130
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%zd", strlen(l->qname));
1131
+ }
1132
+
1133
+ /* Print type */
1134
+ if (config.fieldsf & FIELD_TYPE) {
1135
+ if (offset != 0)
1136
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", d);
1137
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", rr_type);
1138
+ }
1139
+
1140
+ /* Print answer */
1141
+ if (config.fieldsf & FIELD_ANSWER) {
1142
+ if (offset != 0)
1143
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", d);
1144
+ if (is_err_record)
1145
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", rr_rcode);
1146
+ else
1147
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", p->answer);
1148
+ }
1149
+
1150
+ /* Print answer length*/
1151
+ if (config.fieldsf & FIELD_ANSWER_LEN) {
1152
+ if (offset != 0)
1153
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", d);
1154
+ if (is_err_record)
1155
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%zd", strlen(rr_rcode));
1156
+ else
1157
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%zd", strlen(p->answer));
1158
+ }
1159
+
1160
+ /* Print TTL */
1161
+ if (config.fieldsf & FIELD_TTL) {
1162
+ if (offset != 0)
1163
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", d);
1164
+ if (is_err_record)
1165
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%d", PASSET_ERR_TTL);
1166
+ else
1167
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%u", p->rr->_ttl);
1168
+ }
1169
+
1170
+ /* Print count */
1171
+ if (config.fieldsf & FIELD_COUNT) {
1172
+ if (offset != 0)
1173
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", d);
1174
+ if (is_err_record)
1175
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%d", PASSET_ERR_COUNT);
1176
+ else
1177
+ offset += snprintf(output+offset, sizeof(buffer) - offset, "%"PRIu64, p->seen);
1178
+ }
1179
+
1180
+ #ifdef HAVE_JSON
1181
+ }
1182
+ #endif /* HAVE_JSON */
1183
+
1184
+ /* Print to log file */
1185
+ if (fd) {
1186
+ fprintf(fd, "%s\n", output);
1187
+ fflush(fd);
1188
+ }
1189
+
1190
+ /* Print to syslog */
1191
+ if ((is_err_record && config.output_syslog_nxd) ||
1192
+ (!is_err_record && config.output_syslog)) {
1193
+ openlog(PDNS_IDENT, LOG_NDELAY, LOG_LOCAL7);
1194
+ syslog(LOG_INFO, "%s", output);
1195
+ closelog();
1196
+ }
1197
+
1198
+ if (is_err_record) {
1199
+ l->last_print = l->last_seen;
1200
+ l->seen = 0;
1201
+ }
1202
+ else {
1203
+ p->last_print = p->last_seen;
1204
+ p->seen = 0;
1205
+ }
1206
+
1207
+ #ifdef HAVE_JSON
1208
+ if ((is_err_record && config.use_json_nxd) ||
1209
+ (!is_err_record && config.use_json)) {
1210
+ /* json_dumps allocate memory that has to be freed */
1211
+ free(output);
1212
+ }
1213
+ #endif /* HAVE_JSON */
1214
+
1215
+ free(proto);
1216
+ free(rr_class);
1217
+ free(rr_type);
1218
+ free(rr_rcode);
1219
+
1220
+ }
1221
+
1222
+ pdns_record *get_pdns_record(uint64_t dnshash, packetinfo *pi,
1223
+ unsigned char *domain_name)
1224
+ {
1225
+ pdns_record *pdnsr = dbucket[dnshash];
1226
+ pdns_record *head = pdnsr;
1227
+ uint32_t len = 0;
1228
+
1229
+ /* Search through the bucket */
1230
+ while (pdnsr != NULL)
1231
+ {
1232
+ /* If found, update and return dnsr */
1233
+ if (strcmp((const char *)domain_name,
1234
+ (const char *)pdnsr->qname) == 0) {
1235
+ /* match :) */
1236
+ memcpy( &pdnsr->last_seen, &pi->pheader->ts, sizeof( struct timeval ) );
1237
+ pdnsr->af = pi->cxt->af;
1238
+ pdnsr->cip = pi->cxt->s_ip; /* This should always be the client IP */
1239
+ pdnsr->sip = pi->cxt->d_ip; /* This should always be the server IP */
1240
+ if (pi->eth_hdr){
1241
+ memcpy(pdnsr->cmac, pi->eth_hdr->ether_dst, 6 * sizeof(u_char));
1242
+ memcpy(pdnsr->smac, pi->eth_hdr->ether_src, 6 * sizeof(u_char));
1243
+ }
1244
+ return pdnsr;
1245
+ }
1246
+ pdnsr = pdnsr->next;
1247
+ }
1248
+
1249
+ /* Else, we got a new dnsr :) */
1250
+ if (pdnsr == NULL) {
1251
+ pdnsr = (pdns_record*) calloc(1, sizeof(pdns_record));
1252
+ dlog("[*] Allocated a new dns record...\n");
1253
+ config.p_s.dns_records++;
1254
+ config.dns_records++;
1255
+ }
1256
+ if (head != NULL)
1257
+ head->prev = pdnsr;
1258
+
1259
+ /* Populate new values */
1260
+ memcpy( &pdnsr->first_seen, &pi->pheader->ts, sizeof( struct timeval ) );
1261
+ memcpy( &pdnsr->last_seen, &pi->pheader->ts, sizeof( struct timeval ) );
1262
+ pdnsr->af = pi->cxt->af;
1263
+ pdnsr->nxflag = 0;
1264
+ pdnsr->cip = pi->cxt->s_ip; /* This should always be the client IP */
1265
+ pdnsr->sip = pi->cxt->d_ip; /* This should always be the server IP */
1266
+ if (pi->eth_hdr) {
1267
+ memcpy(pdnsr->cmac, pi->eth_hdr->ether_dst, 6 * sizeof(u_char));
1268
+ memcpy(pdnsr->smac, pi->eth_hdr->ether_src, 6 * sizeof(u_char));
1269
+ }
1270
+ pdnsr->next = head;
1271
+ pdnsr->prev = NULL;
1272
+ pdnsr->passet = NULL;
1273
+ pdnsr->proto = pi->proto;
1274
+ len = strlen((char *)domain_name);
1275
+ pdnsr->qname = calloc(1, (len + 1));
1276
+ strncpy((char *)pdnsr->qname, (char *)domain_name, len);
1277
+
1278
+ dbucket[dnshash] = pdnsr;
1279
+ return pdnsr;
1280
+ }
1281
+
1282
+ void expire_dns_records()
1283
+ {
1284
+ pdns_record *pdnsr;
1285
+ uint8_t run = 0;
1286
+ time_t expire_t;
1287
+ time_t oldest;
1288
+ expire_t = (config.tstamp.tv_sec - config.dnscachetimeout);
1289
+ oldest = config.tstamp.tv_sec;
1290
+
1291
+ dlog("[D] Checking for DNS records to be expired\n");
1292
+
1293
+ while (run == 0)
1294
+ {
1295
+ uint32_t iter;
1296
+ run = 1;
1297
+ for (iter = 0; iter < DBUCKET_SIZE; iter++)
1298
+ {
1299
+ pdnsr = dbucket[iter];
1300
+ while (pdnsr != NULL)
1301
+ {
1302
+ if (pdnsr->last_seen.tv_sec < oldest)
1303
+ /* Find the LRU asset timestamp */
1304
+ oldest = pdnsr->last_seen.tv_sec;
1305
+
1306
+ if (pdnsr->last_seen.tv_sec <= expire_t) {
1307
+ /* Expire the record and all its assets */
1308
+ /* Remove from the hash */
1309
+ if (pdnsr->prev)
1310
+ pdnsr->prev->next = pdnsr->next;
1311
+ if (pdnsr->next)
1312
+ pdnsr->next->prev = pdnsr->prev;
1313
+ pdns_record *tmp = pdnsr;
1314
+ pdns_record *tmp_prev = pdnsr->prev;
1315
+
1316
+ pdnsr = pdnsr->next;
1317
+
1318
+ delete_dns_record(tmp, &dbucket[iter]);
1319
+ if (pdnsr == NULL && tmp_prev == NULL)
1320
+ dbucket[iter] = NULL;
1321
+ }
1322
+ else {
1323
+ /* Search through a domain record for assets to expire */
1324
+ expire_dns_assets(pdnsr, expire_t);
1325
+ pdnsr = pdnsr->next;
1326
+ }
1327
+ }
1328
+ }
1329
+
1330
+ update_config_mem_counters();
1331
+ /* If we are using more memory than mem_limit_max
1332
+ * decrease expire_t too the oldest seen asset at least
1333
+ */
1334
+ if (config.mem_limit_size > config.mem_limit_max) {
1335
+ expire_t = (oldest + 300); /* Oldest asset + 5 minutes */
1336
+ oldest = config.tstamp.tv_sec;
1337
+ run = 0;
1338
+ }
1339
+ }
1340
+ }
1341
+
1342
+ void update_config_mem_counters()
1343
+ {
1344
+ config.mem_limit_size = (sizeof(pdns_record) * config.dns_records) +
1345
+ (sizeof(pdns_asset) * config.dns_assets);
1346
+
1347
+ dlog("DNS and Memory stats:\n");
1348
+ dlog("DNS Records : %12u\n", config.dns_records);
1349
+ dlog("DNS Assets : %12u\n", config.dns_assets);
1350
+ dlog("Current memory size : %12lu Bytes\n", config.mem_limit_size);
1351
+ dlog("Max memory size : %12lu Bytes\n", config.mem_limit_max);
1352
+ dlog("------------------------------------------------\n");
1353
+ }
1354
+
1355
+ void expire_all_dns_records()
1356
+ {
1357
+ pdns_record *pdnsr;
1358
+
1359
+ dlog("[D] Expiring all domain records\n");
1360
+
1361
+ uint32_t iter;
1362
+ for (iter = 0; iter < DBUCKET_SIZE; iter++)
1363
+ {
1364
+ pdnsr = dbucket[iter];
1365
+ while (pdnsr != NULL)
1366
+ {
1367
+ /* Expire the record and all its assets */
1368
+ /* Remove from the hash */
1369
+ if (pdnsr->prev)
1370
+ pdnsr->prev->next = pdnsr->next;
1371
+ if (pdnsr->next)
1372
+ pdnsr->next->prev = pdnsr->prev;
1373
+ pdns_record *tmp = pdnsr;
1374
+
1375
+ pdnsr = pdnsr->next;
1376
+
1377
+ delete_dns_record(tmp, &dbucket[iter]);
1378
+ if (pdnsr == NULL)
1379
+ dbucket[iter] = NULL;
1380
+ }
1381
+ }
1382
+ }
1383
+
1384
+ void delete_dns_record(pdns_record * pdnsr, pdns_record ** bucket_ptr)
1385
+ {
1386
+ pdns_record *prev = pdnsr->prev; /* Older DNS record */
1387
+ pdns_record *next = pdnsr->next; /* Newer DNS record */
1388
+ pdns_asset *asset = pdnsr->passet;
1389
+ pdns_asset *tmp_asset;
1390
+
1391
+ dlog("[D] Deleting domain record: %s\n", pdnsr->qname);
1392
+
1393
+ /* Delete all domain assets */
1394
+ while (asset != NULL)
1395
+ {
1396
+ /* Print the asset before we expires if it
1397
+ * has been updated since it last was printed */
1398
+ if (asset->last_seen.tv_sec > asset->last_print.tv_sec)
1399
+ print_passet(pdnsr, asset, asset->rr, NULL, 0);
1400
+
1401
+ else if (asset->last_seen.tv_sec == asset->last_print.tv_sec) {
1402
+ if (asset->last_seen.tv_usec > asset->last_print.tv_usec)
1403
+ print_passet(pdnsr, asset, asset->rr, NULL, 0);
1404
+ }
1405
+ tmp_asset = asset;
1406
+ asset = asset->next;
1407
+ delete_dns_asset(&pdnsr->passet, tmp_asset);
1408
+ }
1409
+
1410
+ if (prev == NULL) {
1411
+ /* Beginning of list */
1412
+ *bucket_ptr = next;
1413
+ /* Not only entry */
1414
+ if (next)
1415
+ next->prev = NULL;
1416
+ }
1417
+ else if (next == NULL) {
1418
+ /* At end of list! */
1419
+ prev->next = NULL;
1420
+ }
1421
+ else {
1422
+ /* A node */
1423
+ prev->next = next;
1424
+ next->prev = prev;
1425
+ }
1426
+
1427
+ /* Free and set to NULL */
1428
+ free(pdnsr->qname);
1429
+ free(pdnsr);
1430
+ pdnsr = NULL;
1431
+ config.dns_records--;
1432
+ }
1433
+
1434
+ void expire_dns_assets(pdns_record *pdnsr, time_t expire_t)
1435
+ {
1436
+ dlog("[D] Checking for DNS assets to be expired\n");
1437
+
1438
+ pdns_asset *passet = pdnsr->passet;
1439
+
1440
+ while (passet != NULL)
1441
+ {
1442
+ if (passet->last_seen.tv_sec <= expire_t) {
1443
+ /* Print the asset before we expires if it
1444
+ has been updated since it last was printed */
1445
+ if (passet->last_seen.tv_sec > passet->last_print.tv_sec)
1446
+ print_passet(pdnsr, passet, passet->rr, NULL, 0);
1447
+
1448
+ else if (passet->last_seen.tv_sec == passet->last_print.tv_sec) {
1449
+ if (passet->last_seen.tv_usec > passet->last_print.tv_usec)
1450
+ print_passet(pdnsr, passet, passet->rr, NULL, 0);
1451
+ }
1452
+ /* Remove the asset from the linked list */
1453
+ if (passet->prev)
1454
+ passet->prev->next = passet->next;
1455
+ if (passet->next)
1456
+ passet->next->prev = passet->prev;
1457
+ pdns_asset *tmp = passet;
1458
+
1459
+ passet = passet->next;
1460
+
1461
+ /* Delete the asset */
1462
+ delete_dns_asset(&pdnsr->passet, tmp);
1463
+ }
1464
+ else
1465
+ passet = passet->next;
1466
+ }
1467
+ }
1468
+
1469
+ void delete_dns_asset(pdns_asset **passet_head, pdns_asset *passet)
1470
+ {
1471
+ dlog("[D] Deleting domain asset: %s\n", passet->answer);
1472
+
1473
+ if (passet == NULL)
1474
+ return;
1475
+
1476
+ pdns_asset *tmp_pa = NULL;
1477
+ pdns_asset *next_pa = NULL;
1478
+ pdns_asset *prev_pa = NULL;
1479
+
1480
+ tmp_pa = passet;
1481
+ next_pa = tmp_pa->next;
1482
+ prev_pa = tmp_pa->prev;
1483
+
1484
+ if (prev_pa == NULL) {
1485
+ /* Beginning of list */
1486
+ *passet_head = next_pa;
1487
+ /* Not only entry */
1488
+ if (next_pa)
1489
+ next_pa->prev = NULL;
1490
+ }
1491
+ else if (next_pa == NULL) {
1492
+ /* At end of list! */
1493
+ prev_pa->next = NULL;
1494
+ }
1495
+ else {
1496
+ /* A node */
1497
+ prev_pa->next = next_pa;
1498
+ next_pa->prev = prev_pa;
1499
+ }
1500
+
1501
+ free(passet->rr);
1502
+ passet->rr = NULL;
1503
+ free(passet->answer);
1504
+ passet->answer = NULL;
1505
+ free(passet);
1506
+ passet = NULL;
1507
+ config.dns_assets--;
1508
+ }
1509
+
1510
+ void update_dns_stats(packetinfo *pi, uint8_t code)
1511
+ {
1512
+ if (pi->af == AF_INET) {
1513
+ switch (pi->ip4->ip_p) {
1514
+ case IP_PROTO_TCP:
1515
+ config.p_s.ip4_dns_tcp++;
1516
+ if (code == SUCCESS)
1517
+ config.p_s.ip4_dec_tcp_ok++;
1518
+ else
1519
+ config.p_s.ip4_dec_tcp_er++;
1520
+ break;
1521
+ case IP_PROTO_UDP:
1522
+ config.p_s.ip4_dns_udp++;
1523
+ if (code == SUCCESS)
1524
+ config.p_s.ip4_dec_udp_ok++;
1525
+ else
1526
+ config.p_s.ip4_dec_udp_er++;
1527
+ break;
1528
+ default:
1529
+ break;
1530
+ }
1531
+ }
1532
+ else if (pi->af == AF_INET6) {
1533
+ switch (pi->ip6->next) {
1534
+ case IP_PROTO_TCP:
1535
+ config.p_s.ip6_dns_tcp++;
1536
+ if (code == SUCCESS)
1537
+ config.p_s.ip6_dec_tcp_ok++;
1538
+ else
1539
+ config.p_s.ip6_dec_tcp_er++;
1540
+ break;
1541
+ case IP_PROTO_UDP:
1542
+ config.p_s.ip6_dns_udp++;
1543
+ if (code == SUCCESS)
1544
+ config.p_s.ip6_dec_udp_ok++;
1545
+ else
1546
+ config.p_s.ip6_dec_udp_er++;
1547
+ break;
1548
+ default:
1549
+ break;
1550
+ }
1551
+ }
1552
+ }
1553
+
1554
+ void parse_field_flags(char *args)
1555
+ {
1556
+ int i;
1557
+ int ok = 0;
1558
+ int len = 0;
1559
+ uint8_t tmpf;
1560
+
1561
+ tmpf = config.fieldsf;
1562
+ len = strlen(args);
1563
+
1564
+ if (len == 0) {
1565
+ plog("[W] No fields are specified!\n");
1566
+ plog("[*] Continuing with default fields...\n");
1567
+ return;
1568
+ }
1569
+
1570
+ config.fieldsf = 0;
1571
+
1572
+ for (i = 0; i < len; i++)
1573
+ {
1574
+ switch(args[i]) {
1575
+ case 'H': /* Timestamp(YMDHMS) */
1576
+ config.fieldsf |= FIELD_TIMESTAMP_YMDHMS;
1577
+ dlog("[D] Enabling field: FIELD_TIMESTAMP_YMDHMS\n");
1578
+ ok++;
1579
+ break;
1580
+ case 'S': /* Timestamp(s) */
1581
+ config.fieldsf |= FIELD_TIMESTAMP_S;
1582
+ dlog("[D] Enabling field: FIELD_TIMESTAMP_S\n");
1583
+ ok++;
1584
+ break;
1585
+ case 'M': /* Timestamp(ms) */
1586
+ config.fieldsf |= FIELD_TIMESTAMP_MS;
1587
+ dlog("[D] Enabling field: FIELD_TIMESTAMP_MS\n");
1588
+ ok++;
1589
+ break;
1590
+ case 'c': /* Client */
1591
+ config.fieldsf |= FIELD_CLIENT;
1592
+ dlog("[D] Enabling field: FIELD_CLIENT\n");
1593
+ ok++;
1594
+ break;
1595
+ case 's': /* Server */
1596
+ config.fieldsf |= FIELD_SERVER;
1597
+ dlog("[D] Enabling field: FIELD_SERVER\n");
1598
+ ok++;
1599
+ break;
1600
+ case 'C': /* Class */
1601
+ config.fieldsf |= FIELD_CLASS;
1602
+ dlog("[D] Enabling field: FIELD_CLASS\n");
1603
+ ok++;
1604
+ break;
1605
+ case 'Q': /* Query */
1606
+ config.fieldsf |= FIELD_QUERY;
1607
+ dlog("[D] Enabling field: FIELD_QUERY\n");
1608
+ ok++;
1609
+ break;
1610
+ case 'L': /* Query Length */
1611
+ config.fieldsf |= FIELD_QUERY_LEN;
1612
+ dlog("[D] Enabling field: FIELD_QUERY_LEN\n");
1613
+ ok++;
1614
+ break;
1615
+ case 'T': /* Type */
1616
+ config.fieldsf |= FIELD_TYPE;
1617
+ dlog("[D] Enabling field: FIELD_TYPE\n");
1618
+ ok++;
1619
+ break;
1620
+ case 'A': /* Answer */
1621
+ config.fieldsf |= FIELD_ANSWER;
1622
+ dlog("[D] Enabling field: FIELD_ANSWER\n");
1623
+ ok++;
1624
+ break;
1625
+ case 'l': /* Answer Lenght */
1626
+ config.fieldsf |= FIELD_ANSWER_LEN;
1627
+ dlog("[D] Enabling field: FIELD_ANSWER_LEN\n");
1628
+ ok++;
1629
+ break;
1630
+ case 't': /* TTL */
1631
+ config.fieldsf |= FIELD_TTL;
1632
+ dlog("[D] Enabling field: FIELD_TTL\n");
1633
+ ok++;
1634
+ break;
1635
+ case 'p': /* Protocol */
1636
+ config.fieldsf |= FIELD_PROTO;
1637
+ dlog("[D] Enabling field: FIELD_PROTO\n");
1638
+ ok++;
1639
+ break;
1640
+ case 'n': /* Count */
1641
+ config.fieldsf |= FIELD_COUNT;
1642
+ dlog("[D] Enabling field: FIELD_COUNT\n");
1643
+ ok++;
1644
+ break;
1645
+ case 'h': /* Hostname */
1646
+ config.fieldsf |= FIELD_HOSTNAME;
1647
+ dlog("[D] Enabling field: FIELD_HOSTNAME\n");
1648
+ ok++;
1649
+ break;
1650
+ case 'w': /* Client hw address */
1651
+ config.fieldsf |= FIELD_CLT_HWADDR;
1652
+ dlog("[D] Enabling field: FIELD_CLT_HWADDR\n");
1653
+ ok++;
1654
+ break;
1655
+ case 'W': /* Server hw address */
1656
+ config.fieldsf |= FIELD_SRV_HWADDR;
1657
+ dlog("[D] Enabling field: FIELD_SRV_HWADDR\n");
1658
+ ok++;
1659
+ break;
1660
+ default:
1661
+ plog("[*] Unknown field '%c'\n",args[i]);
1662
+ break;
1663
+ }
1664
+ }
1665
+
1666
+ if (ok == 0) {
1667
+ plog("[W] No valid fields parsed, continuing with defaults.\n");
1668
+ config.fieldsf = tmpf;
1669
+ }
1670
+ }
1671
+
1672
+ void parse_dns_flags(char *args)
1673
+ {
1674
+ int i;
1675
+ int ok = 0;
1676
+ int len = 0;
1677
+ uint8_t tmpf;
1678
+
1679
+ tmpf = config.dnsf;
1680
+ len = strlen(args);
1681
+
1682
+ if (len == 0) {
1683
+ plog("[W] No flags are specified!\n");
1684
+ plog("[*] Continuing with default flags...\n");
1685
+ return;
1686
+ }
1687
+
1688
+ config.dnsf = 0;
1689
+ config.dnsfe = 0;
1690
+
1691
+ for (i = 0; i < len; i++){
1692
+ switch(args[i]) {
1693
+ case 'I': /* HINFO */
1694
+ config.dnsf |= DNS_CHK_HINFO;
1695
+ dlog("[D] Enabling flag: DNS_CHK_HINFO\n");
1696
+ ok++;
1697
+ break;
1698
+ case 'H': /* SSHFP */
1699
+ config.dnsf |= DNS_CHK_SSHFP;
1700
+ dlog("[D] Enabling flag: DNS_CHK_SSHFP\n");
1701
+ ok++;
1702
+ break;
1703
+ case 'L': /* LOC */
1704
+ config.dnsf |= DNS_CHK_LOC;
1705
+ dlog("[D] Enabling flag: DNS_CHK_LOC\n");
1706
+ ok++;
1707
+ break;
1708
+ case 'd': /* DNSSEC */
1709
+ config.dnsf |= DNS_CHK_DNSSEC;
1710
+ dlog("[D] Enabling flag: DNS_CHK_DNSSEC\n");
1711
+ ok++;
1712
+ break;
1713
+ case '4': /* A */
1714
+ config.dnsf |= DNS_CHK_A;
1715
+ dlog("[D] Enabling flag: DNS_CHK_A\n");
1716
+ ok++;
1717
+ break;
1718
+ case '6': /* AAAA */
1719
+ config.dnsf |= DNS_CHK_AAAA;
1720
+ dlog("[D] Enabling flag: DNS_CHK_AAAA\n");
1721
+ ok++;
1722
+ break;
1723
+ case 'P': /* PTR */
1724
+ config.dnsf |= DNS_CHK_PTR;
1725
+ dlog("[D] Enabling flag: DNS_CHK_PTR\n");
1726
+ ok++;
1727
+ break;
1728
+ case 'C': /* CNAME */
1729
+ config.dnsf |= DNS_CHK_CNAME;
1730
+ dlog("[D] Enabling flag: DNS_CHK_CNAME\n");
1731
+ ok++;
1732
+ break;
1733
+ case 'D': /* DNAME */
1734
+ config.dnsf |= DNS_CHK_DNAME;
1735
+ dlog("[D] Enabling flag: DNS_CHK_DNAME\n");
1736
+ ok++;
1737
+ break;
1738
+ case 'N': /* NAPTR */
1739
+ config.dnsf |= DNS_CHK_NAPTR;
1740
+ dlog("[D] Enabling flag: DNS_CHK_NAPTR\n");
1741
+ ok++;
1742
+ break;
1743
+ case 'R': /* RP */
1744
+ config.dnsf |= DNS_CHK_RP;
1745
+ dlog("[D] Enabling flag: DNS_CHK_RP\n");
1746
+ ok++;
1747
+ break;
1748
+ case 'S': /* SRV */
1749
+ config.dnsf |= DNS_CHK_SRV;
1750
+ dlog("[D] Enabling flag: DNS_CHK_SRV\n");
1751
+ ok++;
1752
+ break;
1753
+ case 'F': /* SPF */
1754
+ config.dnsf |= DNS_CHK_SPF;
1755
+ dlog("[D] Enabling flag: DNS_CHK_SPF\n");
1756
+ ok++;
1757
+ case 'T': /* TXT */
1758
+ config.dnsf |= DNS_CHK_TXT;
1759
+ dlog("[D] Enabling flag: DNS_CHK_TXT\n");
1760
+ ok++;
1761
+ break;
1762
+ case 'O': /* SOA */
1763
+ config.dnsf |= DNS_CHK_SOA;
1764
+ dlog("[D] Enabling flag: DNS_CHK_SOA\n");
1765
+ ok++;
1766
+ break;
1767
+ case 'M': /* MX */
1768
+ config.dnsf |= DNS_CHK_MX;
1769
+ dlog("[D] Enabling flag: DNS_CHK_MX\n");
1770
+ ok++;
1771
+ break;
1772
+ case 'n': /* NS */
1773
+ config.dnsf |= DNS_CHK_NS;
1774
+ dlog("[D] Enabling flag: DNS_CHK_NS\n");
1775
+ ok++;
1776
+ break;
1777
+ case 'f': /* FORMERR */
1778
+ config.dnsfe |= DNS_SE_CHK_FORMERR;
1779
+ dlog("[D] Enabling flag: DNS_SE_CHK_FORMERR\n");
1780
+ ok++;
1781
+ break;
1782
+ case 's': /* SERVFAIL */
1783
+ config.dnsfe |= DNS_SE_CHK_SERVFAIL;
1784
+ dlog("[D] Enabling flag: DNS_SE_CHK_SERVFAIL\n");
1785
+ ok++;
1786
+ break;
1787
+ case 'x': /* NXDOMAIN */
1788
+ config.dnsfe |= DNS_SE_CHK_NXDOMAIN;
1789
+ dlog("[D] Enabling flag: DNS_SE_CHK_NXDOMAIN\n");
1790
+ ok++;
1791
+ break;
1792
+
1793
+ case 'o': /* NOTIMPL */
1794
+ config.dnsfe |= DNS_SE_CHK_NOTIMPL;
1795
+ dlog("[D] Enabling flag: DNS_SE_CHK_NOTIMPL\n");
1796
+ ok++;
1797
+ break;
1798
+ case 'r': /* REFUSED */
1799
+ config.dnsfe |= DNS_SE_CHK_REFUSED;
1800
+ dlog("[D] Enabling flag: DNS_SE_CHK_REFUSED\n");
1801
+ ok++;
1802
+ break;
1803
+ case 'y': /* YXDOMAIN */
1804
+ config.dnsfe |= DNS_SE_CHK_YXDOMAIN;
1805
+ dlog("[D] Enabling flag: DNS_SE_CHK_YXDOMAIN\n");
1806
+ ok++;
1807
+ break;
1808
+ case 'e': /* YXRRSET */
1809
+ config.dnsfe |= DNS_SE_CHK_YXRRSET;
1810
+ dlog("[D] Enabling flag: DNS_SE_CHK_YXRRSET\n");
1811
+ ok++;
1812
+ break;
1813
+ case 't': /* NXRRSET */
1814
+ config.dnsfe |= DNS_SE_CHK_NXRRSET;
1815
+ dlog("[D] Enabling flag: DNS_SE_CHK_NXRRSET\n");
1816
+ ok++;
1817
+ break;
1818
+ case 'a': /* NOTAUTH */
1819
+ config.dnsfe |= DNS_SE_CHK_NOTAUTH;
1820
+ dlog("[D] Enabling flag: DNS_SE_CHK_NOTAUTH\n");
1821
+ ok++;
1822
+ break;
1823
+ case 'z': /* NOTZONE */
1824
+ config.dnsfe |= DNS_SE_CHK_NOTZONE;
1825
+ dlog("[D] Enabling flag: DNS_SE_CHK_NOTZONE\n");
1826
+ ok++;
1827
+ break;
1828
+ case '\0':
1829
+ dlog("[W] Bad DNS flag - ending flag checks!\n");
1830
+ ok = 0;
1831
+ continue;
1832
+ default:
1833
+ plog("[*] Unknown DNS flag '%c'\n",args[i]);
1834
+ break;
1835
+ }
1836
+ }
1837
+
1838
+ if (ok == 0) {
1839
+ plog("[W] No valid flags parsed, continuing with defaults.\n");
1840
+ config.dnsf = tmpf;
1841
+ }
1842
+ }
1843
+
1844
+ uint16_t pdns_chk_dnsfe(uint16_t rcode)
1845
+ {
1846
+ uint16_t retcode = 0x0000;
1847
+
1848
+ switch (rcode) {
1849
+ case 1:
1850
+ retcode = DNS_SE_CHK_FORMERR;
1851
+ break;
1852
+ case 2:
1853
+ retcode = DNS_SE_CHK_SERVFAIL;
1854
+ break;
1855
+ case 3:
1856
+ retcode = DNS_SE_CHK_NXDOMAIN;
1857
+ break;
1858
+ case 4:
1859
+ retcode = DNS_SE_CHK_NOTIMPL;
1860
+ break;
1861
+ case 5:
1862
+ retcode = DNS_SE_CHK_REFUSED;
1863
+ break;
1864
+ case 6:
1865
+ retcode = DNS_SE_CHK_YXDOMAIN;
1866
+ break;
1867
+ case 7:
1868
+ retcode = DNS_SE_CHK_YXRRSET;
1869
+ break;
1870
+ case 8:
1871
+ retcode = DNS_SE_CHK_NXRRSET;
1872
+ break;
1873
+ case 9:
1874
+ retcode = DNS_SE_CHK_NOTAUTH;
1875
+ break;
1876
+ case 10:
1877
+ retcode = DNS_SE_CHK_NOTZONE;
1878
+ break;
1879
+ default:
1880
+ retcode = 0x0000; /* UNKNOWN-ERROR */
1881
+ break;
1882
+ }
1883
+
1884
+ return retcode;
1885
+ }
1886
+
dns_tunneling/passivedns-master/src/dns.h ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ ** This file is a part of PassiveDNS.
3
+ **
4
+ ** Copyright (C) 2010-2013, Edward Fjellskål <edwardfjellskaal@gmail.com>
5
+ **
6
+ ** This program is free software; you can redistribute it and/or modify
7
+ ** it under the terms of the GNU General Public License as published by
8
+ ** the Free Software Foundation; either version 2 of the License, or
9
+ ** (at your option) any later version.
10
+ **
11
+ ** This program is distributed in the hope that it will be useful,
12
+ ** but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ ** GNU General Public License for more details.
15
+ **
16
+ ** You should have received a copy of the GNU General Public License
17
+ ** along with this program; if not, write to the Free Software
18
+ ** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19
+ **
20
+ */
21
+
22
+ #ifndef DNS_H
23
+ #define DNS_H
24
+
25
+ #include <ldns/ldns.h>
26
+
27
+ /* Default flags for types to handle */
28
+ #define DNS_CHK_AAAA 0x00000001
29
+ #define DNS_CHK_A 0x00000002
30
+ #define DNS_CHK_PTR 0x00000004
31
+ #define DNS_CHK_CNAME 0x00000008
32
+ #define DNS_CHK_DNAME 0x00000010
33
+ #define DNS_CHK_NAPTR 0x00000020
34
+ #define DNS_CHK_RP 0x00000040
35
+ #define DNS_CHK_SRV 0x00000080
36
+ #define DNS_CHK_TXT 0x00000100
37
+ #define DNS_CHK_SOA 0x00000200
38
+ #define DNS_CHK_MX 0x00000400
39
+ #define DNS_CHK_NS 0x00000800
40
+ #define DNS_CHK_DNSSEC 0x00001000
41
+ #define DNS_CHK_LOC 0x00002000
42
+ #define DNS_CHK_SPF 0x00004000
43
+ #define DNS_CHK_SSHFP 0x00008000
44
+ #define DNS_CHK_HINFO 0x00010000
45
+ #define DNS_CHK_ALL 0x80000000
46
+ /* Default flags for Server Errors to handle */
47
+ #define DNS_SE_CHK_FORMERR 0x0001
48
+ #define DNS_SE_CHK_SERVFAIL 0x0002
49
+ #define DNS_SE_CHK_NXDOMAIN 0x0004
50
+ #define DNS_SE_CHK_NOTIMPL 0x0008
51
+ #define DNS_SE_CHK_REFUSED 0x0010
52
+ #define DNS_SE_CHK_YXDOMAIN 0x0020
53
+ #define DNS_SE_CHK_YXRRSET 0x0040
54
+ #define DNS_SE_CHK_NXRRSET 0x0080
55
+ #define DNS_SE_CHK_NOTAUTH 0x0100
56
+ #define DNS_SE_CHK_NOTZONE 0x0200
57
+ #define DNS_SE_CHK_ALL 0x8000
58
+
59
+ /* Flag for indicating an NXDOMAIN */
60
+ #define DNS_NXDOMAIN 0x01
61
+
62
+ /* Flags for which fields to print */
63
+ #define FIELD_TIMESTAMP_S 0x00001
64
+ #define FIELD_TIMESTAMP_MS 0x00002
65
+ #define FIELD_CLIENT 0x00004
66
+ #define FIELD_SERVER 0x00008
67
+ #define FIELD_CLASS 0x00010
68
+ #define FIELD_QUERY 0x00020
69
+ #define FIELD_TYPE 0x00040
70
+ #define FIELD_ANSWER 0x00080
71
+ #define FIELD_TTL 0x00100
72
+ #define FIELD_COUNT 0x00200
73
+ #define FIELD_TIMESTAMP_YMDHMS 0x00400
74
+ #define FIELD_PROTO 0x00800
75
+ #define FIELD_HOSTNAME 0x01000
76
+ #define FIELD_QUERY_LEN 0x02000
77
+ #define FIELD_ANSWER_LEN 0x04000
78
+ #define FIELD_CLT_HWADDR 0x08000
79
+ #define FIELD_SRV_HWADDR 0x10000
80
+
81
+ /* Static values for print_passet() */
82
+ #define PASSET_ERR_TTL 0
83
+ #define PASSET_ERR_COUNT 1
84
+
85
+ /* Syslog */
86
+ #define PDNS_IDENT "passivedns"
87
+
88
+ /* JSON fields used when printing PDNS */
89
+ #define JSON_TIMESTAMP "timestamp"
90
+ #define JSON_TIMESTAMP_S "timestamp_s"
91
+ #define JSON_TIMESTAMP_MS "timestamp_ms"
92
+ #define JSON_CLIENT "client"
93
+ #define JSON_SERVER "server"
94
+ #define JSON_PROTO "proto"
95
+ #define JSON_CLASS "class"
96
+ #define JSON_QUERY "query"
97
+ #define JSON_QUERY_LEN "query_len"
98
+ #define JSON_TYPE "type"
99
+ #define JSON_ANSWER "answer"
100
+ #define JSON_ANSWER_LEN "answer_len"
101
+ #define JSON_TTL "ttl"
102
+ #define JSON_COUNT "count"
103
+ #define JSON_HOSTNAME "hostname"
104
+
105
+ /* To avoid spaming the logfile with duplicate dns info
106
+ * we only print a dns record one time each 24H. This way
107
+ * you will get a last seen timestamp update once a day
108
+ * at least. If the record changes, it will be classified
109
+ * as a new record, and printent. If a record expires and
110
+ * it has been updated since last_print time, it will be
111
+ * printed again.
112
+ */
113
+ #define DNSPRINTTIME 86400 /* 24H = 86400 sec */
114
+
115
+ /* How long we should hold a dns record in our internal
116
+ * cache. It should preferably not be less than DNSPRINTTIME,
117
+ * as that will make it possible to get more than one instance
118
+ * of the record each day in the logfile. That said, setting
119
+ * DNSCACHETIMEOUT to DNSPRINTTIME/2 etc, might help memory
120
+ * usage if that is a concern AND you probably will get a better
121
+ * granularity on the DNS time stamps in the log file.
122
+ * My recomendations are DNSPRINTTIME == 24h and
123
+ * DNSCACHETIMEOUT == 12h.
124
+ */
125
+ #define DNSCACHETIMEOUT 43200 /* 12h=43200sec */
126
+
127
+ /* HASH:
128
+ * [DOMAIN_HASH_BUCKET]_
129
+ * |__[Q-TYPE_BUCKET]_<--- PTR,MX,A...
130
+ * |__[RESPONCE-NAME] <--- FOR PTR is the IPv4/IPv6
131
+ */
132
+
133
+ typedef struct _pdns_asset {
134
+ struct timeval first_seen; /* First seen (unix timestamp) */
135
+ struct timeval last_seen; /* Last seen (unix timestamp) */
136
+ struct timeval last_print; /* Last time asset was printet */
137
+ struct ldns_struct_rr *rr; /* PTR,MX,TXT,A,AAAA... */
138
+ uint64_t seen; /* Number of times seen */
139
+ unsigned char *answer; /* Answer, like 8.8.8.8 or 2001:67c:21e0::16 */
140
+ uint32_t af; /* IP version (4/6) AF_INET */
141
+ struct in6_addr sip; /* DNS Server IP (v4/6) */
142
+ u_char smac[6]; /* DNS Server MAC address */
143
+ struct in6_addr cip; /* DNS Client IP (v4/6) */
144
+ u_char cmac[6]; /* DNS Client MAC address */
145
+ struct _pdns_asset *next; /* Next dns asset */
146
+ struct _pdns_asset *prev; /* Prev dns asset */
147
+ } pdns_asset;
148
+
149
+ typedef struct _pdns_record {
150
+ struct timeval first_seen; /* First seen (unix timestamp) */
151
+ struct timeval last_seen; /* Last seen (unix timestamp) */
152
+ struct timeval last_print; /* Last time record(NXD) was printet */
153
+ uint64_t seen; /* Number of times seen */
154
+ unsigned char *qname; /* Query name (gamelinux.org) */
155
+ uint8_t nxflag; /* Flag to indicate if this is a NXDOMAIN */
156
+ uint32_t af; /* IP version (4/6) AF_INET */
157
+ struct in6_addr sip; /* DNS Server IP (v4/6) */
158
+ u_char smac[6]; /* DNS Server MAC address */
159
+ struct in6_addr cip; /* DNS Client IP (v4/6) */
160
+ u_char cmac[6]; /* DNS Client MAC address */
161
+ uint8_t proto; /* Protocol */
162
+ pdns_asset *passet; /* Head of dns assets */
163
+ struct _pdns_record *next; /* Next dns record */
164
+ struct _pdns_record *prev; /* Prev dns record */
165
+ } pdns_record;
166
+
167
+ /* Declare */
168
+ int process_dns_answer (packetinfo *pi, ldns_pkt *decoded_dns);
169
+ int cache_dns_objects (packetinfo *pi, ldns_rdf *rdf_data, ldns_buffer *buff, ldns_pkt *dns_pkt);
170
+ pdns_record *get_pdns_record (uint64_t dnshash, packetinfo *pi, unsigned char *domain_name);
171
+ const char *u_ntop (const struct in6_addr ip_addr, int af, char *dest);
172
+ void dns_parser (packetinfo *pi);
173
+ void update_pdns_record_asset (packetinfo *pi, pdns_record *pr, ldns_rr *rr, unsigned char *rdomain_name);
174
+ void print_passet (pdns_record *l, pdns_asset *p, ldns_rr *rr, ldns_rdf *lname, uint16_t rcode);
175
+ void expire_dns_assets (pdns_record *pdnsr, time_t expire_t);
176
+ void expire_dns_records();
177
+ void expire_all_dns_records();
178
+ void delete_dns_record (pdns_record *pdnsr, pdns_record **bucket_ptr);
179
+ void delete_dns_asset (pdns_asset **passet_head, pdns_asset *passet);
180
+ void update_config_mem_counters();
181
+ void parse_field_flags (char *args);
182
+ void parse_dns_flags (char *args);
183
+ void update_dns_stats(packetinfo *pi, uint8_t code);
184
+ uint16_t pdns_chk_dnsfe(uint16_t rcode);
185
+
186
+ #endif /* DNS_H */
187
+
dns_tunneling/passivedns-master/src/passivedns.c ADDED
@@ -0,0 +1,1603 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ ** This file is a part of PassiveDNS.
3
+ **
4
+ ** Copyright (C) 2010-2013, Edward Fjellskål <edwardfjellskaal@gmail.com>
5
+ **
6
+ ** This program is free software; you can redistribute it and/or modify
7
+ ** it under the terms of the GNU General Public License as published by
8
+ ** the Free Software Foundation; either version 2 of the License, or
9
+ ** (at your option) any later version.
10
+ **
11
+ ** This program is distributed in the hope that it will be useful,
12
+ ** but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ ** GNU General Public License for more details.
15
+ **
16
+ ** You should have received a copy of the GNU General Public License
17
+ ** along with this program; if not, write to the Free Software
18
+ ** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19
+ **
20
+ */
21
+
22
+ /* I N C L U D E S **********************************************************/
23
+ #include "config.h"
24
+ #include <stdio.h>
25
+ #include <stdlib.h>
26
+ #include <libgen.h>
27
+ #include <string.h>
28
+ #include <arpa/inet.h>
29
+ #include <netinet/in.h>
30
+ #include <signal.h>
31
+ #include <pcap.h>
32
+ #include <getopt.h>
33
+ #include <time.h>
34
+ #include <sys/types.h>
35
+ #include <grp.h>
36
+ #include <pwd.h>
37
+ #include <unistd.h>
38
+ #include <sys/stat.h>
39
+ #include <sys/types.h>
40
+ #include <syslog.h>
41
+ #include <fcntl.h>
42
+ #include <errno.h>
43
+ #include <ctype.h>
44
+ #include <limits.h>
45
+ #include "passivedns.h"
46
+ #include "dns.h"
47
+
48
+ #ifdef HAVE_JSON
49
+ #include <jansson.h>
50
+ #endif /* HAVE_JSON */
51
+
52
+ #ifdef HAVE_PFRING
53
+ #include <pfring.h>
54
+ #endif /* HAVE_PFRING */
55
+
56
+ #ifndef CONFDIR
57
+ #define CONFDIR "/etc/passivedns/"
58
+ #endif
59
+
60
+ /* G L O B A L S *** (or candidates for refactoring, as we say)***********/
61
+ globalconfig config;
62
+ connection *bucket[BUCKET_SIZE];
63
+ static volatile sig_atomic_t signal_reopen_log_files = 0;
64
+
65
+ /* I N T E R N A L P R O T O T Y P E S ***********************************/
66
+ static void usage();
67
+ static void show_version();
68
+ void check_vlan (packetinfo *pi);
69
+ void prepare_null (packetinfo *pi);
70
+ void prepare_raw (packetinfo *pi);
71
+ void prepare_sll (packetinfo *pi);
72
+ void prepare_eth (packetinfo *pi);
73
+ void prepare_ip4 (packetinfo *pi);
74
+ void prepare_ip4ip (packetinfo *pi);
75
+ void prepare_ip6 (packetinfo *pi);
76
+ void prepare_ip6ip (packetinfo *pi);
77
+ void prepare_udp (packetinfo *pi);
78
+ void prepare_tcp (packetinfo *pi);
79
+ void parse_eth (packetinfo *pi);
80
+ void parse_ip4 (packetinfo *pi);
81
+ void parse_ip6 (packetinfo *pi);
82
+ void parse_udp (packetinfo *pi);
83
+ void parse_tcp (packetinfo *pi);
84
+ const char *u_ntop_src(packetinfo *pi, char *dest);
85
+ void set_pkt_end_ptr (packetinfo *pi);
86
+ void check_interrupt();
87
+ void end_sessions();
88
+ void set_end_sessions();
89
+ void set_end_dns_records();
90
+ void cxt_init();
91
+ int connection_tracking(packetinfo *pi);
92
+ connection *cxt_new(packetinfo *pi);
93
+ void del_connection(connection *, connection **);
94
+ void print_pdns_stats();
95
+ void free_config();
96
+ void reopen_log_files();
97
+ void game_over ();
98
+ void got_packet(u_char *useless, const struct pcap_pkthdr *pheader,
99
+ const u_char *packet);
100
+ #ifdef HAVE_PFRING
101
+ void pfring_got_packet(const struct pfring_pkthdr *pfheader,
102
+ const u_char *packet, const u_char *useless);
103
+ #endif /* HAVE_PFRING */
104
+
105
+ /* F U N C T I O N S ********************************************************/
106
+
107
+ #ifdef HAVE_PFRING
108
+
109
+ void pfring_got_packet(const struct pfring_pkthdr *pfheader,
110
+ const u_char *packet, const u_char *useless)
111
+ {
112
+ /* pcap_pkthdr and pfring_pkthdr are identical to each other*/
113
+ struct pcap_pkthdr *pheader = (struct pcap_pkthdr *)pfheader;
114
+
115
+ /* Set timestamp if it's not set */
116
+ if (pheader->ts.tv_sec == 0)
117
+ pheader->ts.tv_sec = time(NULL);
118
+
119
+ /* pfring_loop orders the arguments differently than pcap_loop */
120
+ got_packet((u_char *)useless, (const struct pcap_pkthdr *)pheader, packet);
121
+ }
122
+
123
+ #endif /* HAVE_PFRING */
124
+
125
+ void got_packet(u_char *useless, const struct pcap_pkthdr *pheader,
126
+ const u_char *packet)
127
+ {
128
+ config.p_s.got_packets++;
129
+ packetinfo pstruct = {0};
130
+ packetinfo *pi = &pstruct;
131
+ pi->packet = packet;
132
+ pi->pheader = pheader;
133
+ set_pkt_end_ptr (pi);
134
+ memcpy( &config.tstamp, &pi->pheader->ts, sizeof( struct timeval ) ); /* Global */
135
+
136
+ if (signal_reopen_log_files)
137
+ reopen_log_files();
138
+
139
+ if (config.intr_flag != 0) {
140
+ check_interrupt();
141
+ }
142
+ config.inpacket = 1;
143
+
144
+ switch (config.linktype) {
145
+ case DLT_NULL:
146
+ prepare_null(pi);
147
+ break;
148
+ case DLT_RAW:
149
+ prepare_raw(pi);
150
+ break;
151
+ #ifdef DLT_LINUX_SLL
152
+ case DLT_LINUX_SLL:
153
+ prepare_sll(pi);
154
+ break;
155
+ #endif
156
+ default:
157
+ prepare_eth(pi);
158
+ check_vlan(pi);
159
+ break;
160
+ }
161
+
162
+ switch (pi->eth_type) {
163
+ case ETHERNET_TYPE_IP:
164
+ prepare_ip4(pi);
165
+ parse_ip4(pi);
166
+ break;
167
+ case ETHERNET_TYPE_IPV6:
168
+ prepare_ip6(pi);
169
+ parse_ip6(pi);
170
+ break;
171
+ default:
172
+ config.p_s.otherl_recv++;
173
+ //vlog(0x3, "[*] ETHERNET TYPE : %x\n",pi->eth_hdr->eth_ip_type);
174
+ break;
175
+ }
176
+
177
+ config.inpacket = 0;
178
+ }
179
+
180
+ void prepare_null(packetinfo *pi)
181
+ {
182
+ pi->eth_hlen = LOOPBACK_HDR_LEN;
183
+ if ((u_int32_t)*pi->packet == AF_INET) {
184
+ pi->eth_type = ETHERNET_TYPE_IP;
185
+ } else {
186
+ pi->eth_type = ETHERNET_TYPE_IPV6;
187
+ }
188
+ }
189
+
190
+ void prepare_raw(packetinfo *pi)
191
+ {
192
+ pi->eth_hlen = 0;
193
+ if (IP_V((ip4_header *)pi->packet) == 4)
194
+ pi->eth_type = ETHERNET_TYPE_IP;
195
+ else
196
+ pi->eth_type = ETHERNET_TYPE_IPV6;
197
+ }
198
+
199
+ void prepare_sll(packetinfo *pi)
200
+ {
201
+ pi->eth_hlen = SLL_HDR_LEN;
202
+
203
+ if (IP_V((ip4_header *)(pi->packet + SLL_HDR_LEN)) == 4)
204
+ pi->eth_type = ETHERNET_TYPE_IP;
205
+ else
206
+ pi->eth_type = ETHERNET_TYPE_IPV6;
207
+ }
208
+
209
+ void prepare_eth(packetinfo *pi)
210
+ {
211
+ if (pi->packet + ETHERNET_HEADER_LEN > pi->end_ptr)
212
+ return;
213
+
214
+ config.p_s.eth_recv++;
215
+ pi->eth_hdr = (ether_header *) (pi->packet);
216
+ pi->eth_type = ntohs(pi->eth_hdr->eth_ip_type);
217
+ pi->eth_hlen = ETHERNET_HEADER_LEN;
218
+ }
219
+
220
+ void check_vlan(packetinfo *pi)
221
+ {
222
+ if (pi->eth_type == ETHERNET_TYPE_8021Q) {
223
+ vlog(0x3, "[*] ETHERNET TYPE 8021Q\n");
224
+ config.p_s.vlan_recv++;
225
+ pi->vlan = pi->eth_hdr->eth_8_vid;
226
+ pi->eth_type = ntohs(pi->eth_hdr->eth_8_ip_type);
227
+ pi->eth_hlen += 4;
228
+ if ( pi->eth_type == ETHERNET_TYPE_8021Q ) {
229
+ vlog(0x3, "[*] ETHERNET TYPE 8021Q in 8021Q\n");
230
+ pi->eth_type = ntohs(pi->eth_hdr->eth_82_ip_type);
231
+ pi->eth_hlen += 4;
232
+ pi->vlan = pi->eth_hdr->eth_82_vid;
233
+ }
234
+ }
235
+ else if (pi->eth_type == (ETHERNET_TYPE_802Q1MT | ETHERNET_TYPE_802Q1MT2 |
236
+ ETHERNET_TYPE_802Q1MT3 | ETHERNET_TYPE_8021AD)) {
237
+ vlog(0x3, "[*] ETHERNET TYPE 802Q1MT\n");
238
+ pi->mvlan = pi->eth_hdr->eth_82_mvid;
239
+ pi->eth_type = ntohs(pi->eth_hdr->eth_82_ip_type);
240
+ pi->eth_hlen += 8;
241
+ }
242
+ }
243
+
244
+ void prepare_ip4(packetinfo *pi)
245
+ {
246
+ config.p_s.ip4_recv++;
247
+ pi->af = AF_INET;
248
+ pi->ip4 = (ip4_header *) (pi->packet + pi->eth_hlen);
249
+ pi->packet_bytes = (pi->ip4->ip_len - (IP_HL(pi->ip4) * 4));
250
+ }
251
+
252
+ void parse_ip4(packetinfo *pi)
253
+ {
254
+ /* Paranoia */
255
+ if (((pi->packet + pi->eth_hlen) + (IP_HL(pi->ip4) * 4)) > pi->end_ptr) {
256
+ dlog("[D] Refusing to parse IPv4 packet: IPv4-hdr passed end_ptr\n");
257
+ return;
258
+ }
259
+
260
+ switch (pi->ip4->ip_p) {
261
+ case IP_PROTO_TCP:
262
+ prepare_tcp(pi);
263
+ parse_tcp(pi);
264
+ break;
265
+ case IP_PROTO_UDP:
266
+ prepare_udp(pi);
267
+ parse_udp(pi);
268
+ break;
269
+ case IP_PROTO_IP4:
270
+ prepare_ip4ip(pi);
271
+ break;
272
+ case IP_PROTO_IP6:
273
+ prepare_ip4ip(pi);
274
+ break;
275
+ default:
276
+ break;
277
+ }
278
+ }
279
+
280
+ void prepare_ip6ip(packetinfo *pi)
281
+ {
282
+ packetinfo pipi;
283
+ memset(&pipi, 0, sizeof(packetinfo));
284
+ config.p_s.ip6ip_recv++;
285
+ pipi.pheader = pi->pheader;
286
+ pipi.packet = (pi->packet + pi->eth_hlen + IP6_HEADER_LEN);
287
+ pipi.end_ptr = pi->end_ptr;
288
+
289
+ if (pi->ip6->next == IP_PROTO_IP4) {
290
+ prepare_ip4(&pipi);
291
+ parse_ip4(&pipi);
292
+ }
293
+ else {
294
+ prepare_ip6(&pipi);
295
+ parse_ip6(&pipi);
296
+ }
297
+ }
298
+
299
+ void prepare_ip4ip(packetinfo *pi)
300
+ {
301
+ packetinfo pipi;
302
+ memset(&pipi, 0, sizeof(packetinfo));
303
+ config.p_s.ip4ip_recv++;
304
+ pipi.pheader = pi->pheader;
305
+ pipi.packet = (pi->packet + pi->eth_hlen + (IP_HL(pi->ip4) * 4));
306
+ pipi.end_ptr = pi->end_ptr;
307
+
308
+ if (pi->ip4->ip_p == IP_PROTO_IP4) {
309
+ prepare_ip4(&pipi);
310
+ parse_ip4(&pipi);
311
+ }
312
+ else {
313
+ prepare_ip6(&pipi);
314
+ parse_ip6(&pipi);
315
+ }
316
+ }
317
+
318
+ void prepare_ip6(packetinfo *pi)
319
+ {
320
+ config.p_s.ip6_recv++;
321
+ pi->af = AF_INET6;
322
+ pi->ip6 = (ip6_header *) (pi->packet + pi->eth_hlen);
323
+ pi->packet_bytes = pi->ip6->len;
324
+ }
325
+
326
+ void parse_ip6(packetinfo *pi)
327
+ {
328
+ switch (pi->ip6->next) {
329
+ case IP_PROTO_TCP:
330
+ prepare_tcp(pi);
331
+ parse_tcp(pi);
332
+ break;
333
+ case IP_PROTO_UDP:
334
+ prepare_udp(pi);
335
+ parse_udp(pi);
336
+ break;
337
+ case IP_PROTO_IP4:
338
+ prepare_ip6ip(pi);
339
+ break;
340
+ case IP_PROTO_IP6:
341
+ prepare_ip6ip(pi);
342
+ break;
343
+ default:
344
+ break;
345
+ }
346
+ }
347
+
348
+ void set_pkt_end_ptr(packetinfo *pi)
349
+ {
350
+ /* Paranoia! */
351
+ if (pi->pheader->len <= SNAPLENGTH)
352
+ pi->end_ptr = (pi->packet + pi->pheader->len);
353
+ else
354
+ pi->end_ptr = (pi->packet + SNAPLENGTH);
355
+ }
356
+
357
+ void prepare_tcp(packetinfo *pi)
358
+ {
359
+ config.p_s.tcp_recv++;
360
+ if (pi->af == AF_INET) {
361
+ vlog(0x3, "[*] IPv4 PROTOCOL TYPE TCP:\n");
362
+ pi->tcph = (tcp_header *) (pi->packet + pi->eth_hlen +
363
+ (IP_HL(pi->ip4) * 4));
364
+ pi->plen = (pi->pheader->caplen - (TCP_OFFSET(pi->tcph)) * 4 -
365
+ (IP_HL(pi->ip4) * 4) - pi->eth_hlen);
366
+ pi->payload = (pi->packet + pi->eth_hlen + (IP_HL(pi->ip4) * 4) +
367
+ (TCP_OFFSET(pi->tcph) * 4));
368
+ }
369
+ else if (pi->af == AF_INET6) {
370
+ vlog(0x3, "[*] IPv6 PROTOCOL TYPE TCP:\n");
371
+ pi->tcph = (tcp_header *) (pi->packet + pi->eth_hlen + IP6_HEADER_LEN);
372
+ pi->plen = (pi->pheader->caplen - (TCP_OFFSET(pi->tcph)) * 4 -
373
+ IP6_HEADER_LEN - pi->eth_hlen);
374
+ pi->payload = (pi->packet + pi->eth_hlen + IP6_HEADER_LEN +
375
+ (TCP_OFFSET(pi->tcph)*4));
376
+ }
377
+ pi->proto = IP_PROTO_TCP;
378
+ pi->s_port = pi->tcph->src_port;
379
+ pi->d_port = pi->tcph->dst_port;
380
+ connection_tracking(pi);
381
+ }
382
+
383
+ void prepare_udp(packetinfo *pi)
384
+ {
385
+ config.p_s.udp_recv++;
386
+ if (pi->af == AF_INET) {
387
+ vlog(0x3, "[*] IPv4 PROTOCOL TYPE UDP:\n");
388
+ pi->udph = (udp_header *) (pi->packet + pi->eth_hlen +
389
+ (IP_HL(pi->ip4) * 4));
390
+ pi->plen = pi->pheader->caplen - UDP_HEADER_LEN -
391
+ (IP_HL(pi->ip4) * 4) - pi->eth_hlen;
392
+ pi->payload = (pi->packet + pi->eth_hlen +
393
+ (IP_HL(pi->ip4) * 4) + UDP_HEADER_LEN);
394
+ }
395
+ else if (pi->af == AF_INET6) {
396
+ vlog(0x3, "[*] IPv6 PROTOCOL TYPE UDP:\n");
397
+ pi->udph = (udp_header *) (pi->packet + pi->eth_hlen +
398
+ IP6_HEADER_LEN);
399
+ pi->plen = pi->pheader->caplen - UDP_HEADER_LEN -
400
+ IP6_HEADER_LEN - pi->eth_hlen;
401
+ pi->payload = (pi->packet + pi->eth_hlen +
402
+ IP6_HEADER_LEN + UDP_HEADER_LEN);
403
+ }
404
+ pi->proto = IP_PROTO_UDP;
405
+ pi->s_port = pi->udph->src_port;
406
+ pi->d_port = pi->udph->dst_port;
407
+ connection_tracking(pi);
408
+ }
409
+
410
+ void parse_tcp(packetinfo *pi)
411
+ {
412
+ if (pi->plen <= 0) return;
413
+
414
+ /* Reliable traffic comes from the servers (normally on port 53 or 5353)
415
+ * and the client has sent at least one packet on that
416
+ * connecton (Maybe asking for an aswer :) */
417
+ dlog("[D] Parsing TCP packet...\n");
418
+ dns_parser(pi);
419
+ }
420
+
421
+ void parse_udp(packetinfo *pi)
422
+ {
423
+ if (pi->plen <= 0) return;
424
+
425
+ /* Reliable traffic comes from the servers (normally on port 53 or 5353)
426
+ * and the client has sent at least one packet on that
427
+ * connecton (Maybe asking for an aswer :) */
428
+ dlog("[D] Parsing UDP packet...\n");
429
+ dns_parser(pi);
430
+ }
431
+
432
+ int connection_tracking(packetinfo *pi)
433
+ {
434
+ struct in6_addr *ip_src;
435
+ struct in6_addr *ip_dst;
436
+ struct in6_addr ips;
437
+ struct in6_addr ipd;
438
+ uint16_t src_port = pi->s_port;
439
+ uint16_t dst_port = pi->d_port;
440
+ int af = pi->af;
441
+ connection *cxt = NULL;
442
+ connection *head = NULL;
443
+ uint32_t hash;
444
+
445
+ if(af == AF_INET6){
446
+ ip_src = &PI_IP6SRC(pi);
447
+ ip_dst = &PI_IP6DST(pi);
448
+ }
449
+ else {
450
+ #ifdef BSD_DERIVED
451
+ ips.__u6_addr.__u6_addr32[0] = pi->ip4->ip_src;
452
+ ipd.__u6_addr.__u6_addr32[0] = pi->ip4->ip_dst;
453
+ #else
454
+ ips.s6_addr32[0] = pi->ip4->ip_src;
455
+ ipd.s6_addr32[0] = pi->ip4->ip_dst;
456
+ #endif
457
+ ip_src = &ips;
458
+ ip_dst = &ipd;
459
+ }
460
+
461
+ /* Find the right connection bucket */
462
+ if (af == AF_INET)
463
+ hash = CXT_HASH4(IP4ADDR(ip_src), IP4ADDR(ip_dst), src_port, dst_port,
464
+ pi->proto);
465
+ else if (af == AF_INET6)
466
+ hash = CXT_HASH6(ip_src, ip_dst, src_port, dst_port, pi->proto);
467
+ else {
468
+ dlog("[D] Only CTX with AF_INET and AF_INET6 are supported: %d\n", af);
469
+ return 0;
470
+ }
471
+
472
+ cxt = bucket[hash];
473
+ head = cxt;
474
+
475
+ /* Search through the bucket */
476
+ while (cxt != NULL)
477
+ {
478
+ /* Two-way compare of given connection against connection table */
479
+ if (af == AF_INET) {
480
+ if (CMP_CXT4(cxt, IP4ADDR(ip_src), src_port, IP4ADDR(ip_dst), dst_port)) {
481
+ /* Client sends first packet (TCP/SYN - UDP?) hence this is a client */
482
+ dlog("[D] Found existing v4 client connection.\n");
483
+ return cxt_update_client(cxt, pi);
484
+ }
485
+ else if (CMP_CXT4(cxt, IP4ADDR(ip_dst), dst_port, IP4ADDR(ip_src), src_port)) {
486
+
487
+ if (pi->sc == SC_SERVER) {
488
+ /* This is a server */
489
+ dlog("[D] Found existing v4 server connection.\n");
490
+ return cxt_update_server(cxt, pi);
491
+ }
492
+ else {
493
+ /* This is a client, where we saw a mid-stream DNS response first */
494
+ dlog("[D] Found existing unknown v4 server connection.\n");
495
+ return cxt_update_client(cxt, pi);
496
+ }
497
+ }
498
+ }
499
+ else if (af == AF_INET6) {
500
+ if (CMP_CXT6(cxt, ip_src, src_port, ip_dst, dst_port)) {
501
+ dlog("[D] Found existing v6 client connection.\n");
502
+ return cxt_update_client(cxt, pi);
503
+ }
504
+ else if (CMP_CXT6(cxt, ip_dst, dst_port, ip_src, src_port)) {
505
+ dlog("[D] Found existing v6 client connection.\n");
506
+ return cxt_update_server(cxt, pi);
507
+ }
508
+ }
509
+ cxt = cxt->next;
510
+ }
511
+ /* Bucket turned upside down didn't yield anything. New connection */
512
+ dlog("[D] New connection.\n");
513
+ cxt = cxt_new(pi);
514
+
515
+ /* New connections are pushed on to the head of bucket[s_hash] */
516
+ cxt->next = head;
517
+ if (head != NULL)
518
+ /* Are we double linked? */
519
+ head->prev = cxt;
520
+
521
+ bucket[hash] = cxt;
522
+ pi->cxt = cxt;
523
+ return cxt_update_unknown(cxt, pi);
524
+ }
525
+
526
+ /* Freshly smelling connection :d */
527
+ connection *cxt_new(packetinfo *pi)
528
+ {
529
+ struct in6_addr ips;
530
+ struct in6_addr ipd;
531
+ connection *cxt;
532
+ config.cxtrackerid++;
533
+ cxt = (connection *) calloc(1, sizeof(connection));
534
+ cxt->cxid = config.cxtrackerid;
535
+ cxt->af = pi->af;
536
+
537
+ if (pi->tcph)
538
+ cxt->s_tcpFlags |= pi->tcph->t_flags;
539
+
540
+ cxt->start_time = pi->pheader->ts.tv_sec;
541
+ cxt->last_pkt_time = pi->pheader->ts.tv_sec;
542
+
543
+ if (pi->af == AF_INET6){
544
+ cxt->s_ip = PI_IP6SRC(pi);
545
+ cxt->d_ip = PI_IP6DST(pi);
546
+ }
547
+ else {
548
+ #ifdef BSD_DERIVED
549
+ ips.__u6_addr.__u6_addr32[0] = pi->ip4->ip_src;
550
+ ipd.__u6_addr.__u6_addr32[0] = pi->ip4->ip_dst;
551
+ #else
552
+ ips.s6_addr32[0] = pi->ip4->ip_src;
553
+ ipd.s6_addr32[0] = pi->ip4->ip_dst;
554
+ #endif
555
+ cxt->s_ip = ips;
556
+ cxt->d_ip = ipd;
557
+ }
558
+
559
+ cxt->s_port = pi->s_port;
560
+ cxt->d_port = pi->d_port;
561
+ cxt->proto = pi->proto;
562
+
563
+ cxt->check = 0x00;
564
+ cxt->reversed = 0;
565
+ config.curcxt++;
566
+
567
+ return cxt;
568
+ }
569
+
570
+ int cxt_update_client(connection *cxt, packetinfo *pi)
571
+ {
572
+ cxt->last_pkt_time = pi->pheader->ts.tv_sec;
573
+
574
+ if (pi->tcph)
575
+ cxt->s_tcpFlags |= pi->tcph->t_flags;
576
+
577
+ cxt->s_total_bytes += pi->packet_bytes;
578
+ cxt->s_total_pkts += 1;
579
+
580
+ pi->cxt = cxt;
581
+ pi->sc = SC_CLIENT;
582
+
583
+ if (cxt->s_total_bytes > MAX_BYTE_CHECK ||
584
+ cxt->s_total_pkts > MAX_PKT_CHECK) {
585
+ return 0; /* Don't Check! */
586
+ }
587
+
588
+ return SC_CLIENT;
589
+ }
590
+
591
+ int cxt_update_unknown(connection *cxt, packetinfo *pi)
592
+ {
593
+ cxt->last_pkt_time = pi->pheader->ts.tv_sec;
594
+
595
+ if (pi->tcph)
596
+ cxt->s_tcpFlags |= pi->tcph->t_flags;
597
+
598
+ cxt->s_total_bytes += pi->packet_bytes;
599
+ cxt->s_total_pkts += 1;
600
+
601
+ pi->cxt = cxt;
602
+ pi->sc = SC_UNKNOWN;
603
+
604
+ if (cxt->s_total_bytes > MAX_BYTE_CHECK ||
605
+ cxt->s_total_pkts > MAX_PKT_CHECK) {
606
+ return 0; /* Don't Check! */
607
+ }
608
+
609
+ return SC_UNKNOWN;
610
+ }
611
+
612
+ int cxt_update_server(connection *cxt, packetinfo *pi)
613
+ {
614
+ cxt->last_pkt_time = pi->pheader->ts.tv_sec;
615
+
616
+ if (pi->tcph)
617
+ cxt->d_tcpFlags |= pi->tcph->t_flags;
618
+
619
+ cxt->d_total_bytes += pi->packet_bytes;
620
+ cxt->d_total_pkts += 1;
621
+
622
+ pi->cxt = cxt;
623
+ pi->sc = SC_SERVER;
624
+
625
+ if (cxt->d_total_bytes > MAX_BYTE_CHECK ||
626
+ cxt->d_total_pkts > MAX_PKT_CHECK)
627
+ return 0; /* Don't check! */
628
+
629
+ return SC_SERVER;
630
+ }
631
+
632
+ void end_all_sessions()
633
+ {
634
+ connection *cxt;
635
+ int cxkey;
636
+ config.llcxt = 0;
637
+
638
+ for (cxkey = 0; cxkey < BUCKET_SIZE; cxkey++)
639
+ {
640
+ cxt = bucket[cxkey];
641
+ while (cxt != NULL)
642
+ {
643
+ config.llcxt++;
644
+ if (cxt->prev)
645
+ cxt->prev->next = cxt->next;
646
+ if (cxt->next)
647
+ cxt->next->prev = cxt->prev;
648
+ connection *tmp = cxt;
649
+
650
+ cxt = cxt->next;
651
+ del_connection(tmp, &bucket[cxkey]);
652
+ if (cxt == NULL)
653
+ bucket[cxkey] = NULL;
654
+ }
655
+ }
656
+ dlog("CXT in list before cleaning: %10u\n", config.llcxt);
657
+ dlog("CXT in list after cleaning: %10u\n", config.curcxt);
658
+ }
659
+
660
+ void end_sessions()
661
+ {
662
+ connection *cxt;
663
+ time_t check_time;
664
+ check_time = config.tstamp.tv_sec;
665
+ int ended, expired = 0;
666
+ config.llcxt = 0;
667
+
668
+ int iter;
669
+
670
+ for (iter = 0; iter < BUCKET_SIZE; iter++)
671
+ {
672
+ cxt = bucket[iter];
673
+ while (cxt != NULL)
674
+ {
675
+ ended = 0;
676
+ config.llcxt++;
677
+ /* TCP */
678
+ if (cxt->proto == IP_PROTO_TCP) {
679
+ /* FIN from both sides */
680
+ if (cxt->s_tcpFlags & TF_FIN && cxt->d_tcpFlags & TF_FIN
681
+ && (check_time - cxt->last_pkt_time) > 5)
682
+ ended = 1;
683
+ /* RST from either side */
684
+ else if ((cxt->s_tcpFlags & TF_RST || cxt->d_tcpFlags & TF_RST)
685
+ && (check_time - cxt->last_pkt_time) > 5)
686
+ ended = 1;
687
+ else if ((check_time - cxt->last_pkt_time) > TCP_TIMEOUT)
688
+ expired = 1;
689
+ }
690
+ /* UDP */
691
+ else if (cxt->proto == IP_PROTO_UDP
692
+ && (check_time - cxt->last_pkt_time) > UDP_TIMEOUT)
693
+ expired = 1;
694
+ /* ICMP */
695
+ else if (cxt->proto == IP_PROTO_ICMP ||
696
+ cxt->proto == IP6_PROTO_ICMP) {
697
+ if ((check_time - cxt->last_pkt_time) > ICMP_TIMEOUT)
698
+ expired = 1;
699
+ }
700
+ /* All other protocols */
701
+ else if ((check_time - cxt->last_pkt_time) > OTHER_TIMEOUT)
702
+ expired = 1;
703
+
704
+ if (ended == 1 || expired == 1) {
705
+ /* Remove from the hash */
706
+ if (cxt->prev)
707
+ cxt->prev->next = cxt->next;
708
+ if (cxt->next)
709
+ cxt->next->prev = cxt->prev;
710
+ connection *tmp = cxt;
711
+ connection *tmp_pre = cxt->prev;
712
+
713
+ ended = expired = 0;
714
+
715
+ cxt = cxt->next;
716
+
717
+ del_connection(tmp, &bucket[iter]);
718
+ if (cxt == NULL && tmp_pre == NULL)
719
+ bucket[iter] = NULL;
720
+ }
721
+ else
722
+ cxt = cxt->next;
723
+ }
724
+ }
725
+ dlog("CXT in list before cleaning: %10u\n", config.llcxt);
726
+ dlog("CXT in list after cleaning: %10u\n", config.curcxt);
727
+ }
728
+
729
+ void del_connection(connection * cxt, connection ** bucket_ptr)
730
+ {
731
+ connection *prev = cxt->prev; /* Older connections */
732
+ connection *next = cxt->next; /* Newer connections */
733
+
734
+ if (prev == NULL) {
735
+ /* Beginning of list */
736
+ *bucket_ptr = next;
737
+ /* Not only entry */
738
+ if (next)
739
+ next->prev = NULL;
740
+ }
741
+ else if (next == NULL) {
742
+ /* At end of list! */
743
+ prev->next = NULL;
744
+ }
745
+ else {
746
+ /* A node */
747
+ prev->next = next;
748
+ next->prev = prev;
749
+ }
750
+
751
+ /* Free and set to NULL */
752
+ free(cxt);
753
+ cxt = NULL;
754
+ config.curcxt--;
755
+ }
756
+
757
+ const char *u_ntop_src(packetinfo *pi, char *dest)
758
+ {
759
+ if (pi->af == AF_INET) {
760
+ if (!inet_ntop(AF_INET, &pi->ip4->ip_src, dest, INET_ADDRSTRLEN + 1)) {
761
+ perror("Something died in inet_ntop");
762
+ return NULL;
763
+ }
764
+ }
765
+ else if (pi->af == AF_INET6) {
766
+ if (!inet_ntop(AF_INET6, &pi->ip6->ip_src, dest,
767
+ INET6_ADDRSTRLEN + 1)) {
768
+ perror("Something died in inet_ntop");
769
+ return NULL;
770
+ }
771
+ }
772
+ return dest;
773
+ }
774
+
775
+ void check_interrupt()
776
+ {
777
+ dlog("[D] In interrupt. Flag: %d\n",config.intr_flag);
778
+ if (ISSET_INTERRUPT_END(config))
779
+ game_over();
780
+
781
+ else if (ISSET_INTERRUPT_SESSION(config))
782
+ set_end_sessions();
783
+
784
+ else if (ISSET_INTERRUPT_DNS(config))
785
+ set_end_dns_records();
786
+
787
+ else
788
+ config.intr_flag = 0;
789
+ }
790
+
791
+ void sig_alarm_handler()
792
+ {
793
+ time_t now_t;
794
+ now_t = config.tstamp.tv_sec;
795
+
796
+ dlog("[D] Got SIG ALRM: %lu\n", now_t);
797
+ /* Each time check for timed out sessions */
798
+ set_end_sessions();
799
+
800
+ /* Only check for timed-out dns records each 10 minutes */
801
+ if ((now_t - config.dnslastchk) >= 600) {
802
+ set_end_dns_records();
803
+ }
804
+ alarm(TIMEOUT);
805
+ }
806
+
807
+ void sig_hup_handler()
808
+ {
809
+ signal_reopen_log_files = 1;
810
+ }
811
+
812
+ void reopen_log_files()
813
+ {
814
+ if (config.output_log) {
815
+ if (config.logfile_fd != NULL && config.logfile_fd != stdout)
816
+ fclose(config.logfile_fd);
817
+ config.logfile_fd = fopen(config.logfile, "a");
818
+ }
819
+
820
+ if (config.output_log_nxd) {
821
+ if (config.logfile_all) {
822
+ /* Do nothing, since both logs use the same file */
823
+ }
824
+ else {
825
+ if (config.logfile_nxd_fd != NULL && config.logfile_nxd_fd != stdout)
826
+ fclose(config.logfile_nxd_fd);
827
+ config.logfile_nxd_fd = fopen(config.logfile_nxd, "a");
828
+ }
829
+ }
830
+ signal_reopen_log_files = 0;
831
+ }
832
+
833
+ void set_end_dns_records()
834
+ {
835
+ config.intr_flag |= INTERRUPT_DNS;
836
+
837
+ if (config.inpacket == 0) {
838
+ expire_dns_records();
839
+ config.dnslastchk = config.tstamp.tv_sec;
840
+ config.intr_flag &= ~INTERRUPT_DNS;
841
+ }
842
+ }
843
+
844
+ void set_end_sessions()
845
+ {
846
+ config.intr_flag |= INTERRUPT_SESSION;
847
+
848
+ if (config.inpacket == 0) {
849
+ end_sessions();
850
+ config.intr_flag &= ~INTERRUPT_SESSION;
851
+ }
852
+ }
853
+
854
+ static int set_chroot(void)
855
+ {
856
+ char *absdir;
857
+
858
+ /* Change to the directory */
859
+ if (chdir(config.chroot_dir) != 0)
860
+ printf("set_chroot: Can not chdir to \"%s\": %s\n",
861
+ config.chroot_dir,strerror(errno));
862
+
863
+ /* Always returns an absolute pathname */
864
+ absdir = getcwd(NULL, 0);
865
+
866
+ /* Make the chroot call */
867
+ if (chroot(absdir) < 0)
868
+ printf("Could not chroot to \"%s\": absolute: %s: %s\n",
869
+ config.chroot_dir, absdir, strerror(errno));
870
+
871
+ if (chdir("/") < 0)
872
+ printf("Could not chdir to \"/\" after chroot: %s\n", strerror(errno));
873
+
874
+ return 0;
875
+ }
876
+
877
+ int drop_privs(void)
878
+ {
879
+ struct group *gr;
880
+ struct passwd *pw;
881
+ char *endptr;
882
+ int i;
883
+ int do_setuid = 0;
884
+ int do_setgid = 0;
885
+ unsigned long groupid = 0;
886
+ unsigned long userid = 0;
887
+
888
+ if (config.group_name != NULL) {
889
+ do_setgid = 1;
890
+ if (!isdigit(config.group_name[0])) {
891
+ gr = getgrnam(config.group_name);
892
+ if (!gr) {
893
+ if (config.chroot_dir) {
894
+ elog("ERROR: you have chrooted and must set numeric group ID.\n");
895
+ exit(1);
896
+ }
897
+ else {
898
+ elog("ERROR: couldn't get ID for group %s, group does not exist.", config.group_name);
899
+ exit(1);
900
+ }
901
+ }
902
+ groupid = gr->gr_gid;
903
+ }
904
+ else {
905
+ groupid = strtoul(config.group_name, &endptr, 10);
906
+ }
907
+ }
908
+
909
+ if (config.user_name != NULL) {
910
+ do_setuid = 1;
911
+ do_setgid = 1;
912
+ if (isdigit(config.user_name[0]) == 0) {
913
+ pw = getpwnam(config.user_name);
914
+ if (pw != NULL) {
915
+ userid = pw->pw_uid;
916
+ }
917
+ else {
918
+ printf("[E] User %s not found!\n", config.user_name);
919
+ }
920
+ }
921
+ else {
922
+ userid = strtoul(config.user_name, &endptr, 10);
923
+ pw = getpwuid(userid);
924
+ }
925
+
926
+ if (config.group_name == NULL && pw != NULL)
927
+ groupid = pw->pw_gid;
928
+ }
929
+
930
+ if (do_setgid) {
931
+ if ((i = setgid(groupid)) < 0)
932
+ printf("Unable to set group ID: %s", strerror(i));
933
+ }
934
+
935
+ endgrent();
936
+ endpwent();
937
+
938
+ if (do_setuid) {
939
+ if (getuid() == 0 && initgroups(config.user_name, groupid) < 0)
940
+ printf("Unable to init group names (%s/%lu)", config.user_name,
941
+ groupid);
942
+
943
+ if ((i = setuid(userid)) < 0)
944
+ printf("Unable to set user ID: %s\n", strerror(i));
945
+ }
946
+ return 0;
947
+ }
948
+
949
+ int is_valid_path(const char *path)
950
+ {
951
+ char dir[STDBUF];
952
+ struct stat st;
953
+
954
+ if (path == NULL)
955
+ return 0;
956
+
957
+ memcpy(dir, path, strnlen(path, STDBUF));
958
+ dirname(dir);
959
+
960
+ if (stat(dir, &st) != 0)
961
+ return 0;
962
+
963
+ if (!S_ISDIR(st.st_mode) || access(dir, W_OK) == -1)
964
+ return 0;
965
+
966
+ return 1;
967
+ }
968
+
969
+ int create_pid_file(const char *path)
970
+ {
971
+ char pid_buffer[12];
972
+ struct flock lock;
973
+ int fd;
974
+
975
+ if (!path)
976
+ path = config.pidfile;
977
+
978
+ if (!is_valid_path(path))
979
+ printf("PID path \"%s\" aint writable", path);
980
+
981
+ if ((fd = open(path, O_CREAT | O_WRONLY,
982
+ S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1)
983
+ return ERROR;
984
+
985
+ /* PID file locking */
986
+ lock.l_type = F_WRLCK;
987
+ lock.l_start = 0;
988
+ lock.l_whence = SEEK_SET;
989
+ lock.l_len = 0;
990
+
991
+ if (fcntl(fd, F_SETLK, &lock) == -1) {
992
+ close(fd);
993
+ return ERROR;
994
+ }
995
+
996
+ snprintf(pid_buffer, sizeof(pid_buffer), "%d\n", (int)getpid());
997
+
998
+ if (ftruncate(fd, 0) != 0) {
999
+ close(fd);
1000
+ return ERROR;
1001
+ }
1002
+
1003
+ if (write(fd, pid_buffer, strlen(pid_buffer)) != 0) {
1004
+ close(fd);
1005
+ return ERROR;
1006
+ }
1007
+
1008
+ close(fd);
1009
+ return SUCCESS;
1010
+ }
1011
+
1012
+ int daemonize()
1013
+ {
1014
+ pid_t pid;
1015
+ int fd;
1016
+
1017
+ pid = fork();
1018
+
1019
+ if (pid > 0)
1020
+ exit(0); /* Parent */
1021
+
1022
+ if (pid < 0)
1023
+ return ERROR;
1024
+
1025
+ setsid();
1026
+
1027
+ if ((fd = open("/dev/null", O_RDWR)) >= 0) {
1028
+ dup2(fd, 0);
1029
+ dup2(fd, 1);
1030
+ dup2(fd, 2);
1031
+ if (fd > 2) {
1032
+ close(fd);
1033
+ }
1034
+ }
1035
+
1036
+ if (config.pidfile)
1037
+ return create_pid_file(config.pidfile);
1038
+
1039
+ return SUCCESS;
1040
+ }
1041
+
1042
+ void game_over()
1043
+ {
1044
+ if (config.inpacket == 0) {
1045
+ expire_all_dns_records();
1046
+ print_pdns_stats();
1047
+
1048
+ if (config.handle != NULL)
1049
+ pcap_close(config.handle);
1050
+
1051
+ config.handle = NULL;
1052
+
1053
+ if (config.hostname != NULL)
1054
+ free(config.hostname);
1055
+
1056
+ #ifdef HAVE_PFRING
1057
+ if (config.use_pfring && config.pfhandle != NULL) {
1058
+ pfring_breakloop(config.pfhandle);
1059
+ pfring_close(config.pfhandle);
1060
+ }
1061
+ #endif /* HAVE_PFRING */
1062
+
1063
+ end_all_sessions();
1064
+
1065
+ if (config.logfile_fd != NULL && config.logfile_fd != stdout)
1066
+ fclose(config.logfile_fd);
1067
+
1068
+ if (config.logfile_nxd_fd != NULL && config.logfile_nxd_fd != stdout)
1069
+ fclose(config.logfile_nxd_fd);
1070
+
1071
+ free_config();
1072
+ olog("\n[*] passivedns ended.\n");
1073
+ exit(0);
1074
+ }
1075
+ config.intr_flag |= INTERRUPT_END;
1076
+ }
1077
+
1078
+ void free_config()
1079
+ {
1080
+ if (config.cfilter.bf_insns != NULL)
1081
+ free(config.cfilter.bf_insns);
1082
+ }
1083
+
1084
+ void print_pdns_stats()
1085
+ {
1086
+ FILE *handle = stdout;
1087
+ if (config.use_stats_file) {
1088
+ handle = fopen(config.statsfile, "w");
1089
+ if (handle == NULL) {
1090
+ olog("[!] Error opening stats file %s: %s\n", config.statsfile,
1091
+ strerror(errno));
1092
+ return;
1093
+ }
1094
+ }
1095
+
1096
+ flog(handle, "\n");
1097
+ flog(handle, "-- Total DNS records allocated :%12u\n",
1098
+ config.p_s.dns_records);
1099
+ flog(handle, "-- Total DNS assets allocated :%12u\n",
1100
+ config.p_s.dns_assets);
1101
+ flog(handle, "-- Total DNS packets over IPv4/TCP :%12u\n",
1102
+ config.p_s.ip4_dns_tcp);
1103
+ flog(handle, "-- Total DNS packets over IPv6/TCP :%12u\n",
1104
+ config.p_s.ip6_dns_tcp);
1105
+ flog(handle, "-- Total DNS packets over TCP decoded :%12u\n",
1106
+ config.p_s.ip4_dec_tcp_ok + config.p_s.ip6_dec_tcp_ok);
1107
+ flog(handle, "-- Total DNS packets over TCP failed :%12u\n",
1108
+ config.p_s.ip4_dec_tcp_er + config.p_s.ip6_dec_tcp_er);
1109
+ flog(handle, "-- Total DNS packets over IPv4/UDP :%12u\n",
1110
+ config.p_s.ip4_dns_udp);
1111
+ flog(handle, "-- Total DNS packets over IPv6/UDP :%12u\n",
1112
+ config.p_s.ip6_dns_udp);
1113
+ flog(handle, "-- Total DNS packets over UDP decoded :%12u\n",
1114
+ config.p_s.ip4_dec_udp_ok + config.p_s.ip6_dec_udp_ok);
1115
+ flog(handle, "-- Total DNS packets over UDP failed :%12u\n",
1116
+ config.p_s.ip4_dec_udp_er + config.p_s.ip6_dec_udp_er);
1117
+ flog(handle, "-- Total packets received from libpcap :%12u\n",
1118
+ config.p_s.got_packets);
1119
+ flog(handle, "-- Total Ethernet packets received :%12u\n",
1120
+ config.p_s.eth_recv);
1121
+ flog(handle, "-- Total VLAN packets received :%12u\n",
1122
+ config.p_s.vlan_recv);
1123
+
1124
+ if (config.use_stats_file) {
1125
+ fclose(handle);
1126
+ }
1127
+ }
1128
+
1129
+ void usage()
1130
+ {
1131
+ olog("\n");
1132
+ olog("USAGE:\n");
1133
+ olog(" $ passivedns [options]\n\n");
1134
+ olog(" OPTIONS:\n\n");
1135
+ olog(" -i <iface> Network device <iface> (default: eth0).\n");
1136
+ olog(" -r <file> Read pcap <file>.\n");
1137
+ olog(" -H <hostname> Choose hostname to print in record.\n");
1138
+ #ifdef HAVE_PFRING
1139
+ olog(" -n Use PF_RING.\n");
1140
+ olog(" -c <cluster_id> Set PF_RING cluster_id.\n");
1141
+ #endif /* HAVE_PFRING */
1142
+ olog(" -l <file> Logfile normal queries (default: /var/log/passivedns.log).\n");
1143
+ olog(" -L <file> Logfile for SRC Error queries (default: /var/log/passivedns.log).\n");
1144
+ olog(" -y Log to syslog (uses local7 syslog facility).\n");
1145
+ olog(" -Y Log NXDOMAIN to syslog.\n");
1146
+ olog(" -d <delimiter> Delimiter between fields in log file (default: ||).\n");
1147
+ #ifdef HAVE_JSON
1148
+ olog(" -j Use JSON as output in log file.\n");
1149
+ olog(" -J Use JSON as output in NXDOMAIN log file.\n");
1150
+ #endif /* HAVE_JSON */
1151
+ olog(" -f <fields> Choose which fields to print (default: -f SMcsCQTAtn).\n");
1152
+ olog(" -s <file> Print stats on signal (SIGUSR1) to this file.\n");
1153
+ olog(" -b 'BPF' Berkley Packet Filter (default: 'port 53').\n");
1154
+ olog(" -p <file> Name of pid file (default: /var/run/passivedns.pid).\n");
1155
+ olog(" -S <mem> Soft memory limit in MB (default: 256).\n");
1156
+ olog(" -C <sec> Seconds to cache DNS objects in memory (default: %u).\n", DNSCACHETIMEOUT);
1157
+ olog(" -P <sec> Seconds between printing duplicate DNS info (default %u).\n", DNSPRINTTIME);
1158
+ olog(" -X <flags> Manually set DNS RR Types to care about (default: -X 46CDNPRS).\n");
1159
+ olog(" -N Set interface to non promisc. mode.\n");
1160
+ olog(" -u <uid> User ID to drop privileges to.\n");
1161
+ olog(" -g <gid> Group ID to drop privileges to.\n");
1162
+ olog(" -T <dir> Directory to chroot into.\n");
1163
+ olog(" -q Quiet mode (no output except errors).\n");
1164
+ olog(" -D Run as daemon.\n");
1165
+ olog(" -V Show version and exit.\n");
1166
+ olog(" -h This help message.\n\n");
1167
+ olog(" FIELDS:\n");
1168
+ olog("\n");
1169
+ olog(" H: YMD-HMS Stamp S: Timestamp(s) M: Timestamp(ms) c: Client IP \n");
1170
+ olog(" s: Server IP C: Class Q: Query T: Type \n");
1171
+ olog(" A: Answer t: TTL p: Protocol n: Count \n");
1172
+ olog(" h: hostname L: QueryLength l: AnswerLength w: Client MAC \n");
1173
+ olog(" W: Server MAC \n");
1174
+ olog("\n");
1175
+ olog(" FLAGS:\n");
1176
+ olog("\n");
1177
+ olog(" * For Record Types:\n");
1178
+ olog(" 4:A 6:AAAA C:CNAME D:DNAME N:NAPTR O:SOA L:LOC F:SPF I:HINFO\n");
1179
+ olog(" P:PTR R:RP S:SRV T:TXT M:MX n:NS d:DNSEC H:SSHFP\n");
1180
+ olog(" L also enables GPOS\n");
1181
+ #ifdef LDNS_RR_TYPE_NSEC3PARAM
1182
+ olog(" d enables DS, DNSKEY, NSEC, NSEC3, RRSIG\n");
1183
+ #else
1184
+ olog(" d enables DS, DNSKEY, NSEC, NSEC3, NSEC3PARAM, RRSIG\n");
1185
+ #endif /* LDNS_RR_TYPE_NSEC3PARAM */
1186
+ olog("\n");
1187
+ olog(" * For Server Return Code (SRC) Errors:\n");
1188
+ olog(" f:FORMERR s:SERVFAIL x:NXDOMAIN o:NOTIMPL r:REFUSED\n");
1189
+ olog(" y:YXDOMAIN e:YXRRSET t:NXRRSET a:NOTAUTH z:NOTZONE\n");
1190
+ olog("\n");
1191
+ }
1192
+
1193
+ void show_version()
1194
+ {
1195
+ olog("\n");
1196
+ olog("[*] PassiveDNS %s\n", VERSION);
1197
+ olog("[*] By Edward Bjarte Fjellskål <edward.fjellskaal@gmail.com>\n");
1198
+ olog("[*] Using %s\n", pcap_lib_version());
1199
+ olog("[*] Using ldns version %s\n",ldns_version());
1200
+ #ifdef HAVE_PFRING
1201
+ /* Print PF_RING version if PF_RING is used */
1202
+ if (config.use_pfring) {
1203
+ char pfv[50];
1204
+ u_int32_t pf_version;
1205
+ pfring_version(config.pfhandle, &pf_version);
1206
+ snprintf(pfv, 50, "%d.%d.%d",
1207
+ (pf_version & 0xFFFF0000) >> 16,
1208
+ (pf_version & 0x0000FF00) >> 8,
1209
+ pf_version & 0x000000FF);
1210
+ olog("[*] Using PF_RING version %s\n", pfv);
1211
+ }
1212
+ #endif /* HAVE_PFRING */
1213
+ #ifdef HAVE_JSON
1214
+ if (config.use_json || config.use_json_nxd) {
1215
+ olog("[*] Using jansson version %s\n", JANSSON_VERSION);
1216
+ }
1217
+ #endif /* HAVE_JSON */
1218
+ }
1219
+
1220
+ extern int optind, opterr, optopt; // getopt()
1221
+
1222
+ /* magic main */
1223
+ int main(int argc, char *argv[])
1224
+ {
1225
+ int ch = 0; // verbose_already = 0;
1226
+ int daemon = 0;
1227
+ memset(&config, 0, sizeof(globalconfig));
1228
+ config.inpacket = config.intr_flag = 0;
1229
+ config.dnslastchk = 0;
1230
+ config.bpff = BPFF;
1231
+ config.logfile = "/var/log/passivedns.log";
1232
+ config.logfile_nxd = "/var/log/passivedns.log";
1233
+ config.statsfile = "/var/log/passivedns.stats";
1234
+ config.pidfile = "/var/run/passivedns.pid";
1235
+ config.promisc = 1;
1236
+ config.output_log = 0;
1237
+ config.output_log_nxd = 0;
1238
+ config.output_syslog = 0;
1239
+ config.output_syslog_nxd = 0;
1240
+ /* Default memory limit: 256 MB */
1241
+ config.mem_limit_max = (256 * 1024 * 1024);
1242
+ config.dnsprinttime = DNSPRINTTIME;
1243
+ config.dnscachetimeout = DNSCACHETIMEOUT;
1244
+ config.dnsf = 0;
1245
+ config.log_delimiter = "||";
1246
+ config.fieldsf = 0;
1247
+ config.fieldsf |= FIELD_TIMESTAMP_S;
1248
+ config.fieldsf |= FIELD_TIMESTAMP_MS;
1249
+ config.fieldsf |= FIELD_CLIENT;
1250
+ config.fieldsf |= FIELD_SERVER;
1251
+ config.fieldsf |= FIELD_CLASS;
1252
+ config.fieldsf |= FIELD_QUERY;
1253
+ config.fieldsf |= FIELD_TYPE;
1254
+ config.fieldsf |= FIELD_ANSWER;
1255
+ config.fieldsf |= FIELD_TTL;
1256
+ config.fieldsf |= FIELD_COUNT;
1257
+ config.dnsf |= DNS_CHK_A;
1258
+ config.dnsf |= DNS_CHK_AAAA;
1259
+ config.dnsf |= DNS_CHK_PTR;
1260
+ config.dnsf |= DNS_CHK_CNAME;
1261
+ config.dnsf |= DNS_CHK_DNAME;
1262
+ config.dnsf |= DNS_CHK_NAPTR;
1263
+ config.dnsf |= DNS_CHK_RP;
1264
+ config.dnsf |= DNS_CHK_SRV;
1265
+ #ifdef HAVE_PFRING
1266
+ config.cluster_id = 0;
1267
+ u_int32_t flags = 0;
1268
+ #endif /* HAVE_PFRING */
1269
+ signal(SIGTERM, game_over);
1270
+ signal(SIGINT, game_over);
1271
+ signal(SIGQUIT, game_over);
1272
+ signal(SIGALRM, sig_alarm_handler);
1273
+ signal(SIGHUP, sig_hup_handler);
1274
+ signal(SIGUSR1, print_pdns_stats);
1275
+ signal(SIGUSR2, expire_all_dns_records);
1276
+
1277
+ #define ARGS "i:H:r:qc:nyYNjJl:s:L:d:hb:Dp:C:P:S:f:X:u:g:T:V"
1278
+
1279
+ while ((ch = getopt(argc, argv, ARGS)) != -1)
1280
+ switch (ch) {
1281
+ case 'i':
1282
+ config.dev = optarg;
1283
+ break;
1284
+ case 'H':
1285
+ config.hostname = strdup(optarg);
1286
+ break;
1287
+ case 'r':
1288
+ config.pcap_file = optarg;
1289
+ break;
1290
+ case 'q':
1291
+ config.cflags |= CONFIG_QUIET;
1292
+ break;
1293
+ case 'L':
1294
+ config.output_log_nxd = 1;
1295
+ config.logfile_nxd = optarg;
1296
+ break;
1297
+ case 'l':
1298
+ config.output_log = 1;
1299
+ config.logfile = optarg;
1300
+ break;
1301
+ case 'y':
1302
+ config.output_syslog = 1;
1303
+ break;
1304
+ case 'Y':
1305
+ config.output_syslog_nxd = 1;
1306
+ break;
1307
+ #ifdef HAVE_JSON
1308
+ case 'j':
1309
+ config.use_json = 1;
1310
+ break;
1311
+ case 'J':
1312
+ config.use_json_nxd = 1;
1313
+ break;
1314
+ #endif /* HAVE_JSON */
1315
+ case 'd':
1316
+ config.log_delimiter = optarg;
1317
+ break;
1318
+ case 'b':
1319
+ config.bpff = optarg;
1320
+ break;
1321
+ case 'p':
1322
+ config.pidfile = optarg;
1323
+ break;
1324
+ case 'C':
1325
+ config.dnscachetimeout = strtol(optarg, NULL, 0);
1326
+ break;
1327
+ case 'P':
1328
+ config.dnsprinttime = strtol(optarg, NULL, 0);
1329
+ break;
1330
+ case 'S':
1331
+ config.mem_limit_max = (strtol(optarg, NULL, 0) * 1024 * 1024);
1332
+ break;
1333
+ case 's':
1334
+ config.use_stats_file = 1;
1335
+ config.statsfile = optarg;
1336
+ break;
1337
+ case 'f':
1338
+ parse_field_flags(optarg);
1339
+ break;
1340
+ case 'X':
1341
+ parse_dns_flags(optarg);
1342
+ break;
1343
+ case 'D':
1344
+ daemon = 1;
1345
+ break;
1346
+ case 'T':
1347
+ config.chroot_dir = optarg;
1348
+ config.chroot_flag = 1;
1349
+ break;
1350
+ case 'u':
1351
+ config.user_name = optarg;
1352
+ config.drop_privs_flag = 1;
1353
+ break;
1354
+ case 'g':
1355
+ config.group_name = optarg;
1356
+ config.drop_privs_flag = 1;
1357
+ break;
1358
+ case 'N':
1359
+ config.promisc = 0;
1360
+ break;
1361
+ #ifdef HAVE_PFRING
1362
+ case 'n':
1363
+ config.use_pfring = 1;
1364
+ break;
1365
+ case 'c':
1366
+ config.cluster_id = strtol(optarg, NULL, 0);
1367
+ break;
1368
+ #endif /* HAVE_PFRING */
1369
+ case 'h':
1370
+ usage();
1371
+ exit(0);
1372
+ break;
1373
+ case 'V':
1374
+ show_version();
1375
+ olog("\n");
1376
+ exit(0);
1377
+ break;
1378
+ case '?':
1379
+ elog("unrecognized argument: '%c'\n", optopt);
1380
+ break;
1381
+ default:
1382
+ elog("Did not recognize argument '%c'\n", ch);
1383
+ }
1384
+
1385
+ /* Get hostname if not specified by commandline */
1386
+ if (config.fieldsf & FIELD_HOSTNAME) {
1387
+ if (config.hostname == NULL) {
1388
+ config.hostname = malloc(HOST_NAME_MAX + 1);
1389
+ gethostname(config.hostname, HOST_NAME_MAX);
1390
+ }
1391
+ }
1392
+
1393
+ /* Fall back to log file if syslog is not used */
1394
+ if (config.output_syslog == 0)
1395
+ config.output_log = 1;
1396
+
1397
+ if (config.output_syslog_nxd == 0)
1398
+ config.output_log_nxd = 1;
1399
+
1400
+ /* Open log file */
1401
+ if (config.output_log) {
1402
+ if (config.logfile[0] == '-' && config.logfile[1] == '\0') {
1403
+ config.logfile_fd = stdout;
1404
+ }
1405
+ else {
1406
+ config.logfile_fd = fopen(config.logfile, "a");
1407
+ if (config.logfile_fd == NULL) {
1408
+ elog("[!] Error opening log file %s\n", config.logfile);
1409
+ exit(1);
1410
+ }
1411
+ }
1412
+ }
1413
+
1414
+ /* Open NXDOMAIN log file */
1415
+ if (config.output_log_nxd) {
1416
+ if (config.output_log && strcmp(config.logfile, config.logfile_nxd) == 0) {
1417
+ config.logfile_all = 1;
1418
+ }
1419
+ else if (config.logfile_nxd[0] == '-' && config.logfile_nxd[1] == '\0') {
1420
+ config.logfile_nxd_fd = stdout;
1421
+ }
1422
+ else {
1423
+ config.logfile_nxd_fd = fopen(config.logfile_nxd, "a");
1424
+ if (config.logfile_nxd_fd == NULL) {
1425
+ elog("[!] Error opening NXDOMAIN log file %s\n", config.logfile_nxd);
1426
+ exit(1);
1427
+ }
1428
+ }
1429
+ }
1430
+
1431
+ show_version();
1432
+
1433
+ #ifdef HAVE_PFRING
1434
+ if (config.use_pfring) {
1435
+ /* PF_RING does not have an option to read PCAP files */
1436
+ if (config.pcap_file) {
1437
+ elog("[!] Reading PCAP files are not supported when using PF_RING\n");
1438
+ exit(1);
1439
+ }
1440
+
1441
+ if (config.dev == NULL) {
1442
+ elog("[!] Must specify capture NIC\n");
1443
+ exit(1);
1444
+ }
1445
+
1446
+ flags |= PF_RING_PROMISC;
1447
+ config.pfhandle = pfring_open(config.dev, SNAPLENGTH, flags);
1448
+
1449
+ if (config.pfhandle == NULL) {
1450
+ elog("[!] Could not start PF_RING capture\n");
1451
+ exit(1);
1452
+ }
1453
+
1454
+ config.linktype = DLT_EN10MB;
1455
+ pfring_set_application_name(config.pfhandle, "passivedns");
1456
+
1457
+ if (config.cluster_id == 0)
1458
+ config.cluster_id = 99; /* Default cluster_id */
1459
+
1460
+ /* Don't add ring to cluster when using ZC or DNA */
1461
+ if ((strncmp(config.dev, "zc", 2) != 0) && (strncmp(config.dev, "dna", 3)) != 0) {
1462
+ if ((pfring_set_cluster(config.pfhandle, config.cluster_id,
1463
+ cluster_per_flow)) != 0) {
1464
+ elog("[!] Could not set PF_RING cluster_id\n");
1465
+ }
1466
+ }
1467
+
1468
+ #ifdef HAVE_PFRING_BPF
1469
+ if (*config.bpff != '\0') {
1470
+ if ((pfring_set_bpf_filter(config.pfhandle, config.bpff)) != 0) {
1471
+ elog("[!] Unable to set bpf filter\n");
1472
+ }
1473
+ }
1474
+ #endif /* HAVE_PFRING_BPF */
1475
+
1476
+ if ((pfring_enable_ring(config.pfhandle)) != 0) {
1477
+ elog("[!] Could not enable ring\n");
1478
+ exit(1);
1479
+ }
1480
+
1481
+ if (config.chroot_dir) {
1482
+ olog("[*] Chrooting to dir '%s'..\n", config.chroot_dir);
1483
+ if (set_chroot()) {
1484
+ elog("[!] failed to chroot\n");
1485
+ exit(1);
1486
+ }
1487
+ }
1488
+
1489
+ if (config.drop_privs_flag) {
1490
+ olog("[*] Dropping privs...\n");
1491
+ drop_privs();
1492
+ }
1493
+
1494
+ if (daemon) {
1495
+ if (!is_valid_path(config.pidfile))
1496
+ elog("[*] Unable to create pidfile '%s'\n", config.pidfile);
1497
+ openlog("passivedns", LOG_PID | LOG_CONS, LOG_DAEMON);
1498
+ olog("[*] Daemonizing...\n\n");
1499
+ daemonize();
1500
+ }
1501
+
1502
+ alarm(TIMEOUT);
1503
+ olog("[*] Device: %s\n", config.dev);
1504
+ olog("[*] Sniffing...\n\n");
1505
+
1506
+ pfring_loop(config.pfhandle, pfring_got_packet, (u_char*)NULL, 1);
1507
+
1508
+ game_over();
1509
+ return 0;
1510
+ }
1511
+ #endif /* HAVE_PFRING */
1512
+
1513
+ if (config.pcap_file) {
1514
+ /* Read from PCAP file specified by '-r' switch. */
1515
+ olog("[*] Reading from file %s\n\n", config.pcap_file);
1516
+ if (!(config.handle = pcap_open_offline(config.pcap_file, config.errbuf))) {
1517
+ elog("[*] Unable to open %s. (%s)", config.pcap_file, config.errbuf);
1518
+ }
1519
+
1520
+ }
1521
+ else {
1522
+ /* Look up an available device if non specified */
1523
+ if (config.dev == 0x0) {
1524
+ pcap_if_t *alldevs;
1525
+ if (0 != pcap_findalldevs(&alldevs, config.errbuf)) {
1526
+ elog("[*] Error pcap_findalldevs: %s \n", config.errbuf);
1527
+ exit(1);
1528
+ }
1529
+ config.dev = strdup(alldevs[0].name);
1530
+ pcap_freealldevs(alldevs);
1531
+ }
1532
+ olog("[*] Device: %s\n", config.dev);
1533
+
1534
+ if ((config.handle = pcap_open_live(config.dev, SNAPLENGTH, config.promisc, 500,
1535
+ config.errbuf)) == NULL) {
1536
+ elog("[*] Error pcap_open_live: %s \n", config.errbuf);
1537
+ exit(1);
1538
+ }
1539
+
1540
+ if (strlen(config.errbuf) > 0) {
1541
+ /* Fix to enable passivedns to run in an OpenVZ container */
1542
+ if (strcmp(config.errbuf, "arptype 65535 not supported by libpcap - falling back to cooked socket") == 0) {
1543
+ olog("[*] %s \n", config.errbuf);
1544
+ }
1545
+ else {
1546
+ elog("[*] Error errbuf: %s \n", config.errbuf);
1547
+ exit(1);
1548
+ }
1549
+ }
1550
+
1551
+ if (config.chroot_dir) {
1552
+ olog("[*] Chrooting to dir '%s'..\n", config.chroot_dir);
1553
+ if(set_chroot()){
1554
+ elog("[!] failed to chroot\n");
1555
+ exit(1);
1556
+ }
1557
+ }
1558
+
1559
+ if (config.drop_privs_flag) {
1560
+ olog("[*] Dropping privs...\n");
1561
+ drop_privs();
1562
+ }
1563
+
1564
+ if (daemon) {
1565
+ if (!is_valid_path(config.pidfile))
1566
+ elog("[*] Unable to create pidfile '%s'\n", config.pidfile);
1567
+ openlog("passivedns", LOG_PID | LOG_CONS, LOG_DAEMON);
1568
+ olog("[*] Daemonizing...\n\n");
1569
+ daemonize();
1570
+ }
1571
+
1572
+ }
1573
+
1574
+ if (config.handle == NULL) {
1575
+ game_over();
1576
+ return 1;
1577
+ }
1578
+
1579
+ config.linktype = pcap_datalink(config.handle);
1580
+
1581
+ /* Segfaults on empty pcap! */
1582
+ if ((pcap_compile(config.handle, &config.cfilter, config.bpff, 1,
1583
+ config.net_mask)) == -1) {
1584
+ elog("[*] Error pcap_compile user_filter: %s\n",
1585
+ pcap_geterr(config.handle));
1586
+ exit(1);
1587
+ }
1588
+
1589
+ if (pcap_setfilter(config.handle, &config.cfilter)) {
1590
+ olog("[*] Unable to set pcap filter! %s",
1591
+ pcap_geterr(config.handle));
1592
+ }
1593
+
1594
+ alarm(TIMEOUT);
1595
+
1596
+ if (!config.pcap_file) olog("[*] Sniffing...\n\n");
1597
+
1598
+ pcap_loop(config.handle, -1, got_packet, NULL);
1599
+
1600
+ game_over();
1601
+ return 0;
1602
+ }
1603
+
dns_tunneling/passivedns-master/src/passivedns.h ADDED
@@ -0,0 +1,580 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ ** This file is a part of PassiveDNS.
3
+ **
4
+ ** Copyright (C) 2010-2013, Edward Fjellskål <edwardfjellskaal@gmail.com>
5
+ **
6
+ ** This program is free software; you can redistribute it and/or modify
7
+ ** it under the terms of the GNU General Public License as published by
8
+ ** the Free Software Foundation; either version 2 of the License, or
9
+ ** (at your option) any later version.
10
+ **
11
+ ** This program is distributed in the hope that it will be useful,
12
+ ** but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ ** GNU General Public License for more details.
15
+ **
16
+ ** You should have received a copy of the GNU General Public License
17
+ ** along with this program; if not, write to the Free Software
18
+ ** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19
+ **
20
+ */
21
+
22
+ /* I N C L U D E S **********************************************************/
23
+ #include "config.h"
24
+
25
+ #ifdef HAVE_PFRING
26
+ #include <pfring.h>
27
+ #endif /* HAVE_PFRING */
28
+
29
+ /* D E F I N E S ************************************************************/
30
+ #define TIMEOUT 60
31
+ #define BUCKET_SIZE 65537
32
+ #define SNAPLENGTH 1600
33
+ #define PKT_MAXPAY 255
34
+ #define MAX_BYTE_CHECK 500000
35
+ #define MAX_PKT_CHECK 10
36
+ #define TCP_TIMEOUT 300 /* When idle IP connections should be timed out */
37
+ #define UDP_TIMEOUT 60
38
+ #define ICMP_TIMEOUT 60
39
+ #define OTHER_TIMEOUT 300
40
+
41
+ #define ETHERNET_TYPE_IP 0x0800
42
+ #define ETHERNET_TYPE_IPV6 0x86dd
43
+
44
+ #define ETHERNET_TYPE_8021Q 0x8100
45
+ #define ETHERNET_TYPE_802Q1MT 0x9100
46
+ #define ETHERNET_TYPE_802Q1MT2 0x9200
47
+ #define ETHERNET_TYPE_802Q1MT3 0x9300
48
+ #define ETHERNET_TYPE_8021AD 0x88a8
49
+
50
+ #define IP_PROTO_ICMP 1
51
+ #define IP_PROTO_TCP 6
52
+ #define IP_PROTO_UDP 17
53
+ #define IP_PROTO_IP6 41
54
+ #define IP6_PROTO_ICMP 58
55
+
56
+ #define SLL_HDR_LEN 16
57
+ #define LOOPBACK_HDR_LEN 4
58
+ #define IP4_HEADER_LEN 20
59
+ #define IP6_HEADER_LEN 40
60
+ #define TCP_HEADER_LEN 20
61
+ #define UDP_HEADER_LEN 8
62
+ #define MAC_ADDR_LEN 6
63
+ #define ETHERNET_HEADER_LEN 14
64
+ #define ETHERNET_8021Q_HEADER_LEN 18
65
+ #define ETHERNET_802Q1MT_HEADER_LEN 22
66
+
67
+ #define IP_PROTO_TCP 6
68
+ #define IP_PROTO_UDP 17
69
+ #define IP_PROTO_IP6 41
70
+ #define IP_PROTO_IP4 94
71
+
72
+ #define TF_FIN 0x01
73
+ #define TF_SYN 0x02
74
+ #define TF_RST 0x04
75
+ #define TF_PUSH 0x08
76
+ #define TF_ACK 0x10
77
+ #define TF_URG 0x20
78
+ #define TF_ECE 0x40
79
+ #define TF_CWR 0x80
80
+
81
+ #define SUCCESS 0
82
+ #define ERROR 1
83
+ #define STDBUF 1024
84
+
85
+ #define BPFF "port 53" /* Default BPF filter */
86
+
87
+ #if defined(__FreeBSD__) || defined(__APPLE__)
88
+ #define s6_addr32 __u6_addr.__u6_addr32
89
+ #endif /* __FreeBSD__ or __APPLE__ */
90
+
91
+ #ifndef HOST_NAME_MAX
92
+ #if defined(__APPLE__)
93
+ #define HOST_NAME_MAX 255
94
+ #else
95
+ #define HOST_NAME_MAX 64
96
+ #endif /* __APPLE__ */
97
+ #endif /* HOST_NAME_MAX */
98
+
99
+ /* D A T A S T R U C T U R E S *********************************************/
100
+
101
+ /*
102
+ * Ethernet header
103
+ */
104
+
105
+ typedef struct _ether_header {
106
+ u_char ether_dst[6]; /* Destination MAC */
107
+ u_char ether_src[6]; /* Source MAC */
108
+
109
+ union
110
+ {
111
+ struct etht
112
+ {
113
+ u_short ether_type; /* Ethernet type (normal) */
114
+ } etht;
115
+
116
+ struct qt
117
+ {
118
+ u_short eth_t_8021; /* Ethernet type/802.1Q tag */
119
+ u_short eth_t_8_vid;
120
+ u_short eth_t_8_type;
121
+ } qt;
122
+
123
+ struct qot
124
+ {
125
+ u_short eth_t_80212; /* Ethernet type/802.1QinQ */
126
+ u_short eth_t_82_mvid;
127
+ u_short eth_t_82_8021;
128
+ u_short eth_t_82_vid;
129
+ u_short eth_t_82_type;
130
+ } qot;
131
+ } vlantag;
132
+
133
+ #define eth_ip_type vlantag.etht.ether_type
134
+
135
+ #define eth_8_type vlantag.qt.eth_t_8021
136
+ #define eth_8_vid vlantag.qt.eth_t_8_vid
137
+ #define eth_8_ip_type vlantag.qt.eth_t_8_type
138
+
139
+ #define eth_82_type vlantag.qot.eth_t_80212
140
+ #define eth_82_mvid vlantag.qot.eth_t_82_mvid
141
+ #define eth_82_8021 vlantag.qot.eth_t_82_8021
142
+ #define eth_82_vid vlantag.qot.eth_t_82_vid
143
+ #define eth_82_ip_type vlantag.qot.eth_t_82_type
144
+
145
+ } ether_header;
146
+
147
+ typedef struct _arphdr {
148
+ uint16_t ar_hrd; /* Format of hardware address */
149
+ uint16_t ar_pro; /* Format of protocol address */
150
+ uint8_t ar_hln; /* Length of hardware address */
151
+ uint8_t ar_pln; /* Length of protocol address */
152
+ uint16_t ar_op; /* ARP opcode (command) */
153
+ } arphdr;
154
+
155
+ typedef struct _ether_arp {
156
+ arphdr ea_hdr; /* Fixed-size header */
157
+ uint8_t arp_sha[MAC_ADDR_LEN]; /* Sender hardware address */
158
+ uint8_t arp_spa[4]; /* Sender protocol address */
159
+ uint8_t arp_tha[MAC_ADDR_LEN]; /* Target hardware address */
160
+ uint8_t arp_tpa[4]; /* Target protocol address */
161
+ } ether_arp;
162
+
163
+ /*
164
+ * IPv4 header
165
+ */
166
+
167
+ typedef struct _ip4_header {
168
+ uint8_t ip_vhl; /* Version << 4 | header length >> 2 */
169
+ uint8_t ip_tos; /* Type of service */
170
+ uint16_t ip_len; /* Total length */
171
+ uint16_t ip_id; /* Identification */
172
+ uint16_t ip_off; /* Fragment offset field */
173
+ uint8_t ip_ttl; /* Time to live */
174
+ uint8_t ip_p; /* Protocol */
175
+ uint16_t ip_csum; /* Checksum */
176
+ uint32_t ip_src; /* Source address */
177
+ uint32_t ip_dst; /* Destination address */
178
+ } ip4_header;
179
+
180
+ #define IP_RF 0x8000 /* Reserved fragment flag */
181
+ #define IP_DF 0x4000 /* Don't fragment flag */
182
+ #define IP_MF 0x2000 /* More fragments flag */
183
+ #define IP_OFFMASK 0x1fff /* Mask for fragmenting bits */
184
+ #define IP_HL(ip4_header) (((ip4_header)->ip_vhl) & 0x0f)
185
+ #define IP_V(ip4_header) (((ip4_header)->ip_vhl) >> 4)
186
+
187
+ /*
188
+ * IPv6 header
189
+ */
190
+
191
+ typedef struct _ip6_header {
192
+ uint32_t vcl; /* Version, class, and label */
193
+ uint16_t len; /* Length of the payload */
194
+ uint8_t next; /* Next header
195
+ * Uses the same flags as
196
+ * the IPv4 protocol field */
197
+ uint8_t hop_lmt; /* Hop limit */
198
+ struct in6_addr ip_src; /* Source address */
199
+ struct in6_addr ip_dst; /* Destination address */
200
+ } ip6_header;
201
+
202
+ /*
203
+ * TCP header
204
+ */
205
+
206
+ typedef struct _tcp_header {
207
+ uint16_t src_port; /* Source port */
208
+ uint16_t dst_port; /* Destination port */
209
+ uint32_t t_seq; /* Sequence number */
210
+ uint32_t t_ack; /* Acknowledgement number */
211
+ uint8_t t_offx2; /* Data offset, rsvd */
212
+ uint8_t t_flags; /* TCP flags */
213
+ uint16_t t_win; /* Window */
214
+ uint16_t t_csum; /* Checksum */
215
+ uint16_t t_urgp; /* Urgent pointer */
216
+ } tcp_header;
217
+
218
+ #define TCP_OFFSET(tcp_header) (((tcp_header)->t_offx2 & 0xf0) >> 4)
219
+ #define TCP_X2(tcp_header) ((tcp_header)->t_offx2 & 0x0f)
220
+ #define TCP_ISFLAGSET(tcp_header, flags) (((tcp_header)->t_flags & (flags)) == (flags))
221
+
222
+ /*
223
+ * UDP header
224
+ */
225
+
226
+ typedef struct _udp_header {
227
+ uint16_t src_port; /* Source port */
228
+ uint16_t dst_port; /* Destination port */
229
+ uint16_t len; /* Length of the payload */
230
+ uint16_t csum; /* Checksum */
231
+ } udp_header;
232
+
233
+ /*
234
+ * Structure for connections
235
+ */
236
+
237
+ typedef struct _connection {
238
+ struct _connection *prev;
239
+ struct _connection *next;
240
+ time_t start_time; /* Connection start time */
241
+ time_t last_pkt_time; /* Last seen packet time */
242
+ uint64_t cxid; /* Connection ID */
243
+ uint8_t reversed; /* 1 if the connection is reversed */
244
+ uint32_t af; /* IP version (4/6) AF_INET */
245
+ uint8_t proto; /* IP protocol type */
246
+ struct in6_addr s_ip; /* Source address */
247
+ struct in6_addr d_ip; /* Destination address */
248
+ uint16_t s_port; /* Source port */
249
+ uint16_t d_port; /* Destination port */
250
+ uint64_t s_total_pkts; /* Total source packets */
251
+ uint64_t s_total_bytes; /* Total source bytes */
252
+ uint64_t d_total_pkts; /* Total destination packets */
253
+ uint64_t d_total_bytes; /* Total destination bytes */
254
+ uint8_t s_tcpFlags; /* TCP flags sent by source */
255
+ uint8_t d_tcpFlags; /* TCP flags sent by destination */
256
+ uint8_t check; /* Flags specifying checking */
257
+ uint16_t plid; /* Protocol layer ID (DNS TID) */
258
+ } connection;
259
+ #define CXT_DONT_CHECK_SERVER 0x01 /* Don't check server packets */
260
+ #define CXT_DONT_CHECK_CLIENT 0x02 /* Don't check client packets */
261
+ #define CXT_SERVICE_DONT_CHECK 0x04 /* Don't check payload from server */
262
+ #define CXT_CLIENT_DONT_CHECK 0x08 /* Don't check payload from client */
263
+ #define CXT_SERVICE_UNKNOWN_SET 0x10 /* If service is set as unknown */
264
+ #define CXT_CLIENT_UNKNOWN_SET 0x20 /* If client is set as unknown */
265
+
266
+ #define ISSET_CXT_DONT_CHECK_CLIENT(pi) (pi->cxt->check & CXT_DONT_CHECK_CLIENT)
267
+ #define ISSET_CXT_DONT_CHECK_SERVER(pi) (pi->cxt->check & CXT_DONT_CHECK_SERVER)
268
+ #define ISSET_DONT_CHECK_SERVICE(pi) (pi->cxt->check & CXT_SERVICE_DONT_CHECK)
269
+ #define ISSET_DONT_CHECK_CLIENT(pi) (pi->cxt->check & CXT_CLIENT_DONT_CHECK)
270
+ #define ISSET_SERVICE_UNKNOWN(pi) (pi->cxt->check & CXT_SERVICE_UNKNOWN_SET)
271
+ #define ISSET_CLIENT_UNKNOWN(pi) (pi->cxt->check & CXT_CLIENT_UNKNOWN_SET)
272
+
273
+ #ifdef BSD_DERIVED
274
+ // sidds darwin ports
275
+ #define IP4ADDR(ip) (ip)->__u6_addr.__u6_addr32[0]
276
+
277
+ #define CMP_ADDR6(a1,a2) \
278
+ (((a1)->__u6_addr.__u6_addr32[3] == (a2)->__u6_addr.__u6_addr32[3] && \
279
+ (a1)->__u6_addr.__u6_addr32[2] == (a2)->__u6_addr.__u6_addr32[2] && \
280
+ (a1)->__u6_addr.__u6_addr32[1] == (a2)->__u6_addr.__u6_addr32[1] && \
281
+ (a1)->__u6_addr.__u6_addr32[0] == (a2)->__u6_addr.__u6_addr32[0]))
282
+
283
+ // The reason why we can't get rid of pi->s6_addr32
284
+ #define CMP_ADDR4(a1,a2) \
285
+ (((a1)->__u6_addr.__u6_addr32[0] == (a2)))
286
+ #define CMP_ADDRA(a1,a2) \
287
+ (((a1)->__u6_addr.__u6_addr32[0] == (a2)->__u6_addr.__u6_addr32[0]))
288
+
289
+ #define CMP_PORT(p1,p2) \
290
+ ((p1 == p2))
291
+ #else
292
+ #define IP6ADDR0(ip) ((ip)->s6_addr32[0])
293
+ #define IP6ADDR1(ip) ((ip)->s6_addr32[1])
294
+ #define IP6ADDR2(ip) ((ip)->s6_addr32[2])
295
+ #define IP6ADDR3(ip) ((ip)->s6_addr32[3])
296
+ #define IP6ADDR(ip) \
297
+ IP6ADDR0(ip), IP6ADDR1(ip), IP6ADDR2(ip), IP6ADDR3(ip)
298
+
299
+ #define IP4ADDR(ip) ((ip)->s6_addr32[0])
300
+
301
+ #define CMP_ADDR6(a1,a2) \
302
+ (((a1)->s6_addr32[3] == (a2)->s6_addr32[3] && \
303
+ (a1)->s6_addr32[2] == (a2)->s6_addr32[2] && \
304
+ (a1)->s6_addr32[1] == (a2)->s6_addr32[1] && \
305
+ (a1)->s6_addr32[0] == (a2)->s6_addr32[0]))
306
+
307
+ // The reason why we can't get rid of pi->s6_addr32
308
+ // apples and apples
309
+ #define CMP_ADDR4A(a1,a2) \
310
+ ((a1)->s6_addr32[0] == (a2)->s6_addr32[0])
311
+ // apples and oranges
312
+ #define CMP_ADDR4(apple,orange) \
313
+ (((apple)->s6_addr32[0] == (orange)))
314
+ #define CMP_PORT(p1,p2) \
315
+ ((p1 == p2))
316
+ #endif /* OSX */
317
+
318
+ /* Since two or more connections can have the same hash key, we need to
319
+ * compare the connections with the current hash key. */
320
+ #define CMP_CXT4(cxt1, src, sp, dst, dp) \
321
+ (( \
322
+ CMP_PORT((cxt1)->s_port, (sp)) && \
323
+ CMP_PORT((cxt1)->d_port, (dp)) && \
324
+ CMP_ADDR4(&((cxt1)->s_ip), (src)) && \
325
+ CMP_ADDR4(&((cxt1)->d_ip), (dst)) \
326
+ ))
327
+
328
+ #define CMP_CXT6(cxt1, src, sp, dst, dp) \
329
+ ((CMP_ADDR6(&(cxt1)->s_ip, (src)) && \
330
+ CMP_ADDR6(&(cxt1)->d_ip, (dst)) && \
331
+ CMP_PORT((cxt1)->s_port, (sp)) && CMP_PORT((cxt1)->d_port, (dp))))
332
+
333
+ /* clear the address structure by setting all fields to 0 */
334
+ #ifdef BSD_DERIVED
335
+ #define CLEAR_ADDR(a) { \
336
+ (a)->__u6_addr.__u6_addr32[0] = 0; \
337
+ (a)->__u6_addr.__u6_addr32[1] = 0; \
338
+ (a)->__u6_addr.__u6_addr32[2] = 0; \
339
+ (a)->__u6_addr.__u6_addr32[3] = 0; \
340
+ }
341
+ #else
342
+ #define CLEAR_ADDR(a) { \
343
+ (a)->s6_addr32[0] = 0; \
344
+ (a)->s6_addr32[1] = 0; \
345
+ (a)->s6_addr32[2] = 0; \
346
+ (a)->s6_addr32[3] = 0; \
347
+ }
348
+ #endif
349
+
350
+ #define CXT_HASH4(src,dst,sp,dp,pr) \
351
+ ((src + dst + sp + dp + pr) % BUCKET_SIZE)
352
+
353
+ #ifndef BSD_DERIVED
354
+ #define CXT_HASH6(src,dst,sp,dp,pr) \
355
+ (( \
356
+ (src)->s6_addr32[0] + (src)->s6_addr32[1] + \
357
+ (src)->s6_addr32[2] + (src)->s6_addr32[3] + \
358
+ (dst)->s6_addr32[0] + (dst)->s6_addr32[1] + \
359
+ (dst)->s6_addr32[2] + (dst)->s6_addr32[3] + \
360
+ sp + dp + pr ) % BUCKET_SIZE)
361
+ #else
362
+ #define CXT_HASH6(src,dst,sp,dp,pr) \
363
+ (( \
364
+ (src)->__u6_addr.__u6_addr32[0] + (src)->__u6_addr.__u6_addr32[1] + \
365
+ (src)->__u6_addr.__u6_addr32[2] + (src)->__u6_addr.__u6_addr32[3] + \
366
+ (dst)->__u6_addr.__u6_addr32[0] + (dst)->__u6_addr.__u6_addr32[1] + \
367
+ (dst)->__u6_addr.__u6_addr32[2] + (dst)->__u6_addr.__u6_addr32[3] + \
368
+ sp + dp + pr ) % BUCKET_SIZE)
369
+ #endif
370
+
371
+ typedef struct _packetinfo {
372
+ /* Macro out the need for some of these
373
+ * eth_type(pi) is same as pi->eth_type, no?
374
+ * marked candidates for deletion */
375
+ const struct pcap_pkthdr *pheader; /* Libpcap packet header struct pointer */
376
+ const uint8_t *packet; /* Unsigned char pointer to raw packet */
377
+ /* Compute (all) these from packet */
378
+ uint32_t eth_hlen; /* Ethernet header length */
379
+ uint16_t mvlan; /* Metro vlan tag */
380
+ uint16_t vlan; /* VLAN tag */
381
+ uint16_t eth_type; /* Ethernet type (IPv4/IPv6/etc) */
382
+ uint32_t af; /* IP version (4/6) AF_INET */
383
+ ether_header *eth_hdr; /* Ethernet header struct pointer */
384
+ ether_arp *arph; /* ARP header struct pointer */
385
+ ip4_header *ip4; /* IPv4 header struct pointer */
386
+ ip6_header *ip6; /* IPv6 header struct pointer */
387
+ uint16_t packet_bytes; /* Length of IP payload in packet */
388
+ uint16_t s_port; /* Source port */
389
+ uint16_t d_port; /* Destination port */
390
+ uint8_t proto; /* IP protocol type */
391
+ uint8_t sc; /* SC_SERVER, SC_CLIENT or SC_UNKNOWN */
392
+ tcp_header *tcph; /* TCP header struct pointer */
393
+ udp_header *udph; /* UDP header struct pointer */
394
+ uint16_t gre_hlen; /* Length of dynamic GRE header length */
395
+ const uint8_t *end_ptr; /* Paranoid end pointer of packet */
396
+ const uint8_t *payload; /* Char pointer to transport payload */
397
+ uint32_t plen; /* Transport payload length */
398
+ uint32_t our; /* Is the asset in our defined network */
399
+ uint8_t up; /* Set if the asset has been updated */
400
+ connection *cxt; /* Pointer to the cxt for this packet */
401
+ } packetinfo;
402
+
403
+ /*
404
+ * Packetinfo accessor macros
405
+ */
406
+
407
+ #define PI_TOS(pi) ( (pi)->ip4->ip_tos )
408
+ #define PI_ECN(pi) ( (pi)->tcph->t_flags & (TF_ECE|TF_CWR) )
409
+
410
+ #define PI_IP4(pi) ((pi)->ip4)
411
+ #define PI_IP4SRC(pi) ( PI_IP4(pi)->ip_src )
412
+ #define PI_IP4DST(pi) ( PI_IP4(pi)->ip_dst )
413
+
414
+ #define PI_IP6(pi) ((pi)->ip6)
415
+ #define PI_IP6SRC(pi) (PI_IP6(pi)->ip_src)
416
+ #define PI_IP6DST(pi) (PI_IP6(pi)->ip_dst)
417
+
418
+ #define PI_TCP_SP(pi) ( ntohs((pi)->tcph->src_port))
419
+ #define PI_TCP_DP(pi) ( ntohs((pi)->tcph->dst_port))
420
+
421
+ #define SC_CLIENT 0x01 /* Pi for this session is client */
422
+ #define SC_SERVER 0x02 /* Pi for this session is server */
423
+ #define SC_UNKNOWN 0x03 /* Pi for this session is not yet known */
424
+
425
+ typedef struct _pdns_stat {
426
+ uint32_t got_packets; /* Number of packets received by program */
427
+ uint32_t eth_recv; /* Number of Ethernet packets received */
428
+ uint32_t arp_recv; /* Number of ARP packets received */
429
+ uint32_t otherl_recv; /* Number of other Link layer packets received */
430
+ uint32_t vlan_recv; /* Number of VLAN packets received */
431
+ uint32_t ip4_recv; /* Number of IPv4 packets received */
432
+ uint32_t ip6_recv; /* Number of IPv6 packets received */
433
+
434
+ uint32_t ip4_dns_udp; /* Number of IPv4 packets received */
435
+ uint32_t ip4_dec_udp_ok; /* Number of IPv4 packets received */
436
+ uint32_t ip4_dec_udp_er; /* Number of IPv4 packets received */
437
+ uint32_t ip4_dns_tcp; /* Number of IPv4 packets received */
438
+ uint32_t ip4_dec_tcp_ok; /* Number of IPv4 packets received */
439
+ uint32_t ip4_dec_tcp_er; /* Number of IPv4 packets received */
440
+ uint32_t ip4_recv_tcp; /* Number of IPv4 packets received */
441
+
442
+ uint32_t ip6_dns_udp; /* Number of IPv4 packets received */
443
+ uint32_t ip6_dec_udp_ok; /* Number of IPv4 packets received */
444
+ uint32_t ip6_dec_udp_er; /* Number of IPv4 packets received */
445
+ uint32_t ip6_dns_tcp; /* Number of IPv4 packets received */
446
+ uint32_t ip6_dec_tcp_ok; /* Number of IPv4 packets received */
447
+ uint32_t ip6_dec_tcp_er; /* Number of IPv4 packets received */
448
+ uint32_t ip6_recv_tcp; /* Number of IPv4 packets received */
449
+
450
+ uint32_t ip4ip_recv; /* Number of IP4/6 packets in IPv4 packets */
451
+ uint32_t ip6ip_recv; /* Number of IP4/6 packets in IPv6 packets */
452
+ uint32_t gre_recv; /* Number of GRE packets received */
453
+ uint32_t tcp_recv; /* Number of TCP packets received */
454
+ uint32_t udp_recv; /* Number of UDP packets received */
455
+ uint32_t icmp_recv; /* Number of ICMP packets received */
456
+ uint32_t othert_recv; /* Number of other transport layer packets received */
457
+ uint32_t dns_records; /* Total number of DNS records detected */
458
+ uint32_t dns_assets; /* Total number of DNS assets detected */
459
+ uint32_t tcp_os_assets; /* Total number of TCP os assets detected */
460
+ uint32_t udp_os_assets; /* Total number of UDP os assets detected */
461
+ uint32_t icmp_os_assets; /* Total number of ICMP os assets detected */
462
+ uint32_t dhcp_os_assets; /* Total number of DHCP os assets detected */
463
+ uint32_t tcp_services; /* Total number of TCP services detected */
464
+ uint32_t tcp_clients; /* Total number of TCP clients detected */
465
+ uint32_t udp_services; /* Total number of UDP services detected */
466
+ uint32_t udp_clients; /* Total number of TCP clients detected */
467
+ } pdns_stat;
468
+
469
+ #define CONFIG_VERBOSE 0x01
470
+ #define CONFIG_UPDATES 0x02
471
+ #define CONFIG_SYSLOG 0x04
472
+ #define CONFIG_QUIET 0x08
473
+ #define CONFIG_CONNECT 0x10
474
+ #define CONFIG_CXWRITE 0x20
475
+
476
+ #define INTERRUPT_END 0x01
477
+ #define INTERRUPT_SESSION 0x02
478
+ #define INTERRUPT_DNS 0x04
479
+
480
+ typedef struct _globalconfig {
481
+ pcap_t *handle; /* Pointer to libpcap handle */
482
+ #ifdef HAVE_PFRING
483
+ pfring *pfhandle; /* Pointer to libpfring handle */
484
+ uint8_t use_pfring; /* Use PF_RING or not */
485
+ u_int cluster_id; /* PF_RING cluster ID */
486
+ #endif /* HAVE_PFRING */
487
+ struct pcap_stat ps; /* Libpcap stats */
488
+ int linktype; /* Libpcap linktype */
489
+ pdns_stat p_s; /* PDNS stats */
490
+ struct bpf_program cfilter;
491
+ bpf_u_int32 net_mask;
492
+ uint8_t intr_flag;
493
+ uint8_t inpacket;
494
+
495
+ time_t dnslastchk; /* Timestamp for last DNS cache expiration check */
496
+ struct timeval tstamp; /* Current timestamp from packet-header */
497
+ uint8_t cflags; /* Config flags */
498
+ uint8_t verbose; /* Verbose or not */
499
+ uint8_t print_updates; /* Prints updates */
500
+ uint8_t output_log; /* Log to log file */
501
+ uint8_t output_log_nxd; /* Log NXDOMAIN to log file */
502
+ uint8_t output_syslog; /* Log to syslog */
503
+ uint8_t output_syslog_nxd; /* Log NXDOMAIN to syslog */
504
+ #ifdef HAVE_JSON
505
+ uint8_t use_json; /* Use JSON as output in log */
506
+ uint8_t use_json_nxd; /* Use JSON as output in NXDOMAIN log */
507
+ #endif /* HAVE_JSON */
508
+ uint8_t use_stats_file; /* Print stats on signal to file */
509
+ char *statsfile; /* File to print stats to */
510
+ uint8_t setfilter;
511
+ uint8_t promisc; /* set interface promisc mode */
512
+ uint8_t drop_privs_flag; /* Flag marking to drop privs */
513
+ uint8_t chroot_flag; /* Flag for going chroot */
514
+ uint8_t daemon_flag; /* Flag for going daemon */
515
+ uint8_t logfile_all; /* Log everything in the same log file */
516
+ uint32_t fieldsf; /* flags for fields to print */
517
+ uint64_t dnsf; /* Flags for DNS RR Type checks to do */
518
+ uint32_t dnsfe; /* Flags for DNS Server Error Types to check */
519
+ uint32_t payload; /* Dump how much of the payload ? */
520
+ uint32_t curcxt;
521
+ uint32_t llcxt;
522
+ uint64_t mem_limit_max; /* Try soft limit memory use */
523
+ uint64_t mem_limit_size; /* Current memory size */
524
+ uint32_t dns_records; /* Total number of DNS records in memory */
525
+ uint32_t dns_assets; /* Total number of DNS assets in memory */
526
+ uint64_t cxtrackerid; /* cxtracker ID counter */
527
+ char errbuf[PCAP_ERRBUF_SIZE];
528
+ char *hostname;
529
+ char *bpff;
530
+ char *user_filter;
531
+ char *net_ip_string;
532
+ char *log_delimiter; /* Delimiter between fields in log */
533
+ char *logfile; /* Filename of /var/log/passivedns.log */
534
+ char *logfile_nxd; /* Filename for NXDOMAIN logging /var/log/passivedns-nxd.log */
535
+ char *pcap_file; /* Filename to PCAP too read */
536
+ FILE *logfile_fd; /* File descriptor for log file */
537
+ FILE *logfile_nxd_fd; /* File descriptor for NXDOMAIN log file */
538
+ char *dev; /* Device name to use for sniffing */
539
+ char *dpath; /* ... ??? seriously ???... */
540
+ char *chroot_dir; /* Directory to chroot to */
541
+ char *group_name; /* Group to drop privileges too */
542
+ char *user_name; /* User to drop privileges too */
543
+ char *pidfile; /* Pidfile */
544
+ char *configpath; /* Path to config directory */
545
+ uint32_t dnsprinttime; /* Minimum time between printing duplicate DNS info */
546
+ uint32_t dnscachetimeout; /* Time before a DNS record/asset times out if not updated */
547
+ } globalconfig;
548
+
549
+ #define ISSET_CONFIG_VERBOSE(config) ((config).cflags & CONFIG_VERBOSE)
550
+ #define ISSET_CONFIG_UPDATES(config) ((config).cflags & CONFIG_UPDATES)
551
+ #define ISSET_CONFIG_SYSLOG(config) ((config).cflags & CONFIG_SYSLOG)
552
+ #define ISSET_CONFIG_QUIET(config) ((config).cflags & CONFIG_QUIET)
553
+
554
+ #define ISSET_INTERRUPT_END(config) ((config).intr_flag & INTERRUPT_END)
555
+ #define ISSET_INTERRUPT_SESSION(config) ((config).intr_flag & INTERRUPT_SESSION)
556
+ #define ISSET_INTERRUPT_DNS(config) ((config).intr_flag & INTERRUPT_DNS)
557
+
558
+ #define plog(fmt, ...) do{ fprintf(stdout, (fmt), ##__VA_ARGS__); }while(0)
559
+ #define flog(h, fmt, ...) \
560
+ do{ \
561
+ if (!(h == stdout && ISSET_CONFIG_QUIET(config))) \
562
+ fprintf(h, fmt, ##__VA_ARGS__); \
563
+ } \
564
+ while(0)
565
+ #define olog(fmt, ...) do{ if(!(ISSET_CONFIG_QUIET(config))) fprintf(stdout, (fmt), ##__VA_ARGS__); }while(0)
566
+ //#define DEBUG 1
567
+ #ifdef DEBUG
568
+ #define dlog(fmt, ...) do { fprintf(stderr, ("[%s:%d(%s)] " fmt), __FILE__, __LINE__, __PRETTY_FUNCTION__, ##__VA_ARGS__);} while(0)
569
+ #define vlog(v, fmt, ...) do{ if(DEBUG == v) fprintf(stderr, ("[%s:%d(%s)] " fmt), __FILE__, __LINE__, __PRETTY_FUNCTION__, ##__VA_ARGS__); }while(0)
570
+ #define elog(fmt, ...) fprintf(stderr, ("[%s:%d(%s)] " fmt), __FILE__, __LINE__, __PRETTY_FUNCTION__, ##__VA_ARGS__);
571
+ #else
572
+ #define elog(fmt, ...) fprintf(stderr, (fmt), ##__VA_ARGS__);
573
+ #define dlog(fmt, ...) do { ; } while(0)
574
+ #define vlog(fmt, ...) do { ; } while(0)
575
+ #endif
576
+
577
+ int cxt_update_client(connection *cxt, packetinfo *pi);
578
+ int cxt_update_unknown(connection *cxt, packetinfo *pi);
579
+ int cxt_update_server(connection *cxt, packetinfo *pi);
580
+
dns_tunneling/passivedns-master/tools/README.skip_white_black-list.txt ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PassiveDNS (https://github.com/gamelinux/passivedns)
2
+ # Example file for skiplist, whitelist and blacklist to be read from pdns2db.pl
3
+ # Lines starting with # are not processed.
4
+
5
+ # Example 1: STATIC DOMAINS/IPs
6
+ # work with: --skiplist, --whitelist or --blacklist
7
+ # One domain on each line. The match has to be exact.
8
+ www.google.com
9
+ www.facebook.com
10
+ www.twitter.com
11
+ 8.8.8.8
12
+ 8.8.4.4
13
+ current.cvd.clamav.net
14
+
15
+ # Example 2: PCRE formated DOMAINS/IPs
16
+ # work with: --skiplist-pcre, --whitelist-pcre or --blacklist-pcre
17
+ # One domain on each line.
18
+ \.google\.com$
19
+ \.facebook\.com$
20
+ \.twitter\.com$
21
+ antivirus
22
+ \.3322\.org$
23
+ # blacklist type of services
24
+ \.mailserveren\.com$
25
+ \.sorbs\.net$
26
+ \.spamcop\.net$
27
+ \.list\.dnswl\.org$
28
+ \.(zen|sbl|dbl)\.spamhaus\.org$
29
+ \.bb\.barracudacentral\.org$
30
+ \.mailspike\.net$
31
+ \.score\.senderscore\.com$
32
+ \.bondedsender\.org$
33
+ \.surbl\.org$
34
+ \.uribl\.com$
35
+ \.habeas\.com$
36
+ \.support-intelligence\.net$
37
+ \.in-addr\.arpa$
dns_tunneling/passivedns-master/tools/pdns2db.pl ADDED
@@ -0,0 +1,531 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/perl
2
+
3
+ # ----------------------------------------------------------------------
4
+ # PassiveDNS to DB
5
+ # Copyright (C) 2011-2012, Edward Fjellskål <edwardfjellskaal@gmail.com>
6
+ #
7
+ # This program is free software; you can redistribute it and/or modify
8
+ # it under the terms of the GNU General Public License as published by
9
+ # the Free Software Foundation; either version 2 of the License, or
10
+ # (at your option) any later version.
11
+ #
12
+ # This program is distributed in the hope that it will be useful,
13
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
+ # GNU General Public License for more details.
16
+ #
17
+ # You should have received a copy of the GNU General Public License
18
+ # along with this program; if not, write to the Free Software
19
+ # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20
+ # ----------------------------------------------------------------------
21
+
22
+ use strict;
23
+ use warnings;
24
+ use POSIX qw(setsid strftime);
25
+ use DateTime;
26
+ use Getopt::Long qw/:config auto_version auto_help/;
27
+ use DBI;
28
+
29
+ #use Data::Dumper;
30
+
31
+ =head1 NAME
32
+
33
+ pdns2db.pl - Load passive DNS data from passivedns into a DB
34
+
35
+ =head1 VERSION
36
+
37
+ 0.3
38
+
39
+ =head1 SYNOPSIS
40
+
41
+ $ pdns2db.pl [options]
42
+
43
+ OPTIONS:
44
+
45
+ --file <file> : set the file to monitor for passivedns entries (/var/log/passivedns.log)
46
+ --batch : process a file and exit when done
47
+ --skiplist <file> : file with a list of domains to skip DB insertion
48
+ --onlylist <file> : file with a list of domains to only insert into DB
49
+ --whitelist <file> : file with a list of domains to not check for in blacklist
50
+ --blacklist <file> : file with a list of domains to alert on
51
+ --skiplist-pcre <file> : file with regexp list of domains to skip DB insertion
52
+ --onlylist-pcre <file> : file with regexp list of domains to only insert into DB
53
+ --whitelist-pcre <file>: file with regexp list of domains to not check for in blacklist
54
+ --blacklist-pcre <file>: file with regexp list of domains to alert on
55
+ --alertlog <file> : file to log alerts to (/var/log/passivedns-alert.log)
56
+ --nodb : dont talk to the DB at all
57
+ --daemon : enables daemon mode
58
+ --verbose : enables some verboseness
59
+ --debug <int> : enable debug messages (default: 0 (disabled))
60
+ --help : this help message
61
+ --version : show pdns2db.pl version
62
+
63
+ =cut
64
+
65
+ our $VERSION = 0.3;
66
+ our $DEBUG = 0;
67
+ our $VERBOSE = 0;
68
+ our $DAEMON = 0;
69
+ our $TIMEOUT = 1;
70
+ my $PDNSFILE = q(/var/log/passivedns.log);
71
+ my $LOGFILE = q(/var/log/passivedns-run.log);
72
+ my $ALERTLOG = q(/var/log/passivedns-alert.log);
73
+ my $PIDFILE = q(/var/run/pdns2db.pid);
74
+ our $DB_NAME = "pdns";
75
+ our $DB_HOST = "127.0.0.1";
76
+ our $DB_PORT = "3306";
77
+ our $DB_USERNAME = "pdns";
78
+ our $DB_PASSWORD = "pdns";
79
+ our $DBI = "DBI:mysql:$DB_NAME:$DB_HOST:$DB_PORT";
80
+ our $TABLE_NAME = "pdns";
81
+ our $AUTOCOMMIT = 0;
82
+ our $BATCH = 0;
83
+ our $dbh;
84
+ our $NODB = 0;
85
+ my $DOMAIN_BLACKLIST_FILE = undef;
86
+ my $DOMAIN_BLACKLIST_FILE_PCRE = undef;
87
+ my $DOMAIN_WHITELIST_FILE = undef;
88
+ my $DOMAIN_WHITELIST_FILE_PCRE = undef;
89
+ my $DOMAIN_DBSKIPLIST_FILE = undef;
90
+ my $DOMAIN_DBSKIPLIST_FILE_PCRE = undef;
91
+ my $DOMAIN_DBONLYLIST_FILE = undef;
92
+ my $DOMAIN_DBONLYLIST_FILE_PCRE = undef;
93
+
94
+ GetOptions(
95
+ 'file=s' => \$PDNSFILE,
96
+ 'skiplist=s' => \$DOMAIN_DBSKIPLIST_FILE,
97
+ 'skiplist-pcre=s' => \$DOMAIN_DBSKIPLIST_FILE_PCRE,
98
+ 'whitelist=s' => \$DOMAIN_WHITELIST_FILE,
99
+ 'whitelist-pcre=s' => \$DOMAIN_WHITELIST_FILE_PCRE,
100
+ 'blacklist=s' => \$DOMAIN_BLACKLIST_FILE,
101
+ 'blacklist-pcre=s' => \$DOMAIN_BLACKLIST_FILE_PCRE,
102
+ 'onlylist=s' => \$DOMAIN_DBONLYLIST_FILE,
103
+ 'onlylist-pcre=s' => \$DOMAIN_DBONLYLIST_FILE_PCRE,
104
+ 'alertlog=s' => \$ALERTLOG,
105
+ 'batch' => \$BATCH,
106
+ 'nodb' => \$NODB,
107
+ 'debug=s' => \$DEBUG,
108
+ 'daemon' => \$DAEMON,
109
+ 'verbose' => \$VERBOSE,
110
+ );
111
+
112
+ our $HASH_BLACKLIST = {};
113
+ our $HASH_WHITELIST = {};
114
+ our $HASH_DBSKIPLIST= {};
115
+ our $HASH_DBONLYLIST= {};
116
+ $HASH_BLACKLIST->{'pcre'} = [load_domain_list_pcre($DOMAIN_BLACKLIST_FILE_PCRE)] if $DOMAIN_BLACKLIST_FILE_PCRE;
117
+ $HASH_BLACKLIST->{'static'} = load_domain_list_static($DOMAIN_BLACKLIST_FILE) if $DOMAIN_BLACKLIST_FILE;
118
+ $HASH_WHITELIST->{'pcre'} = [load_domain_list_pcre($DOMAIN_WHITELIST_FILE_PCRE)] if $DOMAIN_WHITELIST_FILE_PCRE;
119
+ $HASH_WHITELIST->{'static'} = load_domain_list_static($DOMAIN_WHITELIST_FILE) if $DOMAIN_WHITELIST_FILE;
120
+ $HASH_DBSKIPLIST->{'pcre'} = [load_domain_list_pcre($DOMAIN_DBSKIPLIST_FILE_PCRE)] if $DOMAIN_DBSKIPLIST_FILE_PCRE;
121
+ $HASH_DBSKIPLIST->{'static'} = load_domain_list_static($DOMAIN_DBSKIPLIST_FILE) if $DOMAIN_DBSKIPLIST_FILE;
122
+ $HASH_DBONLYLIST->{'pcre'} = [load_domain_list_pcre($DOMAIN_DBONLYLIST_FILE_PCRE)] if $DOMAIN_DBONLYLIST_FILE_PCRE;
123
+ $HASH_DBONLYLIST->{'static'} = load_domain_list_static($DOMAIN_DBONLYLIST_FILE) if $DOMAIN_DBONLYLIST_FILE;
124
+
125
+ if (($HASH_WHITELIST) && (not $HASH_BLACKLIST)){
126
+ logger("[W] Whitelist without Blacklist does not make sense!");
127
+ $HASH_WHITELIST = undef;
128
+ }
129
+
130
+ if ((not defined $HASH_DBONLYLIST->{'static'}) && (not defined $HASH_DBONLYLIST->{'pcre'})) {
131
+ # Should also check that there are any entries if they are defined.
132
+ $HASH_DBONLYLIST = undef;
133
+ }
134
+
135
+ # Signal handlers
136
+ use vars qw(%sources);
137
+ #$SIG{"HUP"} = \&recreate_merge_table;
138
+ $SIG{"INT"} = sub { game_over() };
139
+ $SIG{"TERM"} = sub { game_over() };
140
+ $SIG{"QUIT"} = sub { game_over() };
141
+ $SIG{"KILL"} = sub { game_over() };
142
+ #$SIG{"ALRM"} = sub { file_watch(); alarm $TIMEOUT; };
143
+
144
+ logger("[*] Starting pdns2db.pl");
145
+
146
+ # Prepare to meet the world of Daemons
147
+ if ( $DAEMON ) {
148
+ logger("[*] Daemonizing...");
149
+ chdir ("/") or die "chdir /: $!\n";
150
+ open (STDIN, "/dev/null") or die "open /dev/null: $!\n";
151
+ open (STDOUT, "> $LOGFILE") or die "open > $LOGFILE: $!\n";
152
+ defined (my $dpid = fork) or die "fork: $!\n";
153
+ if ($dpid) {
154
+ # Write PID file
155
+ open (PID, "> $PIDFILE") or die "open($PIDFILE): $!\n";
156
+ print PID $dpid, "\n";
157
+ close (PID);
158
+ exit 0;
159
+ }
160
+ setsid ();
161
+ open (STDERR, ">&STDOUT");
162
+ }
163
+
164
+ if ($NODB == 0) {
165
+ logger("[*] Connecting to database...");
166
+ $dbh = DBI->connect($DBI,$DB_USERNAME,$DB_PASSWORD, {RaiseError => 1, mysql_auto_reconnect=>1}) or die "$DBI::errstr";
167
+ # Setup the pdns table, if not exist
168
+ setup_db();
169
+ } else {
170
+ logger("[*] Skipping database operations...");
171
+ }
172
+
173
+ # Start file_watch() which looks for new dns data and puts them into db
174
+ logger("[*] Looking for passive DNS data in file: $PDNSFILE");
175
+ file_watch($PDNSFILE);
176
+ exit;
177
+
178
+ =head1 FUNCTIONS
179
+
180
+ =head2 setup_db
181
+
182
+ Checks if the pdns table exists, if not make it.
183
+
184
+ =cut
185
+
186
+ sub setup_db {
187
+
188
+ if (checkif_table_exist($TABLE_NAME)) {
189
+ return;
190
+ } else {
191
+ if (new_pdns_table($TABLE_NAME)) {
192
+ die "[E] Table $TABLE_NAME does not exist, and we could not create it! Sorry!\n";
193
+ }
194
+ }
195
+ }
196
+
197
+ =head2 file_watch
198
+
199
+ This sub looks for new DNS data in a file.
200
+ Takes $filename to watch as input.
201
+
202
+ =cut
203
+
204
+ sub file_watch {
205
+ my $logfile = shift;
206
+ my $startsize = 0;
207
+ my $pos = 0;
208
+ #infinite loop
209
+ while (1) {
210
+ $startsize = (stat $logfile)[7];
211
+
212
+ if (!defined $startsize) {
213
+ # No such file (Log rotate?)
214
+ sleep $TIMEOUT;
215
+ next;
216
+ }
217
+
218
+ if (!defined $pos) {
219
+ # Initial run.
220
+ $pos = $startsize;
221
+ }
222
+
223
+ if ($startsize < $pos) {
224
+ # Log rotated
225
+ #parseLogfile ($rotlogfile, $pos, (stat $rotlogfile)[7]);
226
+ $pos = 0;
227
+ }
228
+
229
+ parseLogfile ($logfile, $pos, $startsize);
230
+ $pos = $startsize;
231
+
232
+ if ($BATCH == 1) {
233
+ logger("[*] Processing of $logfile is done, exiting!");
234
+ exit 0;
235
+ }
236
+ sleep $TIMEOUT;
237
+ }
238
+ }
239
+
240
+ sub parseLogfile {
241
+ my ($fname, $start, $stop) = @_;
242
+ open (LOGFILE, $fname) or exit 3;
243
+ seek (LOGFILE, $start, 0) or exit 2;
244
+
245
+ LINE:
246
+ while (tell (LOGFILE) < $stop) {
247
+ my $line =<LOGFILE>;
248
+ chomp ($line);
249
+ my $wret = 0;
250
+ my $bret = 0;
251
+ my $sret = 0;
252
+
253
+ my @elements = split(/\|\|/,$line);
254
+ unless(@elements == 9) {
255
+ logger("[W] Not valid Nr. of args in format: '$fname'");
256
+ next LINE;
257
+ }
258
+
259
+ my ($tst, $cip, $sip, $rr, $query, $type, $answer, $ttl, $count) = @elements;
260
+ $query =~ s/^(.*)\.$/$1/;
261
+ $answer =~ s/^(.*)\.$/$1/;
262
+
263
+ if (($HASH_DBSKIPLIST) && ($sret = match_domain($query, $answer, $HASH_DBSKIPLIST))) {
264
+ logger("[*] Domain marked to skip DB insertion: $query or $answer") if $VERBOSE;
265
+ next LINE;
266
+ }
267
+
268
+ if (($HASH_WHITELIST) && ($HASH_BLACKLIST) &&($wret = match_domain($query, $answer, $HASH_WHITELIST))) {
269
+ logger("[*] Whitelisted domain: $query or $answer") if $VERBOSE;
270
+ } elsif (($HASH_BLACKLIST) && ($bret = match_domain($query, $answer, $HASH_BLACKLIST))) {
271
+ logger("[*] Blacklisted domain: $query or $answer") if $VERBOSE;
272
+ if (open (ALOG, ">> $ALERTLOG") ) {
273
+ print ALOG $line, "\n";
274
+ close (ALOG);
275
+ } else {
276
+ logger("[W] Problems with open($ALERTLOG): $!");
277
+ }
278
+ }
279
+
280
+ if (($HASH_DBONLYLIST) && ($sret = match_domain($query, $answer, $HASH_DBONLYLIST))) {
281
+ logger("[*] Onlylisted domain: $query or $answer") if $VERBOSE;
282
+ put_dns_to_db(@elements) if $NODB == 0;
283
+ } elsif (not defined $HASH_DBONLYLIST) {
284
+ put_dns_to_db(@elements) if $NODB == 0;
285
+ } else {
286
+ put_dns_to_db(@elements) if $NODB == 0;
287
+ }
288
+ }
289
+ close(LOGFILE);
290
+ }
291
+
292
+ sub put_dns_to_db {
293
+ # 1322849924.123456||192.168.1.1||8.8.8.8||IN||www.adobe.com.||CNAME||www.wip4.adobe.com.||3600||22
294
+ # 1322849924.123456||192.168.1.1||8.8.8.8||IN||www.adobe.com.||A||193.104.215.61||600||11
295
+ my ($tst, $cip, $sip, $rr, $query, $type, $answer, $ttl, $count) = @_;
296
+ my ($ts, $tsu) = split(/\./,$tst);
297
+ my $tsl = $ts;
298
+
299
+ $query =~ s/^(.*)\.$/$1/; # Strip trailing dot
300
+ $answer =~ s/^(.*)\.$/$1/; # Strip trailing dot
301
+ $query =~ s/(')/\\$1/g; # Wash "user-input" for non-friendly sql chars
302
+ $answer =~ s/(')/\\$1/g; # Wash "user-input" for non-friendly sql chars
303
+
304
+ my ($sql, $sth);
305
+
306
+ eval{
307
+ $sql = qq[
308
+ INSERT INTO $TABLE_NAME (
309
+ QUERY,RR,MAPTYPE,ANSWER,TTL,COUNT,LAST_SEEN,FIRST_SEEN
310
+ ) VALUES (
311
+ '$query','$rr','$type','$answer','$ttl','$count',FROM_UNIXTIME($ts),FROM_UNIXTIME($tsl)
312
+ ) ON DUPLICATE KEY UPDATE
313
+ TTL = if (TTL < $ttl, $ttl, TTL),
314
+ COUNT = COUNT + '$count',
315
+ LAST_SEEN = if (LAST_SEEN < FROM_UNIXTIME($ts), FROM_UNIXTIME($ts), LAST_SEEN),
316
+ FIRST_SEEN = if (FIRST_SEEN > FROM_UNIXTIME($ts), FROM_UNIXTIME($ts), FIRST_SEEN)
317
+ ];
318
+ logger("[D] $sql") if $DEBUG > 1;
319
+ $sth = $dbh->prepare($sql);
320
+ $sth->execute;
321
+ $sth->finish;
322
+ };
323
+ if ($@) {
324
+ # Failed
325
+ return 1;
326
+ }
327
+ return 0;
328
+ }
329
+
330
+ =head2 new_pdns_table
331
+
332
+ Creates a new pdns table.
333
+ Takes $tablename as input.
334
+
335
+ =cut
336
+
337
+ sub new_pdns_table {
338
+ my ($tablename) = shift;
339
+ my ($sql, $sth);
340
+ logger("[*] Creating $TABLE_NAME...");
341
+ eval{
342
+ $sql = " \
343
+ CREATE TABLE IF NOT EXISTS $tablename \
344
+ ( \
345
+ ID BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, \
346
+ QUERY varchar(255) NOT NULL DEFAULT '', \
347
+ MAPTYPE varchar(10) NOT NULL DEFAULT '', \
348
+ RR varchar(10) NOT NULL DEFAULT '', \
349
+ ANSWER varchar(255) NOT NULL DEFAULT '', \
350
+ TTL int(10) NOT NULL DEFAULT '0', \
351
+ COUNT BIGINT(20) UNSIGNED NOT NULL DEFAULT '1', \
352
+ FIRST_SEEN DATETIME NOT NULL, \
353
+ LAST_SEEN DATETIME NOT NULL, \
354
+ PRIMARY KEY (ID), \
355
+ UNIQUE KEY MARQ (MAPTYPE,ANSWER,RR,QUERY), \
356
+ KEY query_idx (QUERY), \
357
+ KEY answer_idx (ANSWER) \
358
+ ) \
359
+ ";
360
+ $sth = $dbh->prepare($sql);
361
+ $sth->execute;
362
+ $sth->finish;
363
+ };
364
+ if ($@) {
365
+ # Failed
366
+ return 1;
367
+ }
368
+ return 0;
369
+ }
370
+
371
+
372
+ =head2 checkif_table_exist
373
+
374
+ Checks if a table exists. Takes $tablename as input and
375
+ returns 1 if $tablename exists, and 0 if not.
376
+
377
+ =cut
378
+
379
+ sub checkif_table_exist {
380
+ my $tablename = shift;
381
+ my ($sql, $sth);
382
+ eval {
383
+ $sql = "select count(*) from pdns where 1=0";
384
+ $dbh->do($sql);
385
+ };
386
+ if ($dbh->err) {
387
+ logger("[D] Table $tablename does not exist.") if $DEBUG;
388
+ return 0;
389
+ }
390
+ else{
391
+ return 1;
392
+ }
393
+ }
394
+
395
+ =head2 load_domain_list
396
+
397
+ Loads domains from file
398
+
399
+ File format:
400
+ <domain written in regexp>
401
+
402
+ Example:
403
+ ^news\..*daily\.com$
404
+
405
+ =cut
406
+
407
+ sub load_domain_list_pcre {
408
+ my $file = shift;
409
+ my %signatures;
410
+ my $cnt = 0;
411
+
412
+ open(my $FH, "<", $file) or die "[E] Could not open '$file': $!";
413
+
414
+ LINE:
415
+ while (my $line = readline $FH) {
416
+ chomp $line;
417
+ $line =~ s/\#.*//;
418
+ $line =~ s/\t//g;
419
+ $line =~ s/ //g;
420
+ next LINE unless($line); # empty line
421
+ # One should check for a more or less sane signature file.
422
+
423
+ logger("[D] $line") if $DEBUG;
424
+ $signatures{$line} = [qr{$line}];
425
+ $cnt++;
426
+ }
427
+ logger("[D] Loaded $cnt domains") if $DEBUG;
428
+
429
+ return map { $signatures{$_} }
430
+ sort { length $b <=> length $a }
431
+ keys %signatures;
432
+ }
433
+
434
+ sub load_domain_list_static {
435
+ my $file = shift;
436
+ my $signatures = {};
437
+ my $cnt = 0;
438
+
439
+ open(my $FH, "<", $file) or die "[E] Could not open '$file': $!";
440
+
441
+ LINE:
442
+ while (my $line = readline $FH) {
443
+ chomp $line;
444
+ $line =~ s/\#.*//;
445
+ $line =~ s/\t//g;
446
+ $line =~ s/ //g;
447
+ next LINE unless($line); # empty line
448
+ # One should check for a more or less sane signature file.
449
+
450
+ logger("[D] $line") if $DEBUG;
451
+ $signatures->{"$line"} = 1;
452
+ $cnt++;
453
+ }
454
+ logger("[D] Loaded $cnt static domains") if $DEBUG;
455
+
456
+ return $signatures;
457
+ }
458
+
459
+ =head2 match_domain
460
+
461
+ Takes input: $domain, $@domain_list_to_match_on
462
+ Returns 1 if found, 0 if not.
463
+
464
+ =cut
465
+
466
+ sub match_domain {
467
+ my ($query, $answer, $MHASH) = @_;
468
+
469
+ # First we should match agains "static" domain list.
470
+ if ($MHASH->{'static'}->{"$query"}) {
471
+ logger("[D] Domain $query match on static query domain: $query") if $DEBUG;
472
+ return 1;
473
+ } elsif ($MHASH->{'static'}->{"$answer"}) {
474
+ logger("[D] Domain $answer match on static answer domain: $answer") if $DEBUG;
475
+ return 1;
476
+ } else {
477
+ logger("[D] No static match on domain: $query or $answer") if $DEBUG;
478
+ }
479
+
480
+ # Check domain against domains in expensive pcre list
481
+ my $CRAP = $MHASH->{'pcre'};
482
+ for my $s (@$CRAP) {
483
+ my $re = $s->[0];
484
+ if ($query =~ /$re/) {
485
+ logger("[D] Domain $query match on pcre: $re") if $DEBUG;
486
+ return 1;
487
+ } elsif ($answer =~ /$re/) {
488
+ logger("[D] Domain $answer match on pcre: $re") if $DEBUG;
489
+ return 1;
490
+ }
491
+ }
492
+
493
+ logger("[D] No pcre match on domain: $query or $answer") if $DEBUG;
494
+ return 0;
495
+ }
496
+
497
+ =head2 logger
498
+
499
+ Adds time prefix to logg output. Takes $msg as input.
500
+
501
+ =cut
502
+
503
+ sub logger {
504
+ my $msg = shift;
505
+ print strftime('%F %H:%M:%S', localtime), " $msg\n";
506
+ }
507
+ =head2 game_over
508
+
509
+ Terminates the program in a sainfull way.
510
+
511
+ =cut
512
+
513
+ sub game_over {
514
+ logger("[*] Terminating...");
515
+ if (defined $dbh) {
516
+ $dbh->disconnect;
517
+ }
518
+ unlink ($PIDFILE);
519
+ exit 0;
520
+ }
521
+
522
+ =head1 AUTHOR
523
+
524
+ Edward Fjellskaal <edwardfjellskaal@gmail.com>
525
+
526
+ =head1 COPYRIGHT
527
+
528
+ This library is free software, you can redistribute it and/or modify
529
+ it under the same terms as Perl itself.
530
+
531
+ =cut
dns_tunneling/passivedns-master/tools/search-pdns.pl ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/perl
2
+
3
+ # ----------------------------------------------------------------------
4
+ # Search in PassiveDNS DB
5
+ # Copyright (C) 2011-2012, Edward Fjellskål <edwardfjellskaal@gmail.com>
6
+ #
7
+ # This program is free software; you can redistribute it and/or modify
8
+ # it under the terms of the GNU General Public License as published by
9
+ # the Free Software Foundation; either version 2 of the License, or
10
+ # (at your option) any later version.
11
+ #
12
+ # This program is distributed in the hope that it will be useful,
13
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
+ # GNU General Public License for more details.
16
+ #
17
+ # You should have received a copy of the GNU General Public License
18
+ # along with this program; if not, write to the Free Software
19
+ # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20
+ # ----------------------------------------------------------------------
21
+ # Added Resource Record Type : hookol 20180321
22
+
23
+ use strict;
24
+ use warnings;
25
+ use POSIX ('strftime');
26
+ use Time::Local;
27
+ use Date::Simple ('date', 'today');
28
+ use Getopt::Long qw/:config auto_version auto_help/;
29
+ use DBI;
30
+
31
+ # You need to set DB user,password and host to connect to...
32
+ my $db_host = 'localhost';
33
+ my $DB = 'pdns';
34
+ my $db_user_name = 'pdns';
35
+ my $db_password = 'pdns';
36
+ my $DLIMIT = 100;
37
+
38
+ =head1 NAME
39
+
40
+ search-pdns.pl - Search in the PassiveDNS database
41
+
42
+ =head1 VERSION
43
+
44
+ 0.1.1
45
+
46
+ =head1 SYNOPSIS
47
+
48
+ $ search-pdns.pl [options]
49
+
50
+ OPTIONS:
51
+
52
+ -s : %IP/Domain%
53
+ -r : Enables raw search
54
+ -t : Resource Record Type (A, NS, MX, SOA, etc.)
55
+ --first-seen : Date to search from in iso format (2010-01-01 etc.)
56
+ --last-seen : Date to search to in iso format (2020-01-01 etc.)
57
+ --limit : Limit on search results (100)
58
+
59
+ EXAMPLES:
60
+
61
+ # Searches for "%facebook%"
62
+ search-pdns.pl -s "facebook"
63
+
64
+ # Searches for "^facebook.%.com$"
65
+ search-pdns.pl -r -s "facebook.%.com"
66
+
67
+ # Searches for domains/IPs that existed just one day, 2011-01-01.
68
+ search-pdns.pl --first-seen 2011-01-01 --last-seen 2011-01-01
69
+
70
+ =cut
71
+
72
+ our $DEBUG = 0; # Set to 1 for debugging, 2 to exit before the sql call
73
+ our $RAW = 0;
74
+ our $SEARCH = "%";
75
+ our $FROM_DATE;
76
+ our $TO_DATE;
77
+ our $LIMIT;
78
+ our $TYPE;
79
+
80
+ GetOptions(
81
+ 'd=s' => \$DEBUG,
82
+ 's=s' => \$SEARCH,
83
+ 'r' => \$RAW,
84
+ 'first-seen=s' => \$FROM_DATE,
85
+ 'last-seen=s' => \$TO_DATE,
86
+ 'limit=s' => \$LIMIT,
87
+ 't=s' => \$TYPE,
88
+ );
89
+
90
+ if ($SEARCH eq "") {
91
+ print "[*] You need to search for something....\n";
92
+ exit 0;
93
+ }
94
+
95
+ my $dsn = "DBI:mysql:$DB:" . $db_host;
96
+ my $dbh = DBI->connect($dsn, $db_user_name, $db_password);
97
+
98
+ our ($QUERY, $QUERY1, $QUERY2) = q();
99
+
100
+ $QUERY = qq[SELECT query, answer, first_seen, last_seen, ttl, count, maptype FROM pdns WHERE ];
101
+
102
+ if (defined $FROM_DATE ) {
103
+ if ($FROM_DATE=~ /^\d\d\d\d\-\d\d\-\d\d$/) {
104
+ print "Searching from date: $FROM_DATE 00:00:01\n" if $DEBUG;
105
+ $QUERY1 = $QUERY . qq[first_seen > '$FROM_DATE 00:00:01' ];
106
+ } elsif ($FROM_DATE=~ /^\d\d\d\d\-\d\d\-\d\d \d\d:\d\d:\d\d$/) {
107
+ print "Searching from date: $FROM_DATE\n" if $DEBUG;
108
+ $QUERY1 = $QUERY . qq[first_seen > '$FROM_DATE' ];
109
+ }
110
+ } else {
111
+ print "Searching from date: Thu Jan 1 00:00:00 UTC 1970\n" if $DEBUG;
112
+ $QUERY1 = $QUERY . qq[first_seen > '1970-01-01 00:00:01' ];
113
+ }
114
+
115
+ if (defined $TO_DATE) {
116
+ if ($TO_DATE =~ /^\d\d\d\d\-\d\d\-\d\d$/) {
117
+ print "Searching to date: $TO_DATE 23:59:59\n" if $DEBUG;
118
+ $QUERY1 = $QUERY1 . qq[AND last_seen < '$TO_DATE' ];
119
+ } elsif ($TO_DATE =~ /^\d\d\d\d\-\d\d\-\d\d \d\d:\d\d:\d\d$/) {
120
+ print "Searching to date: $TO_DATE\n" if $DEBUG;
121
+ $QUERY1 = $QUERY1 . qq[AND last_seen < '$TO_DATE' ];
122
+ }
123
+ }
124
+
125
+ $QUERY2 = $QUERY1;
126
+
127
+ if (defined $SEARCH) {
128
+ print "Searching for: $SEARCH\n" if $DEBUG;
129
+ if ( $RAW == 1 ) {
130
+ $QUERY1 = $QUERY1 . qq[AND query like '$SEARCH' ];
131
+ $QUERY2 = $QUERY2 . qq[AND answer like '$SEARCH' ];
132
+ } else {
133
+ $QUERY1 = $QUERY1 . qq[AND query like '%$SEARCH%' ];
134
+ $QUERY2 = $QUERY2 . qq[AND answer like '%$SEARCH%' ];
135
+ }
136
+ }
137
+
138
+
139
+ if (defined $TYPE) {
140
+ $QUERY1 = $QUERY1 . qq[AND maptype = '$TYPE' ];
141
+ $QUERY2 = $QUERY2 . qq[AND maptype = '$TYPE' ];
142
+ }
143
+
144
+
145
+ $QUERY = $QUERY1 . qq[ UNION ] . $QUERY2;
146
+
147
+ if (defined $LIMIT && $LIMIT =~ /^([\d])+$/) {
148
+ print "Limit: $LIMIT\n" if $DEBUG;
149
+ $DLIMIT = $LIMIT;
150
+ $QUERY = $QUERY . qq[ORDER BY last_seen LIMIT $LIMIT ];
151
+ } else {
152
+ print "Limit: $DLIMIT\n" if $DEBUG;
153
+ $QUERY = $QUERY . qq[ORDER BY last_seen LIMIT $DLIMIT ];
154
+ }
155
+
156
+ print "\nmysql> $QUERY;\n\n" if $DEBUG;
157
+
158
+ exit 0 if $DEBUG > 1;
159
+
160
+ my $pri = $dbh->prepare( qq{ $QUERY } );
161
+ $pri->execute();
162
+
163
+ my $cnt = 0;
164
+ print " === PassiveDNS ===\n\n";
165
+ print " FirstSeen | LastSeen | TYPE | TTL | Query | Answer | Count\n";
166
+ print "------------------------------------------------------------------------------------------------------------------------------\n";
167
+ while (my ($query, $answer, $firstseen, $lastseen, $ttl, $count, $maptype) = $pri->fetchrow_array()) {
168
+ next if not defined $query or not defined $answer;
169
+ $cnt++;
170
+ #printf("%20s | %20s | %5s | %6s | %-34s | %12s\n", $firstseen, $lastseen, $maptype, $ttl, $query, $answer);
171
+ printf("%20s | %19s | %5s | %6s | %-34s | %14s | %8s\n", $firstseen, $lastseen, $maptype, $ttl, $query, $answer, $count);
172
+
173
+ }
174
+ print "Displayed $cnt (sql limit: $DLIMIT)\n";
175
+
176
+ $pri->finish();
177
+ $dbh->disconnect();
178
+
179
+ =head1 AUTHOR
180
+
181
+ Edward Fjellskaal <edwardfjellskaal@gmail.com>
182
+
183
+ =head1 COPYRIGHT
184
+
185
+ Copyright (C) 2011, Edward Fjellskaal (edwardfjellskaal@gmail.com)
186
+
187
+ This program is free software; you can redistribute it and/or modify
188
+ it under the terms of the GNU General Public License as published by
189
+ the Free Software Foundation; either version 2 of the License, or
190
+ (at your option) any later version.
191
+
192
+ This program is distributed in the hope that it will be useful,
193
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
194
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
195
+ GNU General Public License for more details.
196
+
197
+ You should have received a copy of the GNU General Public License
198
+ along with this program; if not, write to the Free Software
199
+ Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
200
+
201
+ =cut
dns_tunneling/passivedns-master/www/index.php ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ # --------------------------------------------------------------------------
3
+ # Copyright (C) 2013 Edward Fjellskål <edward.fjellskaal@gmail.com>
4
+ #
5
+ # This program is free software; you can redistribute it and/or modify
6
+ # it under the terms of the GNU General Public License as published by
7
+ # the Free Software Foundation; either version 2 of the License, or
8
+ # (at your option) any later version.
9
+ #
10
+ # This program is distributed in the hope that it will be useful,
11
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ # GNU General Public License for more details.
14
+ #
15
+ # You should have received a copy of the GNU General Public License
16
+ # along with this program; if not, write to the Free Software
17
+ # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18
+ # --------------------------------------------------------------------------
19
+ #
20
+ # Configure Start
21
+ $DATABASE = "127.0.0.1";
22
+ $DBUSER = "pdns";
23
+ $DBTABLE = "pdns";
24
+ $DBPASSWD = "pdns";
25
+ $DBLIMIT = 500;
26
+ # Configure End
27
+
28
+ $query = sanitize("query"); if (empty($query)) $query = "";
29
+
30
+ print_header();
31
+ print_search_body();
32
+
33
+ if ($query) {
34
+ echo "<center>";
35
+ mysql_connect($DATABASE, $DBUSER, $DBPASSWD) or die(mysql_error());
36
+ mysql_select_db($DBTABLE) or die(mysql_error());
37
+ if ( filter_var($query, FILTER_VALIDATE_IP) ) {
38
+ echo "<b>PassiveDNS Records for IP: ". $query ."</b><br><br>";
39
+ $domains = mysql_query("SELECT * FROM pdns WHERE answer='$query' LIMIT $DBLIMIT");
40
+ if(mysql_num_rows($domains)==0){
41
+ echo "<b>No records found...</b><br><br>";
42
+ } else {
43
+ echo "<table cellpadding='2'><tr><td><b>First Seen</b></td><td><b>Last Seen</b></td><td><b>Type</b></td><td><b>TTL</b></td><td><b>Query</b></td><td><b>Answer</b></td><td><b>Count</b></td></tr>";
44
+ echo '
45
+ ';
46
+ while ( $r = mysql_fetch_array($domains) ) {
47
+ echo "<tr>";
48
+ echo "<td>". $r['FIRST_SEEN'] ."</td>";
49
+ echo "<td>". $r['LAST_SEEN'] ."</td>";
50
+ echo "<td>". $r['MAPTYPE'] ."</td>";
51
+ echo "<td>". $r['TTL'] ."</td>";
52
+ echo "<td><a href='?query=". $r['QUERY'] ."'>". $r['QUERY'] ."</a></td>";
53
+ echo "<td><a href='?query=". $r['ANSWER'] ."'>". $r['ANSWER'] ."</a></td>";
54
+ echo "<td>". $r['COUNT'] ."</td>";
55
+ echo "</tr>";
56
+ }
57
+ }
58
+ } else {
59
+ echo "<b>PassiveDNS Records for Domain: ". $query ."</b> <br><br>";
60
+ $domains = mysql_query("SELECT * FROM pdns WHERE query LIKE '$query' LIMIT $DBLIMIT");
61
+ if(mysql_num_rows($domains)==0){
62
+ echo "<b>No records found...</b><br><br>";
63
+ } else {
64
+ echo "<table cellpadding='2'><tr><td><b>First Seen</b></td><td><b>Last Seen</b></td><td><b>Type</b></td><td><b>TTL</b></td><td><b>Query</b></td><td><b>Answer</b></td><td><b>Count</b></td></tr>";
65
+ echo '
66
+ ';
67
+ while ( $r = mysql_fetch_array($domains) ) {
68
+ echo "<tr>";
69
+ echo "<td>". $r['FIRST_SEEN'] ."</td>";
70
+ echo "<td>". $r['LAST_SEEN'] ."</td>";
71
+ echo "<td>". $r['MAPTYPE'] ."</td>";
72
+ echo "<td>". $r['TTL'] ."</td>";
73
+ echo "<td><a href='?query=". $r['QUERY'] ."'>". $r['QUERY'] ."</a></td>";
74
+ echo "<td><a href='?query=". $r['ANSWER'] ."'>". $r['ANSWER'] ."</a></td>";
75
+ echo "<td>". $r['COUNT'] ."</td>";
76
+ echo "</tr>";
77
+ }
78
+ }
79
+ }
80
+ echo "</center>";
81
+ }
82
+
83
+ print_tail();
84
+
85
+ function getVar($in) {
86
+
87
+ if (isset($_POST[$in])) {
88
+ $out = $_POST[$in];
89
+ } else {
90
+ $out = $_GET[$in];
91
+ }
92
+
93
+ if (get_magic_quotes_gpc()) {
94
+ if (is_array($out)) {
95
+ foreach ($out as $el) {
96
+ $array[] = stripslashes($el);
97
+ }
98
+ $out = $array;
99
+ } else {
100
+ $out = stripslashes($out);
101
+ }
102
+ }
103
+
104
+ return $out;
105
+ }
106
+
107
+ function sanitize($in) {
108
+ $qvar = strip_tags(addslashes(getVar($in)));
109
+
110
+ if ( preg_match('/(\w+\.)*\w{2,}\.\w{2,4}$/i', $qvar) ) {
111
+ /* Might be a domain */
112
+ return $qvar;
113
+ } else if ( preg_match('/^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$/', $qvar) ) {
114
+ /* Might be a IPv4 */
115
+ return $qvar;
116
+ } else if (preg_match('/^[a-f0-9]{1,4}:([a-f0-9]{0,4}:){1,6}[a-f0-9]{1,4}$/i', $qvar)) {
117
+ /* FE80:0000:0000:0000:0202:B3FF:FE1E:8329 or FE80::0202:B3FF:FE1E:8329 */
118
+ /* or even 2001:db8::1 or 0:0:0:0:0:ffff:192.1.56.10 */
119
+ /* Might be a IPv6 */
120
+ return $qvar;
121
+ } else {
122
+ /* B0rked */
123
+ echo "B0rked";
124
+ return "";
125
+ }
126
+ }
127
+
128
+ function print_header() {
129
+ echo "<html>
130
+ <head>
131
+ <title>PassiveDNS</title>";
132
+ echo '
133
+ <style type="text/css">
134
+ td,p,div.box {
135
+ color: #000;
136
+ margin: 4px;
137
+ padding: 4px;
138
+ font-family: verdana, arial, helvetica, sans-serif;
139
+ font-size: 13px;
140
+ font-weight: normal;
141
+ border-bottom: 1px none #BFE9FF;
142
+ }
143
+ tr.odd {
144
+ background-color: #E2F1FF;
145
+ }
146
+ table
147
+ {
148
+ margin-left: auto;
149
+ margin-right: auto;
150
+ }
151
+ </style>
152
+ </head>
153
+ <body><center>
154
+ <div style="width: 860px; margin:auto;">
155
+ <p>
156
+ This data has been collected using <a href="http://github.com/gamelinux/passivedns">PassiveDNS</a>.
157
+ </p>
158
+ </div>
159
+ <table width="860" cellpadding="2" cellspacing="0">
160
+ ';
161
+ }
162
+
163
+ function print_search_body() {
164
+ echo '<tr><td><center><form name search method="GET">';
165
+ echo 'Domain/IP: <input type="text" maxlength="300" name="query">';
166
+ echo '<input type="submit" value="Search"></form><center><br>
167
+ ';
168
+ }
169
+
170
+ function print_tail() {
171
+ echo '
172
+ </center>
173
+ </body>
174
+ </html>';
175
+ }
176
+
177
+ ?>