Upload dns_tunneling dataset
Browse filesFiles changed (32)
- dns_tunneling/dns_tunneling_processed.csvAdded
- dns_tunneling/metadata.jsonAdded+24
- dns_tunneling/passivedns-master/.gitignoreAdded+28
- dns_tunneling/passivedns-master/Makefile.amAdded+3
- dns_tunneling/passivedns-master/READMEAdded+90
- dns_tunneling/passivedns-master/bootstrapAdded+19
- dns_tunneling/passivedns-master/configure.acAdded+293
- dns_tunneling/passivedns-master/doc/AUTHORSAdded+27
- dns_tunneling/passivedns-master/doc/ChangeLogAdded+52
- dns_tunneling/passivedns-master/doc/How-it-works.txtAdded+37
- dns_tunneling/passivedns-master/doc/INSTALLAdded+74
- dns_tunneling/passivedns-master/doc/ISSUESAdded+9
- dns_tunneling/passivedns-master/doc/LICENSEAdded+339
- dns_tunneling/passivedns-master/doc/READMEAdded+38
- dns_tunneling/passivedns-master/doc/README.upgradingAdded+18
- dns_tunneling/passivedns-master/doc/ROADMAPAdded+62
- dns_tunneling/passivedns-master/doc/TODOAdded+12
- dns_tunneling/passivedns-master/etc/default/passivedns-debianAdded+44
- dns_tunneling/passivedns-master/etc/init.d/passivedns-debianAdded+66
- dns_tunneling/passivedns-master/etc/init.d/passivedns-redhatAdded+129
- dns_tunneling/passivedns-master/etc/logrotate.d/passivednsAdded+13
- dns_tunneling/passivedns-master/etc/sysconfig/passivedns-redhatAdded+66
- dns_tunneling/passivedns-master/pdns.patchAdded+57
- dns_tunneling/passivedns-master/src/Makefile.amAdded+17
- dns_tunneling/passivedns-master/src/dns.cAdded+1886
- dns_tunneling/passivedns-master/src/dns.hAdded+187
- dns_tunneling/passivedns-master/src/passivedns.cAdded+1603
- dns_tunneling/passivedns-master/src/passivedns.hAdded+580
- dns_tunneling/passivedns-master/tools/README.skip_white_black-list.txtAdded+37
- dns_tunneling/passivedns-master/tools/pdns2db.plAdded+531
- dns_tunneling/passivedns-master/tools/search-pdns.plAdded+201
- dns_tunneling/passivedns-master/www/index.phpAdded+177
123456789101112131415161718192021222324{ "dataset_id": "dns_tunneling",<<<<<<< Updated upstream "processed_at": "2025-08-24T04:17:07.693713", "samples": 10000,======= "processed_at": "2025-08-24T03:09:42.416761", "samples": 150000,>>>>>>> Stashed changes "features": [ "query_name", "query_type", "response_code", "query_length",<<<<<<< Updated upstream "subdomain_count", "is_tunneling"======= "subdomain_count">>>>>>> Stashed changes ], "type": "dns", "file_path": "..\\datasets\\dns_tunneling\\dns_tunneling_processed.csv"}12345678910111213141516171819202122232425262728# Binariessrc/passivedns
# Object files*.o
# Autotools files*.swpaclocal.m4autom4te.cache/compileconfig.guessconfig.logconfig.subconfig.statusconfiguredepcompinstall-shmissingMakefileMakefile.insrc/config.hsrc/config.h.insrc/.deps/src/Makefilesrc/Makefile.insrc/stamp-h1
123AUTOMAKE_OPTIONS = foreignSUBDIRS = src
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990## ______ ____ __ __ _____# | __ | @ | \ | \ | || ___| (TM)# | _____|.------. .-----. .-----. _ -. .-.------. | |\ || \| ||___ |# | | | __ ||__ --'|__ --'| |\ Y /| _--__|_| |/ || || \_| |# |__| |____|_||______||______||_| \_/ |_______/|____/ |__|\__||_____|##
A tool to collect DNS records passively to aid Incident handling, NetworkSecurity Monitoring (NSM) and general digital forensics.
PassiveDNS sniffs traffic from an interface or reads a pcap-file and outputsthe DNS-server answers to a log file. PassiveDNS can cache/aggregate duplicateDNS answers in-memory, limiting the amount of data in the logfile withoutlosing the essense in the DNS answer.
Example output from version 1.0.0->Current in the log file (/var/log/passivedns.log):
#timestamp||dns-client ||dns-server||RR class||Query||Query Type||Answer||TTL||Count1322849924.408856||10.1.1.1||8.8.8.8||IN||upload.youtube.com.||A||74.125.43.117||46587||51322849924.408857||10.1.1.1||8.8.8.8||IN||upload.youtube.com.||A||74.125.43.116||420509||51322849924.408858||10.1.1.1||8.8.8.8||IN||www.adobe.com.||CNAME||www.wip4.adobe.com.||43200||81322849924.408859||10.1.1.1||8.8.8.8||IN||www.adobe.com.||A||193.104.215.61||43200||81322849924.408860||10.1.1.1||8.8.8.8||IN||i1.ytimg.com.||CNAME||ytimg.l.google.com.||43200||31322849924.408861||10.1.1.1||8.8.8.8||IN||clients1.google.com.||A||173.194.32.3||43200||2
PassiveDNS works on IPv4 and IPv6 traffic and parse DNS traffic over TCP and UDP.
** How can PassiveDNS be used: **
Typical usages:
1) Search for domain or IP history when working on an incident. Example: Company has malware talking to bad.twittertoday.com. At current time, the domain is resolving to say 202.29.94.200 You search your Flowdata and find the clients talking to that IP and remidate. You look at the Flowdata, and you discover that the date and time the clients first talked to that IP, and concludes that as the time of infection...
But using PassiveDNS data, quering the domain, you get following history:
FirstSeen | LastSeen | TYPE | TTL | Query | Answer---------------------------------------------------------------------------- 2011-12-01 | 2011-12-11 | A | 60 | bad.twittertoday.com | 71.51.115.11 2011-12-11 | 2011-12-18 | A | 60 | bad.twittertoday.com | 127.0.0.1 2011-12-18 | 2012-01-14 | A | 60 | bad.twittertoday.com | 202.29.94.200
Going back and searching for 71.51.115.11 in your Flowdata, you find traffic back to the FirstSeen data, and you also see more clients initially infected (so you did not manage to remidate/check out all your clients in the first run by just looking at IP 202.29.94.200). Doing forensics on the the clients you missed in the first run, reveals that they have downloaded a different malware and deleted the initial one, that beeing the reason you did not see flows from them to 202.29.94.200. The new malware gives you new domains and IPs to go look for...
2) Say you have an indication of malicious C&C traffic going to an IP on port 80. The domain used by the alleged malware is supposed to be cc.twittertoday.com. Searching you Flowdata, reveals lots of clients talking to that IP, and you might think that the whole company is p0wned. A quick search in your PassiveDNS DB shows you that the IP in question is also hosting 300 + websites and you might even spot a website hosted on that IP that you are familiar with and that you know lots of people in the company would legit visit daily. Searching your PassiveDNS DB gives you no hits for the domain in question, hopefully meaning that you dont have that malware talking to that domain in your network.
3) You know that *.twittertoday.com are often used in malware and the subdomains change randomly. Many have rules for such domains in their IDS/IPS, sucking up unnecessary juice from the systems. Having a script pre-loaded with a list of regexp of domains and subdomains to watch for and giving you an alert when they hit will give you much better detection on threat based on domains.
You can also do a whois for all new top domains seen, correlate the whois info with a list of know bad info, such as the name of the person or company that has registered the domain, telephone/fax numbers, address and so on, ending up with a score that might be high enough for triggering an alert to you :)
Questions, suggestions, sugar or flame is always welcome :)
I hope PassiveDNS gives you a new tool to fight malware and its herders...
(c)2011-2020 - Edward Bjarte Fjellskål12345678910111213141516171819#!/bin/sh## desc: simple script to run all auto commands#####
# defines needed for OpenBSDAUTOMAKE_VERSION=1.15;export AUTOMAKE_VERSIONAUTOCONF_VERSION=2.69;export AUTOCONF_VERSION
if [ ! -d config ]; then mkdir configfi
aclocalautomake --gnu --add-missingautoconfautoheader
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293# -*- Autoconf -*-# Process this file with autoconf to produce a configure script.
AC_INIT([passivedns], [1.2.1])AM_INIT_AUTOMAKEAC_USE_SYSTEM_EXTENSIONSAC_CONFIG_SRCDIR([src/passivedns.h])AC_CONFIG_HEADERS([src/config.h])
# Checks for programs.AC_PROG_CC
AC_CANONICAL_HOST
dnl Checks for OS type.case "$host" in *-freebsd*) AC_DEFINE([BSD_DERIVED],1,BSD_DERIVED) AC_DEFINE([FREEBSD],1,FREEBSD) LDFLAGS="${LDFLAGS}" ;; *-netbsd*) AC_DEFINE([BSD_DERIVED],1,BSD_DERIVED) AC_DEFINE([NETBSD],1,NETBSD) ;; *-openbsd*) AC_DEFINE([BSD_DERIVED],1,BSD_DERIVED) AC_DEFINE([OPENBSD],1,OPENBSD) CFLAGS="${CFLAGS} -Wbounded" LDFLAGS="${LDFLAGS}" ;; *-apple*) AC_DEFINE([BSD_DERIVED],1,BSD_DERIVED) AC_DEFINE([MACOS],1,MACOS) LDFLAGS="${LDFLAGS} -L/sw/lib" AC_SUBST(more_incl) more_incl=-I/sw/include ;; *-linux*) AC_DEFINE([SYSV_DERIVED],1,SYSV_DERIVED) AC_DEFINE([LINUX],1,LINUX) LDFLAGS="${LDFLAGS}" ;; *-solaris*) AC_DEFINE([SYSV_DERIVED],1,SYSV_DERIVED) AC_DEFINE([SOLARIS],1,SOLARIS) LDFLAGS="${LDFLAGS}" ;; *-aix*) AC_DEFINE([SYSV_DERIVED],1,SYSV_DERIVED) AC_DEFINE([AIX],1,AIX) ;; *-hpux*) AC_DEFINE([SYSV_DERIVED],1,SYSV_DERIVED) AC_DEFINE([HPUX],1,HPUX) ;;esac
# Enable debug output.AC_ARG_ENABLE(debug, AS_HELP_STRING([--enable-debug], [Enable debug output]))
AS_IF([test "x$enable_debug" = "xyes"], [ CPPFLAGS="${CPPFLAGS} -Wall -g -DDEBUG"])
# Enable gcc profile info.AC_ARG_ENABLE(gccprofile, AS_HELP_STRING([--enable-gccprofile], [Enable gcc profile info (set -pg flag)]))
AS_IF([test "x$enable_gccprofile" = "xyes"], [ CPPFLAGS="${CPPFLAGS} -g -pg"])
# Checks for libpcap.AC_ARG_WITH(libpcap_includes, [ --with-libpcap-includes=DIR libpcap include directory], [with_libpcap_includes="$withval"],[with_libpcap_includes="no"])
AC_ARG_WITH(libpcap_libraries, [ --with-libpcap-libraries=DIR libpcap library directory], [with_libpcap_libraries="$withval"],[with_libpcap_libraries="no"])
if test "$with_libpcap_includes" != "no"; then CPPFLAGS="${CPPFLAGS} -I${with_libpcap_includes}"fi
if test "$with_libpcap_libraries" != "no"; then LDFLAGS="${LDFLAGS} -L${with_libpcap_libraries}"fi
LDFLAGS="${LDFLAGS} -lpcap"
# Check for libpcap headersAC_CHECK_HEADER(pcap.h,,LIBPCAP_H="no")
if test "$LIBPCAP_H" = "no"; then echo -e "\n ERROR! libpcap headers not found\n" exit 1fi
# Check for libpcap libraryAC_CHECK_LIB(pcap,pcap_loop,,LIBPCAP_L="no")
if test "$LIBPCAP_L" = "no"; then echo -e "\n ERROR! libpcap library not found\n" exit 1fi
# Checks for OpenSSL (newer versions of ldns require OpenSSL).AC_ARG_ENABLE(openssl, AS_HELP_STRING([--disable-openssl], [Requires ldns library compiled without OpenSSL]), [enable_openssl=no], [enable_openssl=yes])
AC_ARG_WITH(openssl_includes, [ --with-openssl-includes=DIR OpenSSL include directory], [with_openssl_includes="$withval"],[with_openssl_includes="no"])
AC_ARG_WITH(openssl_libraries, [ --with-openssl-libraries=DIR OpenSSL library directory], [with_openssl_libraries="$withval"],[with_openssl_libraries="no"])
AS_IF([test "x$enable_openssl" = "xyes"], [ if test "$with_openssl_includes" != "no"; then CPPFLAGS="${CPPFLAGS} -I${with_openssl_includes}" fi
if test "$with_openssl_libraries" != "no"; then LDFLAGS="${LDFLAGS} -L${with_openssl_libraries}" fi
# Check for OpenSSL headers AC_CHECK_HEADER(openssl/ssl.h,,LIBOPENSSL_H="no")
if test "$LIBOPENSSL_H" = "no"; then echo -e "\n ERROR! OpenSSL headers not found\n" exit 1 fi])
# Checks for ldns.AC_ARG_WITH(ldns_includes, [ --with-ldns-includes=DIR ldns include directory], [with_ldns_includes="$withval"],[with_ldns_includes="no"])
AC_ARG_WITH(ldns_libraries, [ --with-ldns-libraries=DIR ldns library directory], [with_ldns_libraries="$withval"],[with_ldns_libraries="no"])
if test "$with_ldns_includes" != "no"; then CPPFLAGS="${CPPFLAGS} -I${with_ldns_includes}"fi
if test "$with_ldns_libraries" != "no"; then LDFLAGS="${LDFLAGS} -L${with_ldns_libraries}"fi
LDFLAGS="${LDFLAGS} -lldns"
# Check or ldns headersAC_CHECK_HEADER(ldns/ldns.h,,LIBLDNS_H="no")
if test "$LIBLDNS_H" = "no"; then echo -e "\n ERROR! ldns headers not found\n" exit 1fi
# Check for ldns libraryAC_CHECK_LIB(ldns,ldns_pkt_get_rcode,,LIBLDNS_L="no")
if test "$LIBLDNS_L" = "no"; then echo -e "\n ERROR! ldns library not found\n" exit 1fi
# Checks for PF_RING.AC_ARG_ENABLE(pfring, AS_HELP_STRING([--enable-pfring], [Enable PF_RING support]))
AC_ARG_WITH(pfring_includes, [ --with-pfring-includes=DIR PF_RING include directory], [with_pfring_includes="$withval"],[with_pfring_includes="no"])
AC_ARG_WITH(pfring_libraries, [ --with-pfring-libraries=DIR PF_RING library directory], [with_pfring_libraries="$withval"],[with_pfring_libraries="no"])
AS_IF([test "x$enable_pfring" = "xyes"], [ AC_DEFINE([HAVE_PFRING],[1],[PF_RING support enabled])
if test "$with_pfring_includes" != "no"; then CPPFLAGS="${CPPFLAGS} -I${with_pfring_includes}" fi
if test "$with_pfring_libraries" != "no"; then LDFLAGS="${LDFLAGS} -L${with_pfring_libraries}" fi
LDFLAGS="${LDFLAGS} -lpfring -lnuma -lrt"
# Checks for libnuma AC_CHECK_HEADER(numa.h,,LIBNUMA="no") AC_CHECK_LIB(numa,numa_available,,LIBNUMA="no")
if test "$LIBNUMA" = "no"; then echo -e "\n ERROR! libnuma not found (PF_RING requirement)\n" exit 1 fi
# Check for PF_RING headers AC_CHECK_HEADER(pfring.h,,LIBPFRING_H="no")
if test "$LIBPFRING_H" = "no"; then echo -e "\n ERROR! PF_RING headers not found\n" exit 1 fi
# Check for PF_RING library AC_CHECK_LIB(pfring,pfring_stats,,LIBPFRING_L="no")
if test "$LIBPFRING_L" = "no"; then echo -e "\n ERROR! PF_RING library not found\n" exit 1 fi
# Check for PF_RING BPF support AC_CHECK_LIB(pfring,pfring_set_bpf_filter,,LIBPFRING_BPF="no")
if test "$LIBPFRING_BPF" != "no"; then AC_DEFINE([HAVE_PFRING_BPF],[1],[PF_RING BPF support]) fi])
# Checks for libjansson.AC_ARG_ENABLE(json, AS_HELP_STRING([--enable-json], [Enable JSON support]))
AC_ARG_WITH(jansson_includes, [ --with-jansson-includes=DIR libjansson include directory], [with_jansson_includes="$withval"],[with_jansson_includes="no"])
AC_ARG_WITH(jansson_libraries, [ --with-jansson-libraries=DIR libjansson library directory], [with_jansson_libraries="$withval"],[with_jansson_libraries="no"])
AS_IF([test "x$enable_json" = "xyes"], [ AC_DEFINE([HAVE_JSON],[1],[JSON support enabled])
if test "$with_jansson_includes" != "no"; then CPPFLAGS="${CPPFLAGS} -I${with_jansson_includes}" fi
if test "$with_jansson_libraries" != "no"; then LDFLAGS="${LDFLAGS} -L${with_jansson_libraries}" fi
LDFLAGS="${LDFLAGS} -ljansson"
# Check for jansson headers AC_CHECK_HEADER(jansson.h,,LIBJANSSON_H="no")
if test "$LIBJANSSON_H" = "no"; then echo -e "\n ERROR! Jansson headers not found\n" exit 1 fi
# Check for jansson library AC_CHECK_LIB(jansson,json_delete,,LIBJANSSON_L="no")
if test "$LIBJANSSON_L" = "no"; then echo -e "\n ERROR! Jansson library not found\n" exit 1 fi])
# Checks for header files.AC_CHECK_HEADERS([arpa/inet.h fcntl.h netinet/in.h stdlib.h string.h syslog.h unistd.h])
# Checks for typedefs, structures, and compiler characteristics.AC_TYPE_PID_TAC_TYPE_UINT16_TAC_TYPE_UINT32_TAC_TYPE_UINT64_TAC_TYPE_UINT8_T
# Checks for library functions.AC_FUNC_FORKAC_FUNC_STRNLENAC_CHECK_FUNCS([alarm dup2 endgrent endpwent ftruncate getcwd memset strdup strerror strtol strtoul])
AC_OUTPUT(Makefile src/Makefile)
123456789101112131415161718192021222324252627Primary authors: Edward Fjellskål <edwardfjellskaal@gmail.com>
Co-Maintainer: Mats Klepsland <mats.klepsland@gmail.com>
Code from earlier projects: Kacper Wysocki <kacper.wysocki@redpill-linpro.com>
Some initially code ideas/borrowed from (Changes has been made): DNS parsing with lib ldns: www.nlnetlabs.nl (https://www.nlnetlabs.nl/projects/ldns/) Mark Ellzey (https://github.com/ellzey/dns-archiver)
Contributions (In no particular order!): Eric Kollman Henrik Ramberg Joe Moore kevin branch David André PingTrip Sony Security Development Team gavinspearhead
If you've been left off the list, it's not intentional. Please let us know!
Thanks!12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152Changes with PassiveDNS 1.2.0
- Added enhancements to better handle high volume traffic- Added support for LOC records- Added support for DNSSEC records- Added support for HINFO records- Added support for SPF records- Added support for SSHFP records- Support for DLT_RAW pcap files- Added support for LINKTYPE_LINUX_SLL- Added autotools support- Better OSX support- Added pf_ring support- Added support for SIGHUP to reopen log files- Added support for JSON output- Added syslog output option- Added support for expire_all_dns_records on SIGUSR2
Changes with PassiveDNS 1.1.3
- Added a fix for correct CNAME handling- Makefile improvements
Changes with PassiveDNS 1.1.2
- Zero padding to microseconds- Added a simple webui in php for searching the pdns mysql db.
Changes with PassiveDNS 1.1.1
- Added stats output to stdout with SIGUSR1 signal- Added support for more Server Return Codes
Changes with PassiveDNS 1.0.0
- Added microseconds to unix timestamps in log output- Added "count" field in log output.- Added more stat fields when exiting
Changes with PassiveDNS 0.5.1
- Fixed an issue of lost dns_records (memleak and finally a cpu spinn)- Fixed segfault when unable to read pcap- Fixed segfault when packet payload was only one byte
Changes with PassiveDNS 0.5.0
- Cleaned up unused code
Changes with PassiveDNS 0.3.4
- Added NXDOMAIN support12345678910111213141516171819202122232425262728293031323334353637#### PassiveDNS internals
## Packet capture* Uses libpcap* Decodes packets as they come in.* Handles vlan (looks inside vlan packets, but does not currently print out the vlan tag seen)* Handles IPv4 and IPv6 packets* We look at DNS on UDP and TCP
## Connection Tracking* Same connection tracking as in cxtracker** When used with a propper BPF (filter), it only tracks traffic on port 53.* Connection tracking is used to make sure that a client asked for a domain, so that there will not be any tracking of domains, if a client did not request one. A bit spoof protection. In the connection data, the DNS Transaction ID is also stored, to verify that the client sent a request, and that the server answered the right TID request :)
## Domain caching* When a DNS question and answer is recieved, it is stored in an internal linked list. If its new, we will print the info to the logfile, and we will not print it again befor it has gone 12 hours or the record has changed. This is to provent flooding of data to the log file, and serving you much duplicat info.* If we have not seen any activity agains a domain in 24h, it will be deleted from the internal cache.* If we have not seen any activity of any related entries within 24h, it will be deleted...
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374# General: # PassiveDNS was initially developed on a Ubuntu 10.04 platform, and later on Ubuntu 12.04, so all # main testing was done on Ubuntu. I have compiled passivedns static and dynamic # and tried it out on different linux OSes with great luck. # I try to keep the git tags "stable" and the master branch might be under development. # If you have issues with the current master, please read doc/ISSUES
FreeBSD Install $ pkg_add -r gmake git ldns $ rehash $ mkdir /usr/local/src/; cd /usr/local/src $ git clone git://github.com/gamelinux/passivedns.git $ cd passivedns/ $ autoreconf --install $ ./configure $ gmake
OS X (using Homebrew for dependencies) $ brew install automake autoconf ldns jansson $ git clone git://github.com/gamelinux/passivedns.git $ cd passivedns/ $ autoreconf --install $ ./configure $ make
Macbook Pro 2023 running Sonoma 14.4.1 (using Homebrew for dependencies) $ brew install automake autoconf ldns jansson openssl $ export LDFLAGS="-L$(brew --prefix openssl)/lib $LDFLAGS" $ export CPPFLAGS="-I$(brew --prefix openssl)/include $CPPFLAGS" $ export LDFLAGS="-L$(brew --prefix ldns)/lib $LDFLAGS" $ export CPPFLAGS="-I$(brew --prefix ldns)/include $CPPFLAGS" $ git clone git://github.com/gamelinux/passivedns.git $ cd passivedns/ $ autoreconf --install $ ./configure $ make
Ubuntu $ sudo apt-get install git-core binutils-dev libldns1 libldns-dev libpcap-dev # libdate-simple-perl is also needed for pdns2db.pl $ git clone git://github.com/gamelinux/passivedns.git $ cd passivedns/ $ autoreconf --install $ ./configure $ make
Debian 12 (Bookworm) $ sudo apt install git build-essential libldns-dev libpcap-dev automake autoconf # libdate-simple-perl might be needed for pdns2db.pl if you're using it $ sudo apt install libdate-simple-perl $ git clone git://github.com/gamelinux/passivedns.git $ cd passivedns/ $ autoreconf --install $ ./configure $ make
RedHat (RHEL 6u2 x86_64) $ yum groupinstall "Development tools" # EPEL : http://fedora.uib.no/epel/6/x86_64/ $ rpm -Uvh http://download.fedoraproject.org/pub/epel/6/x86_64/ldns-devel-1.6.11-2.el6.x86_64.rpm $ rpm -Uvh http://download.fedoraproject.org/pub/epel/6/x86_64/ldns-1.6.11-2.el6.x86_64.rpm # perl-DateTime is also needed for pdns2db.pl $ wget http://www.tcpdump.org/release/libpcap-1.2.1.tar.gz $ tar zxf libpcap-1.2.1.tar.gz; cd libpcap-1.2.1; ./configure; make && make install $ git clone git://github.com/gamelinux/passivedns.git $ cd passivedns/ $ autoreconf --install $ ./configure $ make
123456789# You will find all known issues here:# - https://github.com/gamelinux/passivedns/issues## If you encounter an issue, please add them using the above link.
By trying out passivedns, and giving feedback (Good or Bad), you can help make passivedns better.
# If you want to discuss with a broader audience:# https://groups.google.com/forum/?fromgroups#!forum/passivedns123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339 GNU GENERAL PUBLIC LICENSE Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away yourfreedom to share and change it. By contrast, the GNU General PublicLicense is intended to guarantee your freedom to share and change freesoftware--to make sure the software is free for all its users. ThisGeneral Public License applies to most of the Free SoftwareFoundation's software and to any other program whose authors commit tousing it. (Some other Free Software Foundation software is covered bythe GNU Lesser General Public License instead.) You can apply it toyour programs, too.
When we speak of free software, we are referring to freedom, notprice. Our General Public Licenses are designed to make sure that youhave the freedom to distribute copies of free software (and charge forthis service if you wish), that you receive source code or can get itif you want it, that you can change the software or use pieces of itin new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbidanyone to deny you these rights or to ask you to surrender the rights.These restrictions translate to certain responsibilities for you if youdistribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whethergratis or for a fee, you must give the recipients all the rights thatyou have. You must make sure that they, too, receive or can get thesource code. And you must show them these terms so they know theirrights.
We protect your rights with two steps: (1) copyright the software, and(2) offer you this license which gives you legal permission to copy,distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certainthat everyone understands that there is no warranty for this freesoftware. If the software is modified by someone else and passed on, wewant its recipients to know that what they have is not the original, sothat any problems introduced by others will not reflect on the originalauthors' reputations.
Finally, any free program is threatened constantly by softwarepatents. We wish to avoid the danger that redistributors of a freeprogram will individually obtain patent licenses, in effect making theprogram proprietary. To prevent this, we have made it clear that anypatent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution andmodification follow.
GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which containsa notice placed by the copyright holder saying it may be distributedunder the terms of this General Public License. The "Program", below,refers to any such program or work, and a "work based on the Program"means either the Program or any derivative work under copyright law:that is to say, a work containing the Program or a portion of it,either verbatim or with modifications and/or translated into anotherlanguage. (Hereinafter, translation is included without limitation inthe term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are notcovered by this License; they are outside its scope. The act ofrunning the Program is not restricted, and the output from the Programis covered only if its contents constitute a work based on theProgram (independent of having been made by running the Program).Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program'ssource code as you receive it, in any medium, provided that youconspicuously and appropriately publish on each copy an appropriatecopyright notice and disclaimer of warranty; keep intact all thenotices that refer to this License and to the absence of any warranty;and give any other recipients of the Program a copy of this Licensealong with the Program.
You may charge a fee for the physical act of transferring a copy, andyou may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portionof it, thus forming a work based on the Program, and copy anddistribute such modifications or work under the terms of Section 1above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. Ifidentifiable sections of that work are not derived from the Program,and can be reasonably considered independent and separate works inthemselves, then this License, and its terms, do not apply to thosesections when you distribute them as separate works. But when youdistribute the same sections as part of a whole which is a work basedon the Program, the distribution of the whole must be on the terms ofthis License, whose permissions for other licensees extend to theentire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contestyour rights to work written entirely by you; rather, the intent is toexercise the right to control the distribution of derivative orcollective works based on the Program.
In addition, mere aggregation of another work not based on the Programwith the Program (or with a work based on the Program) on a volume ofa storage or distribution medium does not bring the other work underthe scope of this License.
3. You may copy and distribute the Program (or a work based on it,under Section 2) in object code or executable form under the terms ofSections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work formaking modifications to it. For an executable work, complete sourcecode means all the source code for all modules it contains, plus anyassociated interface definition files, plus the scripts used tocontrol compilation and installation of the executable. However, as aspecial exception, the source code distributed need not includeanything that is normally distributed (in either source or binaryform) with the major components (compiler, kernel, and so on) of theoperating system on which the executable runs, unless that componentitself accompanies the executable.
If distribution of executable or object code is made by offeringaccess to copy from a designated place, then offering equivalentaccess to copy the source code from the same place counts asdistribution of the source code, even though third parties are notcompelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Programexcept as expressly provided under this License. Any attemptotherwise to copy, modify, sublicense or distribute the Program isvoid, and will automatically terminate your rights under this License.However, parties who have received copies, or rights, from you underthis License will not have their licenses terminated so long as suchparties remain in full compliance.
5. You are not required to accept this License, since you have notsigned it. However, nothing else grants you permission to modify ordistribute the Program or its derivative works. These actions areprohibited by law if you do not accept this License. Therefore, bymodifying or distributing the Program (or any work based on theProgram), you indicate your acceptance of this License to do so, andall its terms and conditions for copying, distributing or modifyingthe Program or works based on it.
6. Each time you redistribute the Program (or any work based on theProgram), the recipient automatically receives a license from theoriginal licensor to copy, distribute or modify the Program subject tothese terms and conditions. You may not impose any furtherrestrictions on the recipients' exercise of the rights granted herein.You are not responsible for enforcing compliance by third parties tothis License.
7. If, as a consequence of a court judgment or allegation of patentinfringement or for any other reason (not limited to patent issues),conditions are imposed on you (whether by court order, agreement orotherwise) that contradict the conditions of this License, they do notexcuse you from the conditions of this License. If you cannotdistribute so as to satisfy simultaneously your obligations under thisLicense and any other pertinent obligations, then as a consequence youmay not distribute the Program at all. For example, if a patentlicense would not permit royalty-free redistribution of the Program byall those who receive copies directly or indirectly through you, thenthe only way you could satisfy both it and this License would be torefrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable underany particular circumstance, the balance of the section is intended toapply and the section as a whole is intended to apply in othercircumstances.
It is not the purpose of this section to induce you to infringe anypatents or other property right claims or to contest validity of anysuch claims; this section has the sole purpose of protecting theintegrity of the free software distribution system, which isimplemented by public license practices. Many people have madegenerous contributions to the wide range of software distributedthrough that system in reliance on consistent application of thatsystem; it is up to the author/donor to decide if he or she is willingto distribute software through any other system and a licensee cannotimpose that choice.
This section is intended to make thoroughly clear what is believed tobe a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted incertain countries either by patents or by copyrighted interfaces, theoriginal copyright holder who places the Program under this Licensemay add an explicit geographical distribution limitation excludingthose countries, so that distribution is permitted only in or amongcountries not thus excluded. In such case, this License incorporatesthe limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versionsof the General Public License from time to time. Such new versions willbe similar in spirit to the present version, but may differ in detail toaddress new problems or concerns.
Each version is given a distinguishing version number. If the Programspecifies a version number of this License which applies to it and "anylater version", you have the option of following the terms and conditionseither of that version or of any later version published by the FreeSoftware Foundation. If the Program does not specify a version number ofthis License, you may choose any version ever published by the Free SoftwareFoundation.
10. If you wish to incorporate parts of the Program into other freeprograms whose distribution conditions are different, write to the authorto ask for permission. For software which is copyrighted by the FreeSoftware Foundation, write to the Free Software Foundation; we sometimesmake exceptions for this. Our decision will be guided by the two goalsof preserving the free status of all derivatives of our free software andof promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTYFOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHENOTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIESPROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSEDOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OFMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK ASTO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THEPROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITINGWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/ORREDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISINGOUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITEDTO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BYYOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHERPROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THEPOSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatestpossible use to the public, the best way to achieve this is to make itfree software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safestto attach them to the start of each source file to most effectivelyconvey the exclusion of warranty; and each file should have at leastthe "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like thiswhen it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriateparts of the General Public License. Of course, the commands you use maybe called something other than `show w' and `show c'; they could even bemouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or yourschool, if any, to sign a "copyright disclaimer" for the program, ifnecessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989 Ty Coon, President of Vice
This General Public License does not permit incorporating your program intoproprietary programs. If your program is a subroutine library, you mayconsider it more useful to permit linking proprietary applications with thelibrary. If this is what you want to do, use the GNU Lesser GeneralPublic License instead of this License.1234567891011121314151617181920212223242526272829303132333435363738## ______ ____ __ __ _____# | __ | @ | \ | \ | || ___| (TM)# | _____|.------. .-----. .-----. _ -. .-.------. | |\ || \| ||___ |# | | | __ ||__ --'|__ --'| |\ Y /| _--__|_| |/ || || \_| |# |__| |____|_||______||______||_| \_/ |_______/|____/ |__|\__||_____|##
# Usage########
# passivednsroot@localhost: ./passivedns -i eth1 -l /var/log/passivedns.log
# pdns2db.plroot@localhost: apt-get install libdatetime-perl(Redhat/CentOS: yum install perl-DateTime)
First you need to add a user to the mysql db:
mysql> GRANT USAGE ON *.* TO 'pdns'@'localhost' IDENTIFIED BY 'pdns';mysql> GRANT SELECT,CREATE,INSERT,UPDATE ON pdns.* TO 'pdns'@'localhost';mysql> flush privileges;mysql> CREATE DATABASE pdns;
Then you need to start up pdns2db.pl
root@localhost: perl pdns2db.pl --file /var/log/passivedns.log
# Old School archiving of passivedns.log# While passivedns is running;$ mkdir /var/log/passivedns-archive/$ mv /var/log/passivedns.log /var/log/passivedns-archive/$ gzip -S ".`date +%s`.gz" /var/log/passivedns-archive/passivedns.log # Searching$ zgrep "gamelinux.org" /var/log/passivedns-archive/*
123456789101112131415161718Upgrade from PassiveDNS < 1.0 to 1.0:
- If you are using custom tools to process the passivedns.log files, you need to be aware of the new output filed added (count). Also be aware of the unix timestamp now has microseconds!
- If you are using pdns2db.pl you need to do the following:
1) Stop current passivedns. Make sure that pdns2db.pl has processed passivedns.log Move the old passivedns.log away to archive.
2) Then, in mysql: mysql> ALTER TABLE pdns ADD COUNT BIGINT(20) UNSIGNED NOT NULL DEFAULT '1' AFTER TTL;
3) Install (build) the lastest passivedns and pdns2db.pl Start passivedns && pdns2db.pl
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162# Version 2+ - Slackspace inspection: * inside dns packet * outside dns packet - Entropy checkin on fqdn, TLD, LLD, SLD etc - detect clients that has many NXDOMAIN responces - Look at cxt when timing out that has no Client Transaction ID but a Server Transaction ID.
# Version 2.0.0 == Production ready and stable == - Customizable output of fields
# Version 1.5.0 == Production ready and stable == - Reads passivedns.log file on startup populating the cache with objects seen less than cache-timeout. - Support NXDOMAIN via cmdline switch.
# Version 1.0.0 == Production ready and stable == - Tested/protected for: * hardening: - spoofing - poisoning - other * evation ? * flooding ? * BOF (fuzz the crap out of it) - some stats when exiting * max concurrent records cached * max concurrent sessions (cxt) * max session memory usage (cxt) * DNS counts: - how many was IPv6 - how many was IPv4 - how many was TCP - how many was UDP
# Version 0.5.0 == Production ready and stable == - support specifying RR types via switch: A, AAAA, PTR, CNAME, DNAME, NAPTR, RP, SRV, TXT, SOA, MX and NS - soft memory limiting for caching of DNS objects - cmdline switch for specifying print-time - cmdline switch for specifying cache-time - cmdline for chroot - cmdline for drop privs - cmdline for specifying log file - sniff traffic from an interface - process pcap files - cmdline for specifying BPF filter - cmdline for specifying pidfile - daemon mode - output fields: timestamp||dns-client||dns-server||RR class||Query||Query Type||Answer||TTL
123456789101112
# PassiveDNS
* Add some stats* Add abuility to read log file when starting up - Import domains that has timestamp less then "$cachetimeout" ago -- It will reduce the "noize" at startups.
* Evaluate pdns hardening methods
* Adding abuility for custom output formating
1234567891011121314151617181920212223242526272829303132333435363738394041424344# OPTIONS:# # -i <iface> Network device <iface> (default: eth0).# -r <file> Read pcap <file>.# -l <file> Name of the logfile (default: /var/log/passivedns.log).# -L <file> Name of NXDOMAIN logfile (default: /var/log/passivedns.log).# -b 'BPF' Berkley Packet Filter (default: 'port 53').# -p <file> Name of pid file (default: /var/run/passivedns.pid).# -S <mem> Soft memory limit in MB (default: 256).# -C <sec> Seconds to cache DNS objects in memory (default 43200).# -P <sec> Seconds between printing duplicate DNS info (default 86400).# -X <flags> Manually set DNS RR Types to care about(Default -X 46CDNPRS).# -u <uid> User ID to drop privileges to.# -g <gid> Group ID to drop privileges to.# -T <dir> Directory to chroot into.# -D Run as daemon.# -V Show version and exit.# -h This help message.# # FLAGS:# # 4:A 6:AAAA C:CNAME D:DNAME N:NAPTR O:SOA# P:PTR R:RP S:SRV T:TXT M:MX n:NS# x:NXD# ## Default valuesNAME=passivednsPIDFILE=/var/run/passivedns.pidDAEMON=/usr/bin/$NAME
## Quick and dirty:INTERFACE="-i eth0"LOGFILE="-l /var/log/passivedns.log"NXLOGFILE="-L /var/log/passivedns-nx.log"LOGSYSLOG=""NXSYSLOG=""MAXMEM="-S 256"PRINT="-P 86400"RRTYPES="-X 46CDNOPRSTMnx"#UID="-u 1"#GID="-g 1"#CHROOT="/usr/lib/passivedns/"DEAMON="-D"ARGS="$INTERFACE $LOGFILE $NXLOGFILE $LOGSYSLOG $NXSYSLOG $MAXMEM $PRINT $RRTYPES $DEAMON"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566#!/bin/bash#### BEGIN INIT INFO# Provides: passivedns# Required-Start: $network# Required-Stop: $network# Default-Start: 2 3 4 5# Default-Stop: 0 1 6# Short-Description: Passive DNS collector# Description: This is a network (security) tool designed to # collect DNS information for troubleshooting or# security related work### END INIT INFO
NAME=passivednsPIDFILE=/var/run/passivedns.pidDAEMON=/usr/bin/$NAMEARGS="-i eth0 -D"
# Source default configs.if [ -r /etc/default/passivedns ]; then . /etc/default/passivednsfi
# See how we were called.case "$1" in start) echo -n "Starting $NAME ..." $DAEMON $ARGS > /dev/null 2>&1 echo " done." ;; stop) echo -n "Stopping $NAME ..." start-stop-daemon --oknodo --stop --quiet --pidfile=$PIDFILE --exec $DAEMON rm -f $PIDFILE > /dev/null 2>&1 echo " done." ;; restart) $0 stop $0 start ;; status) if [ -f $PIDFILE ]; then PID=`cat $PIDFILE` ps -p $PID > /dev/null 2>&1 RC=$? if [ "$RC" == "0" ]; then echo "PassiveDNS is running with PID $PID..." else echo "PassiveDNS is not running..." fi else echo "PassiveDNS is not running..." fi ;; force-reload) $0 stop $0 start ;; *) echo "Usage: $0 {start|stop|restart|force-reload|status}" exit 1esac
exit 0
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129#!/bin/sh# $Id$## passivednsd Start/Stop the passivedns daemon.## chkconfig: 2345 40 60# description: passivedns rocks#
# Quick and Dirty script by Eric Kollmann xnih13@gmail.com
lock=/var/lock/subsys/passivednsprog=passivedns
# Source function library.. /etc/rc.d/init.d/functions
# Source the local configuration file. /etc/sysconfig/passivedns
# if there are any non blank values coming from the sysconfig file we'll change them to commands now
if [ "$INTERFACE" != "" ] ; then INTERFACE="-i $INTERFACE"fi
if [ "$PIDFILE" != "" ] ; then PIDFILE="-p $PIDFILE"fi
if [ "$LOGFILE" != "" ] ; then LOGFILE="-l $LOGFILE"fi
if [ "$LOGFIELDS" != "" ] ; then LOGFIELDS="-f $LOGFIELDS"fi
if [ "$NXDOMAINLOGFILE" != "" ] ; then NXDOMAINLOGFILE="-L $NXDOMAINLOGFILE"fi
if [ "$LOGSYSLOG" != "" ] ; then LOGSYSLOG="-y"fi
if [ "$NXSYSLOG" != "" ] ; then NXSYSLOG="-Y"fi
if [ "$BPF" != "" ] ; then BPF="-b \"$BPF\""fi
if [ "$SOFTMEM" != "" ] ; then SOFTMEM="-S $SOFTMEM"fi
if [ "$DNSCACHE" != "" ] ; then DNSCACHE="-C $DNSCACHE"fi
if [ "$DNSDUPE" != "" ] ; then DNSDUPE="-P $DNSDUPE"fi
if [ "$DNSRRTYPES" != "" ] ; then DNSRRTYPES="-X $DNSRRTYPES"fi
if [ "$USER" != "" ] ; then USER="-u $USER"fi
if [ "$GROUP" != "" ] ; then GROUP="-g $GROUP"fi
if [ "$DIRCHROOT" != "" ] ; then DIRCHROOT="-T $DIRCHROOT"fi
######################################
RETVAL=0
function start(){ daemon $prog -D $INTERFACE $PIDFILE $LOGFILE $NXDOMAINLOGFILE $LOGSYSLOG $NXSYSLOG $LOGFIELDS $BPF $SOFTMEM $DNSCACHE $DNSDUPE $DNSRRTYPES $USER $GROUP $DIRCHROOT RETVAL=$? echo [ $RETVAL -eq 0 ] && touch $lock return $RETVAL}
stop(){ killproc $prog RETVAL=$? echo [ $RETVAL -eq 0 ] && rm -f $lock return $RETVAL}
case "$1" in start) echo -n "Starting $prog: " start ;; stop) echo -n "Stopping $prog: " stop ;; restart) stop start ;; condrestart) [ -e $lock ] && stop && start ;; status) status passivedns RETVAL=$? ;;
*) echo "Usage: $0 {start|stop|restart|condrestart|status}" RETVAL=2esac
exit $RETVAL12345678910111213/var/log/passivedns.log { daily rotate 30 missingok notifempty compress delaycompress postrotate /bin/kill -HUP `pgrep passivedns 2>/dev/null` 2>/dev/null || true endscript su root syslog}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566# /etc/sysconfig/passivedns# $Id$# Quick and Dirty Script by Eric Kollmann xnih13@gmail.com
# What interface should passivedns listen on? INTERFACE=
# What user and group should passivedns drop to after starting? # leave blank if you do not want to change privs# if you do change privs you will need to provide that user with writes# on the $PIDFILE directory belowUSER=GROUP=
# Name of passivedns log?LOGFILE=
# Name of NXDOMAIN log?NXDOMAINLOGFILE=
# Log to syslog? (set to "1" to enable)LOGSYSLOG=
# Log NXDOMAIN to syslog? (set to "1" to enable)NXSYSLOG=
# To add a BPF filter to the command line uncomment the following variable# syntax corresponds to tcpdump(8)# default is "port 53"BPF=
# Name of PID file# If you are dropping from root create the /var/run/passivedns folder# and give rights to the $USER $GROUP defined above example:# chown pdns:pdns /var/run/passivedns# otherwise if staying as root just let it be written to /var/run/#PIDFILE=/var/run/passivedns/passivedns.pid#PIDFILE=/var/run/passivedns.pidPIDFILE=
#Soft Memory Limit in MBSOFTMEM=
#Seconds to cache DNS objects in memoryDNSCACHE=
#Seconds between printing duplicate DNS infoDNSDUPE=
#Manually set the values to log:# FIELDS:# H: YMD-HMS Stamp S: Timestamp(s) M: Timestamp(ms) c: Client IP # s: Server IP C: Class Q: Query T: Type # A: Answer t: TTL n: CountLOGFIELDS=SMcsCQTAtn
#Manually set DNS RR Types to care about# FLAGS:# 4:A 6:AAAA C:CNAME D:DNAME N:NAPTR O:SOA# P:PTR R:RP S:SRV T:TXT M:MX n:NS# x:NXDDNSRRTYPES=
#Directory to chroot intoDIRCHROOT=
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657--- search-pdns-original.pl 2017-08-24 19:18:52.859541254 -0400+++ /usr/local/bin/search-pdns.pl 2018-03-21 14:49:24.217877474 -0400@@ -18,6 +18,7 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # ----------------------------------------------------------------------+# Added Resource Record Type : PJN 20180321 use strict; use warnings;@@ -40,7 +41,7 @@ =head1 VERSION - 0.1.0+ 0.1.1 =head1 SYNOPSIS @@ -50,6 +51,7 @@ -s : %IP/Domain% -r : Enables raw search+ -t : Resource Record Type (A, NS, MX, SOA, etc.) --first-seen : Date to search from in iso format (2010-01-01 etc.) --last-seen : Date to search to in iso format (2020-01-01 etc.) --limit : Limit on search results (100)@@ -73,6 +75,7 @@ our $FROM_DATE; our $TO_DATE; our $LIMIT;+our $TYPE; GetOptions( 'd=s' => \$DEBUG,@@ -81,6 +84,7 @@ 'first-seen=s' => \$FROM_DATE, 'last-seen=s' => \$TO_DATE, 'limit=s' => \$LIMIT,+ 't=s' => \$TYPE, ); if ($SEARCH eq "") {@@ -131,6 +135,13 @@ } } ++if (defined $TYPE) {+ $QUERY1 = $QUERY1 . qq[AND maptype = '$TYPE' ];+ $QUERY2 = $QUERY2 . qq[AND maptype = '$TYPE' ];+}++ $QUERY = $QUERY1 . qq[ UNION ] . $QUERY2; if (defined $LIMIT && $LIMIT =~ /^([\d])+$/) {1234567891011121314151617#MakefileAUTOMAKE_OPTIONS = -Wno-portability
OBJECTS=passivedns.o dns.obin_PROGRAMS=passivedns
all: $(bin_PROGRAMS)
%.o: %.c $(CC) -O3 $(CPPFLAGS) -c $< -o $@
passivedns$(EXEEXT): $(OBJECTS) $(CC) -o passivedns $(OBJECTS) $(LDFLAGS)
clean: -rm -v passivedns *.o 2>/dev/null || true
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886/*** This file is a part of PassiveDNS.**** Copyright (C) 2010-2013, Edward Fjellskål <edwardfjellskaal@gmail.com>**** This program is free software; you can redistribute it and/or modify** it under the terms of the GNU General Public License as published by** the Free Software Foundation; either version 2 of the License, or** (at your option) any later version.**** This program is distributed in the hope that it will be useful,** but WITHOUT ANY WARRANTY; without even the implied warranty of** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the** GNU General Public License for more details.**** You should have received a copy of the GNU General Public License** along with this program; if not, write to the Free Software** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.***/
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <time.h>#include <sys/types.h>#include <arpa/inet.h>#include <netinet/in.h>#include <syslog.h>#include <pcap.h>#include "passivedns.h"#include "dns.h"
#ifdef HAVE_JSON#include <jansson.h>#endif /* HAVE_JSON */
extern globalconfig config;
/* The 12th Carol number and 7th Carol prime, 16769023, is also a Carol emirp *///#define DBUCKET_SIZE 16769023#define DBUCKET_SIZE 3967 /* Carol that is primes */
pdns_record *dbucket[DBUCKET_SIZE];
uint64_t hash(unsigned char *str){ uint64_t hash = 5381; uint64_t c;
while ((c = *str++)) hash = ((hash << 5) + hash) + c; /* hash * 33 + c */ return hash % DBUCKET_SIZE;}
void dns_parser(packetinfo *pi){ ldns_status status; ldns_pkt *dns_pkt;
status = LDNS_STATUS_ERR;
/* In DNS tcp messages, the first 2 bytes signal the * amount of data to expect. So we need to skip them in the read. */ if (pi->plen <= 2) return; /* The minimum bytes in a packet, else return */
if (pi->af == AF_INET) { switch (pi->ip4->ip_p) { case IP_PROTO_TCP: status = ldns_wire2pkt(&dns_pkt,pi->payload + 2, pi->plen - 2); break; case IP_PROTO_UDP: status = ldns_wire2pkt(&dns_pkt,pi->payload, pi->plen); break; default: break; } } else if (pi->af == AF_INET6) { switch (pi->ip6->next) { case IP_PROTO_TCP: status = ldns_wire2pkt(&dns_pkt,pi->payload + 2, pi->plen - 2); break; case IP_PROTO_UDP: status = ldns_wire2pkt(&dns_pkt,pi->payload, pi->plen); break; default: break; } }
if (status != LDNS_STATUS_OK) { dlog("[D] ldns_wire2pkt status: %d\n", status); update_dns_stats(pi,ERROR); return; }
/* We don't want to process truncated packets */ if (ldns_pkt_tc(dns_pkt)) { dlog("[D] DNS packet with Truncated (TC) bit set! Skipping!\n"); ldns_pkt_free(dns_pkt); update_dns_stats(pi, ERROR); return; }
/* We only care about answers when we record data */ if (ldns_pkt_qr(dns_pkt)) { /* In situations where the first packet seen is a server response, the client/server determination is incorrectly marked as an SC_CLIENT session prior to the parsing of the DNS payload. In high bandwidth data centers when running against millions of packet capture files, port reuse in the span of a few minutes is not uncommon. This results in all subsequent responses on the reused port being thrown out as if they came from a client. */ if (pi->sc == SC_UNKNOWN || pi->cxt->s_total_pkts == 0) { dlog("[D] DNS Answer without a Question?: Query TID = %d and Answer TID = %d\n", pi->cxt->plid, ldns_pkt_id(dns_pkt)); ldns_pkt_free(dns_pkt); update_dns_stats(pi, ERROR); return; } dlog("[D] DNS Answer\n"); /* Check the DNS TID */ if (pi->cxt->plid == ldns_pkt_id(dns_pkt)) { dlog("[D] DNS Query TID match Answer TID: %d\n", pi->cxt->plid); } else { dlog("[D] DNS Query TID did not match Answer TID: %d != %d - Skipping!\n", pi->cxt->plid, ldns_pkt_id(dns_pkt)); ldns_pkt_free(dns_pkt); update_dns_stats(pi,ERROR); return; }
/* From isc.org wording: * We do not collect any of the query-response traffic that * occurs when the client sets the RD or "Recursion Desired" * bit to 1, that is, the traffic that occurs between DNS * "stub" clients and the caching server itself, since only the * traffic generated in response to a cache miss (RD bit set to 0) * is strictly needed in order to build a passive DNS database. */ if (ldns_pkt_rd(dns_pkt)) { dlog("[D] DNS packet with Recursion Desired (RD) bit set!\n"); /* Between DNS-server to DNS-server, we should drop this kind * of traffic if we are thinking hardening and correctness! * But for people trying this out in a corporate network etc, * between a client and a DNS proxy, will need this most likely * to see any traffic at all. In the future, this might be * controlled by a cmdline switch. */ //ldns_pkt_free(decoded_dns); //return; }
if (!ldns_pkt_qdcount(dns_pkt)) { /* No questions or answers */ dlog("[D] DNS packet did not contain a question. Skipping!\n"); ldns_pkt_free(dns_pkt); update_dns_stats(pi, ERROR); return; }
/* Send it off for processing */ if (process_dns_answer(pi, dns_pkt) < 0) dlog("[D] process_dns_answer() returned -1\n"); } else { /* We need to get the DNS TID from the Query to later match with the * DNS TID in the answer - to harden the implementation. */
/* With the new SC_UNKNOWN state, only responses from an SC_SERVER should be ignored. */ if (pi->sc == SC_SERVER) { dlog("[D] DNS Query not from a client? Skipping!\n"); ldns_pkt_free(dns_pkt); update_dns_stats(pi, ERROR); return; }
/* Check for reuse of a session and a hack for * no timeout of sessions when reading pcaps atm. :/ * 60 Secs are default UDP timeout in cxt, and should * be enough for a TCP session of DNS too. */ if ((pi->cxt->plid != 0 && pi->cxt->plid != ldns_pkt_id(dns_pkt)) && ((pi->cxt->last_pkt_time - pi->cxt->start_time) <= 60)) { dlog("[D] DNS Query on an established DNS session - TID: Old:%d New:%d\n", pi->cxt->plid, ldns_pkt_id(dns_pkt)); /* Some clients have bad or strange random src * port generator and will gladly reuse the same * src port several times in a short time period. * To implement this fully, each cxt should be include * the TID in its tuple, but still this will make a mess :/ */ } else dlog("[D] New DNS Query\n");
if (!ldns_pkt_qdcount(dns_pkt)) { /* No questions or answers */ dlog("[D] DNS Query packet did not contain a question? Skipping!\n"); ldns_pkt_free(dns_pkt); update_dns_stats(pi, ERROR); return; }
if ((pi->cxt->plid = ldns_pkt_id(dns_pkt))) dlog("[D] DNS Query with TID = %d\n", pi->cxt->plid);
else { dlog("[E] Error getting DNS TID from Query!\n"); ldns_pkt_free(dns_pkt); update_dns_stats(pi, ERROR); return; } }
ldns_pkt_free(dns_pkt);}
int process_dns_answer(packetinfo *pi, ldns_pkt *dns_pkt){ int rrcount_query; int j; ldns_rr_list *dns_query_domains; ldns_buffer *dns_buff;
dns_query_domains = ldns_pkt_question(dns_pkt); rrcount_query = ldns_rr_list_rr_count(dns_query_domains); dns_buff = ldns_buffer_new(LDNS_MIN_BUFLEN); dlog("[*] rrcount_query: %d\n", rrcount_query);
/* Do we ever have more than one question? If we do, are we handling it correctly? */ for (j = 0; j < rrcount_query; j++) { ldns_rdf *rdf_data;
rdf_data = ldns_rr_owner(ldns_rr_list_rr(dns_query_domains, j)); dlog("[D] rdf_data: %p\n", rdf_data);
if (cache_dns_objects(pi, rdf_data, dns_buff, dns_pkt) != 0) dlog("[D] cache_dns_objects() returned error\n"); }
ldns_buffer_free(dns_buff); update_dns_stats(pi, SUCCESS); return 0;}
int cache_dns_objects(packetinfo *pi, ldns_rdf *rdf_data, ldns_buffer *buff, ldns_pkt *dns_pkt){ int j; int dns_answer_domain_cnt; uint64_t dnshash; ldns_status status; pdns_record *pr = NULL; ldns_rr_list *dns_answer_domains; unsigned char *domain_name = 0;
ldns_buffer_clear(buff); status = ldns_rdf2buffer_str(buff, rdf_data);
if (status != LDNS_STATUS_OK) { dlog("[D] Error in ldns_rdf2buffer_str(): %d\n", status); return -1; }
dns_answer_domains = ldns_pkt_answer(dns_pkt); dns_answer_domain_cnt = ldns_rr_list_rr_count(dns_answer_domains); domain_name = (unsigned char *) ldns_buffer2str(buff);
if (domain_name == NULL) { dlog("[D] Error in ldns_buffer2str(%p)\n", buff); return -1; } else { dlog("[D] domain_name: %s\n", domain_name); dlog("[D] dns_answer_domain_cnt: %d\n",dns_answer_domain_cnt); }
if (dns_answer_domain_cnt == 0 && ldns_pkt_get_rcode(dns_pkt) != 0) { uint16_t rcode = ldns_pkt_get_rcode(dns_pkt); dlog("[D] Error return code: %d\n", rcode);
/* PROBLEM: * As there is no valid ldns_rr here and we can't fake one that will * be very unique, we cant push this to the normal * bucket[hash->linked_list]. We should probably allocate a static * bucket[MAX_NXDOMAIN] to hold NXDOMAINS, and when that is full, pop * out the oldest (LRU). A simple script querying for random non-existing * domains could easily put stress on passivedns (think conficker etc.) * if the bucket is to big or non-efficient. We would still store data * such as: firstseen,lastseen,client_ip,server_ip,class,query,NXDOMAIN */ if (config.dnsfe & (pdns_chk_dnsfe(rcode))) { ldns_rr_list *dns_query_domains; ldns_rr *rr;
dnshash = hash(domain_name); dlog("[D] Hash: %lu\n", dnshash); /* Check if the node exists, if not, make it */ pr = get_pdns_record(dnshash, pi, domain_name);
/* Set the SRC flag: */ //lname_node->srcflag |= pdns_chk_dnsfe(rcode); dns_query_domains = ldns_pkt_question(dns_pkt); rr = ldns_rr_list_rr(dns_query_domains, 0); if ((pr->last_seen.tv_sec - pr->last_print.tv_sec) >= config.dnsprinttime) { /* Print the SRC Error record */ print_passet(pr, NULL, rr, rdf_data, rcode); } } else dlog("[D] Error return code %d was not processed:%d\n", pdns_chk_dnsfe(rcode), config.dnsfe);
free(domain_name); return 0; }
for (j = 0; j < dns_answer_domain_cnt; j++) { int offset = -1; int to_offset = -1; int len; ldns_rr *rr; ldns_rdf *rname; char *rdomain_name = NULL; char *tmp1 = NULL; char *tmp2 = NULL;
rr = ldns_rr_list_rr(dns_answer_domains, j);
switch (ldns_rr_get_type(rr)) { case LDNS_RR_TYPE_LOC: if (config.dnsf & DNS_CHK_LOC) offset = 0; break; case LDNS_RR_TYPE_GPOS: if (config.dnsf & DNS_CHK_LOC) { offset = 0; to_offset = 3; } break; case LDNS_RR_TYPE_RRSIG: if (config.dnsf & DNS_CHK_DNSSEC) { offset = 0; to_offset = 9; } break; case LDNS_RR_TYPE_DNSKEY: if (config.dnsf & DNS_CHK_DNSSEC) { offset = 0; to_offset = 4; } break;
#ifdef LDNS_RR_TYPE_NSEC3PARAM case LDNS_RR_TYPE_NSEC3PARAM: if (config.dnsf & DNS_CHK_DNSSEC) { offset = 0; to_offset = 4; } break;#endif /* LDNS_RR_TYPE_NSEC3PARAM */ case LDNS_RR_TYPE_NSEC3: if (config.dnsf & DNS_CHK_DNSSEC) { offset = 0; to_offset = 5; } break;
case LDNS_RR_TYPE_NSEC: if (config.dnsf & DNS_CHK_DNSSEC) { offset = 0; to_offset = 2; } break; case LDNS_RR_TYPE_HINFO: if (config.dnsf & DNS_CHK_HINFO) { offset = 0; to_offset = 2; } break; case LDNS_RR_TYPE_DS: if (config.dnsf & DNS_CHK_DNSSEC) { offset = 0; to_offset = 4; } break; case LDNS_RR_TYPE_SSHFP: if (config.dnsf & DNS_CHK_SSHFP) { offset = 0; to_offset = 3; } break; case LDNS_RR_TYPE_AAAA: if (config.dnsf & DNS_CHK_AAAA) offset = 0; break; case LDNS_RR_TYPE_A: if (config.dnsf & DNS_CHK_A) offset = 0; break; case LDNS_RR_TYPE_PTR: if (config.dnsf & DNS_CHK_PTR) offset = 0; break; case LDNS_RR_TYPE_CNAME: if (config.dnsf & DNS_CHK_CNAME) offset = 0; break; case LDNS_RR_TYPE_DNAME: if (config.dnsf & DNS_CHK_DNAME) offset = 0; break; case LDNS_RR_TYPE_NAPTR: if (config.dnsf & DNS_CHK_NAPTR) { offset = 0; to_offset = 6; } break; case LDNS_RR_TYPE_RP: if (config.dnsf & DNS_CHK_RP) offset = 0; break; case LDNS_RR_TYPE_SRV: if (config.dnsf & DNS_CHK_SRV) offset = 3; break; case LDNS_RR_TYPE_TXT: if (config.dnsf & DNS_CHK_TXT) offset = 0; break; case LDNS_RR_TYPE_SPF: if (config.dnsf & DNS_CHK_SPF) offset = 0; break; case LDNS_RR_TYPE_SOA: if (config.dnsf & DNS_CHK_SOA) offset = 0; break; case LDNS_RR_TYPE_MX: if (config.dnsf & DNS_CHK_MX) offset = 1; break; case LDNS_RR_TYPE_NS: if (config.dnsf & DNS_CHK_NS) offset = 0; break; default: offset = -1; dlog("[D] ldns_rr_get_type: %d\n", ldns_rr_get_type(rr)); break; }
if (offset == -1) { dlog("[D] LDNS_RR_TYPE not enabled/supported: %d\n", ldns_rr_get_type(rr)); continue; } do { /* Get the rdf data from the rr */ ldns_buffer_clear(buff); rname = ldns_rr_rdf(rr, offset);
if (rname == NULL) { dlog("[D] ldns_rr_rdf returned: NULL\n"); break; }
ldns_rdf2buffer_str(buff, rname); rdomain_name = (char *) ldns_buffer2str(buff);
if (rdomain_name == NULL) continue; len = strlen(rdomain_name) + 5;
if (tmp1 != NULL) len += strlen(tmp1); tmp2 = malloc(len);
if (tmp1 != NULL) { tmp2 = strcpy(tmp2, tmp1); tmp2 = strcat(tmp2, " "); } else tmp2 = strcpy(tmp2, "");
free(tmp1); tmp2 = strcat(tmp2, rdomain_name); tmp1 = tmp2; free(rdomain_name); offset ++; } while (offset < to_offset);
rdomain_name = tmp1;
if (rname == NULL) continue;
if (rdomain_name == NULL && offset <= 1) { dlog("[D] ldns_buffer2str returned: NULL\n"); continue; } dlog("[D] rdomain_name: %s\n", rdomain_name);
if (pr == NULL) { dnshash = hash(domain_name); dlog("[D] Hash: %lu\n", dnshash); /* Check if the node exists, if not, make it */ pr = get_pdns_record(dnshash, pi, domain_name); }
/* Update the pdns record with the pdns asset */ update_pdns_record_asset(pi, pr, rr, (unsigned char*)rdomain_name);
/* If CNAME, free domain_name, and cp rdomain_name to domain_name */ if (ldns_rr_get_type(rr) == LDNS_RR_TYPE_CNAME) { if (config.dnsf & DNS_CHK_CNAME) { int len; free(domain_name); len = strlen((char *)rdomain_name); domain_name = calloc(1, (len + 1)); strncpy((char *)domain_name, (char *)rdomain_name, len); dnshash = hash(domain_name); dlog("[D] Hash: %lu\n", dnshash); pr = get_pdns_record(dnshash, pi, domain_name); } }
/* Free the rdomain_name */ free(rdomain_name); } free(domain_name); return 0;}
void update_pdns_record_asset(packetinfo *pi, pdns_record *pr, ldns_rr *rr, unsigned char *rdomain_name){ pdns_asset *passet = pr->passet; pdns_asset *head = passet; ldns_rr *prr = NULL; uint32_t len = 0;
dlog("Searching: %u, %s, %s\n", rr->_rr_type, pr->qname, rdomain_name);
while (passet != NULL) { /* If found, update */ dlog("Matching: %u, %s, %s\n",passet->rr->_rr_type, pr->qname, passet->answer); dlog("[*] RR:%u, %u\n", passet->rr->_rr_type, rr->_rr_type); if (passet->rr->_rr_type == rr->_rr_type) { dlog("[*] rr match\n"); dlog("r:%s == a:%s\n", rdomain_name, passet->answer); if (strcmp((const char *)rdomain_name, (const char *)passet->answer) == 0 ) { dlog("[*] rname/answer match\n"); /* We have this, update and if its over 24h since last print - print it, then return */ passet->seen++; memcpy( &passet->last_seen, &pi->pheader->ts, sizeof( struct timeval ) ); passet->af = pi->cxt->af; passet->cip = pi->cxt->s_ip; /* This should always be the client IP */ passet->sip = pi->cxt->d_ip; /* This should always be the server IP */ if (rr->_ttl > passet->rr->_ttl) passet->rr->_ttl = rr->_ttl; /* Catch the highest TTL seen */ dlog("[*] DNS asset updated...\n"); if ((passet->last_seen.tv_sec - passet->last_print.tv_sec) >= config.dnsprinttime) print_passet(pr, passet, passet->rr, NULL, 0); return; } } passet = passet->next; }
/* Else, we got a new passet :) */ if (passet == NULL) { passet = (pdns_asset*) calloc(1, sizeof(pdns_asset)); dlog("[*] Allocated a new dns asset...\n"); config.p_s.dns_assets++; config.dns_assets++; prr = (ldns_rr*) calloc(1, sizeof(ldns_rr)); prr->_owner = rr->_owner; prr->_ttl = rr->_ttl; prr->_rd_count = rr->_rd_count; prr->_rr_type = rr->_rr_type; prr->_rr_class = rr->_rr_class; prr->_rdata_fields = rr->_rdata_fields; passet->seen = 1; passet->rr = prr; } else dlog("[D] BAD\n");
if (head != NULL ) { head->prev = passet; passet->next = head; } else passet->next = NULL;
/* Populate new values */ memcpy( &passet->first_seen, &pi->pheader->ts, sizeof( struct timeval ) ); memcpy( &passet->last_seen, &pi->pheader->ts, sizeof( struct timeval ) ); passet->af = pi->cxt->af; passet->cip = pi->cxt->s_ip; /* This should always be the client IP */ passet->sip = pi->cxt->d_ip; /* This should always be the server IP */ if (pi-> eth_hdr) { memcpy(passet->cmac, pi->eth_hdr->ether_dst, 6 * sizeof(u_char)); memcpy(passet->smac, pi->eth_hdr->ether_src, 6 * sizeof(u_char)); } passet->prev = NULL; len = strlen((char *)rdomain_name); passet->answer = calloc(1, (len + 1)); strncpy((char *)passet->answer, (char *)rdomain_name, len);
dlog("[D] Adding: %u, %s, %s\n",passet->rr->_rr_type, pr->qname, rdomain_name);
pr->passet = passet;
print_passet(pr, passet, passet->rr, NULL, 0);}
const char *u_ntop(const struct in6_addr ip_addr, int af, char *dest){ if (af == AF_INET) { if (!inet_ntop(AF_INET, &IP4ADDR(&ip_addr), dest, INET_ADDRSTRLEN + 1)) { dlog("[E] Something died in inet_ntop\n"); return NULL; } } else if (af == AF_INET6) { if (!inet_ntop(AF_INET6, &ip_addr, dest, INET6_ADDRSTRLEN + 1)) { dlog("[E] Something died in inet_ntop\n"); return NULL; } } return dest;}
void print_passet(pdns_record *l, pdns_asset *p, ldns_rr *rr, ldns_rdf *lname, uint16_t rcode){ FILE *fd = NULL; static char ip_addr_s[INET6_ADDRSTRLEN]; static char ip_addr_c[INET6_ADDRSTRLEN]; char *d = config.log_delimiter; char *proto; char *rr_class; char *rr_type; char *rr_rcode; char buffer[1000] = ""; char *output = buffer; int offset = 0; uint8_t is_err_record = 0;
#ifdef HAVE_JSON json_t *jdata; json_t *json_timestamp_ymdhms; json_t *json_timestamp_s; json_t *json_timestamp_ms; json_t *json_hostname; json_t *json_client; json_t *json_server; json_t *json_proto; json_t *json_class; json_t *json_query; json_t *json_query_len; json_t *json_type; json_t *json_answer; json_t *json_answer_len; json_t *json_ttl; json_t *json_count; size_t data_flags = 0;
/* Print in the same order as inserted */ data_flags |= JSON_PRESERVE_ORDER;
/* No whitespace between fields */ data_flags |= JSON_COMPACT;#endif /* HAVE_JSON */
/* If pdns_asset is not defined, then this is a NXD record */ if (p == NULL) is_err_record = 1;
/* Use the correct file descriptor */ if (is_err_record && config.output_log_nxd) { if (config.logfile_all) fd = config.logfile_fd; else fd = config.logfile_nxd_fd; if (fd == NULL) return; } else if (!is_err_record && config.output_log) { fd = config.logfile_fd; if (fd == NULL) return; }
if (is_err_record) { u_ntop(l->sip, l->af, ip_addr_s); u_ntop(l->cip, l->af, ip_addr_c); } else { u_ntop(p->sip, p->af, ip_addr_s); u_ntop(p->cip, p->af, ip_addr_c); }
proto = malloc(4); rr_class = malloc(10); rr_type = malloc(12); rr_rcode = malloc(20);
switch (l->proto) { case IP_PROTO_TCP: snprintf(proto, 4, "tcp"); break; case IP_PROTO_UDP: snprintf(proto, 4, "udp"); break; default: snprintf(proto, 4, "%d", l->proto); break; }
switch (ldns_rr_get_class(rr)) { case LDNS_RR_CLASS_IN: snprintf(rr_class, 10, "IN"); break; case LDNS_RR_CLASS_CH: snprintf(rr_class, 10, "CH"); break; case LDNS_RR_CLASS_HS: snprintf(rr_class, 10, "HS"); break; case LDNS_RR_CLASS_NONE: snprintf(rr_class, 10, "NONE"); break; case LDNS_RR_CLASS_ANY: snprintf(rr_class, 10, "ANY"); break; default: snprintf(rr_class, 10, "%d", ldns_rr_get_class(rr)); break; }
switch (ldns_rr_get_type(rr)) { case LDNS_RR_TYPE_HINFO: snprintf(rr_type, 10, "HINFO"); break; case LDNS_RR_TYPE_SSHFP: snprintf(rr_type, 10, "SSHFP"); break; case LDNS_RR_TYPE_GPOS: snprintf(rr_type, 10, "GPOS"); break; case LDNS_RR_TYPE_LOC: snprintf(rr_type, 10, "LOC"); break; case LDNS_RR_TYPE_DNSKEY: snprintf(rr_type, 10, "DNSKEY"); break;#ifdef LDNS_RR_TYPE_NSEC3PARAM case LDNS_RR_TYPE_NSEC3PARAM: snprintf(rr_type, 11, "NSEC3PARAM"); break;#endif /* LDNS_RR_TYPE_NSEC3PARAM */ case LDNS_RR_TYPE_NSEC3: snprintf(rr_type, 10, "NSEC3"); break; case LDNS_RR_TYPE_NSEC: snprintf(rr_type, 10, "NSEC"); break; case LDNS_RR_TYPE_RRSIG: snprintf(rr_type, 10, "RRSIG"); break; case LDNS_RR_TYPE_DS: snprintf(rr_type, 10, "DS"); break; case LDNS_RR_TYPE_PTR: snprintf(rr_type, 10, "PTR"); break; case LDNS_RR_TYPE_A: snprintf(rr_type, 10, "A"); break; case LDNS_RR_TYPE_AAAA: snprintf(rr_type, 10, "AAAA"); break; case LDNS_RR_TYPE_CNAME: snprintf(rr_type, 10, "CNAME"); break; case LDNS_RR_TYPE_DNAME: snprintf(rr_type, 10, "DNAME"); break; case LDNS_RR_TYPE_NAPTR: snprintf(rr_type, 10, "NAPTR"); break; case LDNS_RR_TYPE_RP: snprintf(rr_type, 10, "RP"); break; case LDNS_RR_TYPE_SRV: snprintf(rr_type, 10, "SRV"); break; case LDNS_RR_TYPE_TXT: snprintf(rr_type, 10, "TXT"); break; case LDNS_RR_TYPE_SPF: snprintf(rr_type, 10, "SPF"); break; case LDNS_RR_TYPE_SOA: snprintf(rr_type, 10, "SOA"); break; case LDNS_RR_TYPE_NS: snprintf(rr_type, 10, "NS"); break; case LDNS_RR_TYPE_MX: snprintf(rr_type, 10, "MX"); break; default: if (is_err_record) snprintf(rr_type, 10, "%d", ldns_rdf_get_type(lname)); else snprintf(rr_type, 10, "%d", p->rr->_rr_type); break; }
if (is_err_record) { switch (rcode) { case 1: snprintf(rr_rcode, 20, "FORMERR"); break; case 2: snprintf(rr_rcode, 20, "SERVFAIL"); break; case 3: snprintf(rr_rcode, 20, "NXDOMAIN"); break; case 4: snprintf(rr_rcode, 20, "NOTIMPL"); break; case 5: snprintf(rr_rcode, 20, "REFUSED"); break; case 6: snprintf(rr_rcode, 20, "YXDOMAIN"); break; case 7: snprintf(rr_rcode, 20, "YXRRSET"); break; case 8: snprintf(rr_rcode, 20, "NXRRSET"); break; case 9: snprintf(rr_rcode, 20, "NOTAUTH"); break; case 10: snprintf(rr_rcode, 20, "NOTZONE"); break; default: snprintf(rr_rcode, 20, "UNKNOWN-ERROR-%d", rcode); break; } }
#ifdef HAVE_JSON if ((is_err_record && config.use_json_nxd) || (!is_err_record && config.use_json)) { jdata = json_object();
/* Print timestamp(ymdhms) */ if (config.fieldsf & FIELD_TIMESTAMP_YMDHMS) { struct tm *tmpTime; char timestr[200]; tmpTime = localtime(&l->last_seen.tv_sec); strftime(timestr, sizeof(timestr), "%Y-%m-%d %H:%M:%S", tmpTime); json_timestamp_ymdhms = json_string(timestr); json_object_set(jdata, JSON_TIMESTAMP, json_timestamp_ymdhms); json_decref(json_timestamp_ymdhms); }
/* Print timestamp(s) */ if (config.fieldsf & FIELD_TIMESTAMP_S) { json_timestamp_s = json_integer(l->last_seen.tv_sec); json_object_set(jdata, JSON_TIMESTAMP_S, json_timestamp_s); json_decref(json_timestamp_s); }
/* Print timestamp(ms) */ if (config.fieldsf & FIELD_TIMESTAMP_MS) { json_timestamp_ms = json_integer(l->last_seen.tv_usec); json_object_set(jdata, JSON_TIMESTAMP_MS, json_timestamp_ms); json_decref(json_timestamp_ms); }
/* Print hostname */ if (config.fieldsf & FIELD_HOSTNAME) { json_hostname = json_string(config.hostname); json_object_set(jdata, JSON_HOSTNAME, json_hostname); json_decref(json_hostname); }
/* Print client IP */ if (config.fieldsf & FIELD_CLIENT) { json_client = json_string(ip_addr_c); json_object_set(jdata, JSON_CLIENT, json_client); json_decref(json_client); }
/* Print server IP */ if (config.fieldsf & FIELD_SERVER) { json_server = json_string(ip_addr_s); json_object_set(jdata, JSON_SERVER, json_server); json_decref(json_server); }
/* Print protocol */ if (config.fieldsf & FIELD_PROTO) { json_proto = json_string(proto); json_object_set(jdata, JSON_PROTO, json_proto); json_decref(json_proto); }
/* Print class */ if (config.fieldsf & FIELD_CLASS) { json_class = json_string(rr_class); json_object_set(jdata, JSON_CLASS, json_class); json_decref(json_class); }
/* Print query */ if (config.fieldsf & FIELD_QUERY) { json_query = json_string((const char *)l->qname); json_object_set(jdata, JSON_QUERY, json_query); json_decref(json_query); }
/* Print query length */ if (config.fieldsf & FIELD_QUERY_LEN) { json_query_len = json_integer(strlen(l->qname)); json_object_set(jdata, JSON_QUERY_LEN, json_query_len); json_decref(json_query_len); }
/* Print type */ if (config.fieldsf & FIELD_TYPE) { json_type = json_string(rr_type); json_object_set(jdata, JSON_TYPE, json_type); json_decref(json_type); }
if (is_err_record) { /* Print answer */ if (config.fieldsf & FIELD_ANSWER) { json_answer = json_string(rr_rcode); json_object_set(jdata, JSON_ANSWER, json_answer); json_decref(json_answer); }
/* Print answer length */ if (config.fieldsf & FIELD_ANSWER_LEN) { json_answer_len = json_integer(strlen(rr_rcode)); json_object_set(jdata, JSON_ANSWER_LEN, json_answer_len); json_decref(json_answer_len); }
/* Print TTL */ if (config.fieldsf & FIELD_TTL) { json_ttl = json_integer(PASSET_ERR_TTL); json_object_set(jdata, JSON_TTL, json_ttl); json_decref(json_ttl); }
/* Print count */ if (config.fieldsf & FIELD_COUNT) { json_count = json_integer(PASSET_ERR_COUNT); json_object_set(jdata, JSON_COUNT, json_count); json_decref(json_count); } } else { /* Print answer */ if (config.fieldsf & FIELD_ANSWER) { json_answer = json_string((const char *)p->answer); json_object_set(jdata, JSON_ANSWER, json_answer); json_decref(json_answer); }
/* Print answer length */ if (config.fieldsf & FIELD_ANSWER_LEN) { json_answer_len = json_integer(strlen(p->answer)); json_object_set(jdata, JSON_ANSWER_LEN, json_answer_len); json_decref(json_answer_len); }
/* Print TTL */ if (config.fieldsf & FIELD_TTL) { json_ttl = json_integer(p->rr->_ttl); json_object_set(jdata, JSON_TTL, json_ttl); json_decref(json_ttl); }
/* Print count */ if (config.fieldsf & FIELD_COUNT) { json_count = json_integer(p->seen); json_object_set(jdata, JSON_COUNT, json_count); json_decref(json_count); } }
output = json_dumps(jdata, data_flags); json_decref(jdata); if (output == NULL) return; } else {#endif /* HAVE_JSON */ /* Print timestamp */ if ((config.fieldsf & FIELD_TIMESTAMP_YMDHMS)) { struct tm *tmpTime; char timestr[200]; tmpTime = localtime(&l->last_seen.tv_sec); strftime(timestr, sizeof(timestr), "%Y-%m-%d %H:%M:%S", tmpTime); if (is_err_record) offset += snprintf(output, sizeof(buffer) - offset, "%s.%06lu", timestr, l->last_seen.tv_usec); else offset += snprintf(output, sizeof(buffer) - offset, "%s.%06lu", timestr, p->last_seen.tv_usec); } else if ((config.fieldsf & FIELD_TIMESTAMP_S) && (config.fieldsf & FIELD_TIMESTAMP_MS)) { if (is_err_record) offset += snprintf(output, sizeof(buffer) - offset, "%lu.%06lu", l->last_seen.tv_sec, l->last_seen.tv_usec); else offset += snprintf(output, sizeof(buffer) - offset, "%lu.%06lu", p->last_seen.tv_sec, p->last_seen.tv_usec); } else if (config.fieldsf & FIELD_TIMESTAMP_S) { if (is_err_record) offset += snprintf(output, sizeof(buffer) - offset, "%lu", l->last_seen.tv_sec); else offset += snprintf(output, sizeof(buffer) - offset, "%lu", p->last_seen.tv_sec); } else if (config.fieldsf & FIELD_TIMESTAMP_MS) { if (is_err_record) offset += snprintf(output, sizeof(buffer) - offset, "%06lu", l->last_seen.tv_usec); else offset += snprintf(output, sizeof(buffer) - offset, "%06lu", p->last_seen.tv_usec); }
/* Print hostname */ if (config.fieldsf & FIELD_HOSTNAME) { if (offset != 0) offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", d); offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", config.hostname); }
/* Print client IP */ if (config.fieldsf & FIELD_CLIENT) { if (offset != 0) offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", d); offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", ip_addr_c); }
/* Print client hardware address */ if (config.fieldsf & FIELD_CLT_HWADDR) { char buf[128]; if (offset != 0) offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", d); snprintf(buf, 128, "%02x:%02x:%02x:%02x:%02x:%02x", p->cmac[0], p->cmac[1], p->cmac[2], p->cmac[3], p->cmac[4], p->cmac[5]); offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", buf); }
/* Print server IP */ if (config.fieldsf & FIELD_SERVER) { if (offset != 0) offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", d); offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", ip_addr_s); }
/* Print server hardware address */ if (config.fieldsf & FIELD_SRV_HWADDR) { char buf[128]; if (offset != 0) offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", d); snprintf(buf, 128, "%02x:%02x:%02x:%02x:%02x:%02x", p->smac[0], p->smac[1], p->smac[2], p->smac[3], p->smac[4], p->smac[5]); offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", buf); }
/* Print protocol */ if (config.fieldsf & FIELD_PROTO) { if (offset != 0) offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", d); offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", proto); }
/* Print class */ if (config.fieldsf & FIELD_CLASS) { if (offset != 0) offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", d); offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", rr_class); }
/* Print query */ if (config.fieldsf & FIELD_QUERY) { if (offset != 0) offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", d); offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", l->qname); }
/* Print query length */ if (config.fieldsf & FIELD_QUERY_LEN) { if (offset != 0) offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", d); offset += snprintf(output+offset, sizeof(buffer) - offset, "%zd", strlen(l->qname)); }
/* Print type */ if (config.fieldsf & FIELD_TYPE) { if (offset != 0) offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", d); offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", rr_type); }
/* Print answer */ if (config.fieldsf & FIELD_ANSWER) { if (offset != 0) offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", d); if (is_err_record) offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", rr_rcode); else offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", p->answer); }
/* Print answer length*/ if (config.fieldsf & FIELD_ANSWER_LEN) { if (offset != 0) offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", d); if (is_err_record) offset += snprintf(output+offset, sizeof(buffer) - offset, "%zd", strlen(rr_rcode)); else offset += snprintf(output+offset, sizeof(buffer) - offset, "%zd", strlen(p->answer)); }
/* Print TTL */ if (config.fieldsf & FIELD_TTL) { if (offset != 0) offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", d); if (is_err_record) offset += snprintf(output+offset, sizeof(buffer) - offset, "%d", PASSET_ERR_TTL); else offset += snprintf(output+offset, sizeof(buffer) - offset, "%u", p->rr->_ttl); }
/* Print count */ if (config.fieldsf & FIELD_COUNT) { if (offset != 0) offset += snprintf(output+offset, sizeof(buffer) - offset, "%s", d); if (is_err_record) offset += snprintf(output+offset, sizeof(buffer) - offset, "%d", PASSET_ERR_COUNT); else offset += snprintf(output+offset, sizeof(buffer) - offset, "%"PRIu64, p->seen); }
#ifdef HAVE_JSON }#endif /* HAVE_JSON */
/* Print to log file */ if (fd) { fprintf(fd, "%s\n", output); fflush(fd); }
/* Print to syslog */ if ((is_err_record && config.output_syslog_nxd) || (!is_err_record && config.output_syslog)) { openlog(PDNS_IDENT, LOG_NDELAY, LOG_LOCAL7); syslog(LOG_INFO, "%s", output); closelog(); }
if (is_err_record) { l->last_print = l->last_seen; l->seen = 0; } else { p->last_print = p->last_seen; p->seen = 0; }
#ifdef HAVE_JSON if ((is_err_record && config.use_json_nxd) || (!is_err_record && config.use_json)) { /* json_dumps allocate memory that has to be freed */ free(output); }#endif /* HAVE_JSON */
free(proto); free(rr_class); free(rr_type); free(rr_rcode);
}
pdns_record *get_pdns_record(uint64_t dnshash, packetinfo *pi, unsigned char *domain_name){ pdns_record *pdnsr = dbucket[dnshash]; pdns_record *head = pdnsr; uint32_t len = 0;
/* Search through the bucket */ while (pdnsr != NULL) { /* If found, update and return dnsr */ if (strcmp((const char *)domain_name, (const char *)pdnsr->qname) == 0) { /* match :) */ memcpy( &pdnsr->last_seen, &pi->pheader->ts, sizeof( struct timeval ) ); pdnsr->af = pi->cxt->af; pdnsr->cip = pi->cxt->s_ip; /* This should always be the client IP */ pdnsr->sip = pi->cxt->d_ip; /* This should always be the server IP */ if (pi->eth_hdr){ memcpy(pdnsr->cmac, pi->eth_hdr->ether_dst, 6 * sizeof(u_char)); memcpy(pdnsr->smac, pi->eth_hdr->ether_src, 6 * sizeof(u_char)); } return pdnsr; } pdnsr = pdnsr->next; }
/* Else, we got a new dnsr :) */ if (pdnsr == NULL) { pdnsr = (pdns_record*) calloc(1, sizeof(pdns_record)); dlog("[*] Allocated a new dns record...\n"); config.p_s.dns_records++; config.dns_records++; } if (head != NULL) head->prev = pdnsr;
/* Populate new values */ memcpy( &pdnsr->first_seen, &pi->pheader->ts, sizeof( struct timeval ) ); memcpy( &pdnsr->last_seen, &pi->pheader->ts, sizeof( struct timeval ) ); pdnsr->af = pi->cxt->af; pdnsr->nxflag = 0; pdnsr->cip = pi->cxt->s_ip; /* This should always be the client IP */ pdnsr->sip = pi->cxt->d_ip; /* This should always be the server IP */ if (pi->eth_hdr) { memcpy(pdnsr->cmac, pi->eth_hdr->ether_dst, 6 * sizeof(u_char)); memcpy(pdnsr->smac, pi->eth_hdr->ether_src, 6 * sizeof(u_char)); } pdnsr->next = head; pdnsr->prev = NULL; pdnsr->passet = NULL; pdnsr->proto = pi->proto; len = strlen((char *)domain_name); pdnsr->qname = calloc(1, (len + 1)); strncpy((char *)pdnsr->qname, (char *)domain_name, len);
dbucket[dnshash] = pdnsr; return pdnsr;}
void expire_dns_records(){ pdns_record *pdnsr; uint8_t run = 0; time_t expire_t; time_t oldest; expire_t = (config.tstamp.tv_sec - config.dnscachetimeout); oldest = config.tstamp.tv_sec;
dlog("[D] Checking for DNS records to be expired\n");
while (run == 0) { uint32_t iter; run = 1; for (iter = 0; iter < DBUCKET_SIZE; iter++) { pdnsr = dbucket[iter]; while (pdnsr != NULL) { if (pdnsr->last_seen.tv_sec < oldest) /* Find the LRU asset timestamp */ oldest = pdnsr->last_seen.tv_sec;
if (pdnsr->last_seen.tv_sec <= expire_t) { /* Expire the record and all its assets */ /* Remove from the hash */ if (pdnsr->prev) pdnsr->prev->next = pdnsr->next; if (pdnsr->next) pdnsr->next->prev = pdnsr->prev; pdns_record *tmp = pdnsr; pdns_record *tmp_prev = pdnsr->prev;
pdnsr = pdnsr->next;
delete_dns_record(tmp, &dbucket[iter]); if (pdnsr == NULL && tmp_prev == NULL) dbucket[iter] = NULL; } else { /* Search through a domain record for assets to expire */ expire_dns_assets(pdnsr, expire_t); pdnsr = pdnsr->next; } } }
update_config_mem_counters(); /* If we are using more memory than mem_limit_max * decrease expire_t too the oldest seen asset at least */ if (config.mem_limit_size > config.mem_limit_max) { expire_t = (oldest + 300); /* Oldest asset + 5 minutes */ oldest = config.tstamp.tv_sec; run = 0; } }}
void update_config_mem_counters(){ config.mem_limit_size = (sizeof(pdns_record) * config.dns_records) + (sizeof(pdns_asset) * config.dns_assets);
dlog("DNS and Memory stats:\n"); dlog("DNS Records : %12u\n", config.dns_records); dlog("DNS Assets : %12u\n", config.dns_assets); dlog("Current memory size : %12lu Bytes\n", config.mem_limit_size); dlog("Max memory size : %12lu Bytes\n", config.mem_limit_max); dlog("------------------------------------------------\n");}
void expire_all_dns_records(){ pdns_record *pdnsr;
dlog("[D] Expiring all domain records\n");
uint32_t iter; for (iter = 0; iter < DBUCKET_SIZE; iter++) { pdnsr = dbucket[iter]; while (pdnsr != NULL) { /* Expire the record and all its assets */ /* Remove from the hash */ if (pdnsr->prev) pdnsr->prev->next = pdnsr->next; if (pdnsr->next) pdnsr->next->prev = pdnsr->prev; pdns_record *tmp = pdnsr;
pdnsr = pdnsr->next;
delete_dns_record(tmp, &dbucket[iter]); if (pdnsr == NULL) dbucket[iter] = NULL; } }}
void delete_dns_record(pdns_record * pdnsr, pdns_record ** bucket_ptr){ pdns_record *prev = pdnsr->prev; /* Older DNS record */ pdns_record *next = pdnsr->next; /* Newer DNS record */ pdns_asset *asset = pdnsr->passet; pdns_asset *tmp_asset;
dlog("[D] Deleting domain record: %s\n", pdnsr->qname);
/* Delete all domain assets */ while (asset != NULL) { /* Print the asset before we expires if it * has been updated since it last was printed */ if (asset->last_seen.tv_sec > asset->last_print.tv_sec) print_passet(pdnsr, asset, asset->rr, NULL, 0);
else if (asset->last_seen.tv_sec == asset->last_print.tv_sec) { if (asset->last_seen.tv_usec > asset->last_print.tv_usec) print_passet(pdnsr, asset, asset->rr, NULL, 0); } tmp_asset = asset; asset = asset->next; delete_dns_asset(&pdnsr->passet, tmp_asset); }
if (prev == NULL) { /* Beginning of list */ *bucket_ptr = next; /* Not only entry */ if (next) next->prev = NULL; } else if (next == NULL) { /* At end of list! */ prev->next = NULL; } else { /* A node */ prev->next = next; next->prev = prev; }
/* Free and set to NULL */ free(pdnsr->qname); free(pdnsr); pdnsr = NULL; config.dns_records--;}
void expire_dns_assets(pdns_record *pdnsr, time_t expire_t){ dlog("[D] Checking for DNS assets to be expired\n");
pdns_asset *passet = pdnsr->passet;
while (passet != NULL) { if (passet->last_seen.tv_sec <= expire_t) { /* Print the asset before we expires if it has been updated since it last was printed */ if (passet->last_seen.tv_sec > passet->last_print.tv_sec) print_passet(pdnsr, passet, passet->rr, NULL, 0);
else if (passet->last_seen.tv_sec == passet->last_print.tv_sec) { if (passet->last_seen.tv_usec > passet->last_print.tv_usec) print_passet(pdnsr, passet, passet->rr, NULL, 0); } /* Remove the asset from the linked list */ if (passet->prev) passet->prev->next = passet->next; if (passet->next) passet->next->prev = passet->prev; pdns_asset *tmp = passet;
passet = passet->next;
/* Delete the asset */ delete_dns_asset(&pdnsr->passet, tmp); } else passet = passet->next; }}
void delete_dns_asset(pdns_asset **passet_head, pdns_asset *passet){ dlog("[D] Deleting domain asset: %s\n", passet->answer);
if (passet == NULL) return;
pdns_asset *tmp_pa = NULL; pdns_asset *next_pa = NULL; pdns_asset *prev_pa = NULL;
tmp_pa = passet; next_pa = tmp_pa->next; prev_pa = tmp_pa->prev;
if (prev_pa == NULL) { /* Beginning of list */ *passet_head = next_pa; /* Not only entry */ if (next_pa) next_pa->prev = NULL; } else if (next_pa == NULL) { /* At end of list! */ prev_pa->next = NULL; } else { /* A node */ prev_pa->next = next_pa; next_pa->prev = prev_pa; }
free(passet->rr); passet->rr = NULL; free(passet->answer); passet->answer = NULL; free(passet); passet = NULL; config.dns_assets--;}
void update_dns_stats(packetinfo *pi, uint8_t code){ if (pi->af == AF_INET) { switch (pi->ip4->ip_p) { case IP_PROTO_TCP: config.p_s.ip4_dns_tcp++; if (code == SUCCESS) config.p_s.ip4_dec_tcp_ok++; else config.p_s.ip4_dec_tcp_er++; break; case IP_PROTO_UDP: config.p_s.ip4_dns_udp++; if (code == SUCCESS) config.p_s.ip4_dec_udp_ok++; else config.p_s.ip4_dec_udp_er++; break; default: break; } } else if (pi->af == AF_INET6) { switch (pi->ip6->next) { case IP_PROTO_TCP: config.p_s.ip6_dns_tcp++; if (code == SUCCESS) config.p_s.ip6_dec_tcp_ok++; else config.p_s.ip6_dec_tcp_er++; break; case IP_PROTO_UDP: config.p_s.ip6_dns_udp++; if (code == SUCCESS) config.p_s.ip6_dec_udp_ok++; else config.p_s.ip6_dec_udp_er++; break; default: break; } }}
void parse_field_flags(char *args){ int i; int ok = 0; int len = 0; uint8_t tmpf;
tmpf = config.fieldsf; len = strlen(args);
if (len == 0) { plog("[W] No fields are specified!\n"); plog("[*] Continuing with default fields...\n"); return; }
config.fieldsf = 0;
for (i = 0; i < len; i++) { switch(args[i]) { case 'H': /* Timestamp(YMDHMS) */ config.fieldsf |= FIELD_TIMESTAMP_YMDHMS; dlog("[D] Enabling field: FIELD_TIMESTAMP_YMDHMS\n"); ok++; break; case 'S': /* Timestamp(s) */ config.fieldsf |= FIELD_TIMESTAMP_S; dlog("[D] Enabling field: FIELD_TIMESTAMP_S\n"); ok++; break; case 'M': /* Timestamp(ms) */ config.fieldsf |= FIELD_TIMESTAMP_MS; dlog("[D] Enabling field: FIELD_TIMESTAMP_MS\n"); ok++; break; case 'c': /* Client */ config.fieldsf |= FIELD_CLIENT; dlog("[D] Enabling field: FIELD_CLIENT\n"); ok++; break; case 's': /* Server */ config.fieldsf |= FIELD_SERVER; dlog("[D] Enabling field: FIELD_SERVER\n"); ok++; break; case 'C': /* Class */ config.fieldsf |= FIELD_CLASS; dlog("[D] Enabling field: FIELD_CLASS\n"); ok++; break; case 'Q': /* Query */ config.fieldsf |= FIELD_QUERY; dlog("[D] Enabling field: FIELD_QUERY\n"); ok++; break; case 'L': /* Query Length */ config.fieldsf |= FIELD_QUERY_LEN; dlog("[D] Enabling field: FIELD_QUERY_LEN\n"); ok++; break; case 'T': /* Type */ config.fieldsf |= FIELD_TYPE; dlog("[D] Enabling field: FIELD_TYPE\n"); ok++; break; case 'A': /* Answer */ config.fieldsf |= FIELD_ANSWER; dlog("[D] Enabling field: FIELD_ANSWER\n"); ok++; break; case 'l': /* Answer Lenght */ config.fieldsf |= FIELD_ANSWER_LEN; dlog("[D] Enabling field: FIELD_ANSWER_LEN\n"); ok++; break; case 't': /* TTL */ config.fieldsf |= FIELD_TTL; dlog("[D] Enabling field: FIELD_TTL\n"); ok++; break; case 'p': /* Protocol */ config.fieldsf |= FIELD_PROTO; dlog("[D] Enabling field: FIELD_PROTO\n"); ok++; break; case 'n': /* Count */ config.fieldsf |= FIELD_COUNT; dlog("[D] Enabling field: FIELD_COUNT\n"); ok++; break; case 'h': /* Hostname */ config.fieldsf |= FIELD_HOSTNAME; dlog("[D] Enabling field: FIELD_HOSTNAME\n"); ok++; break; case 'w': /* Client hw address */ config.fieldsf |= FIELD_CLT_HWADDR; dlog("[D] Enabling field: FIELD_CLT_HWADDR\n"); ok++; break; case 'W': /* Server hw address */ config.fieldsf |= FIELD_SRV_HWADDR; dlog("[D] Enabling field: FIELD_SRV_HWADDR\n"); ok++; break; default: plog("[*] Unknown field '%c'\n",args[i]); break; } }
if (ok == 0) { plog("[W] No valid fields parsed, continuing with defaults.\n"); config.fieldsf = tmpf; }}
void parse_dns_flags(char *args){ int i; int ok = 0; int len = 0; uint8_t tmpf;
tmpf = config.dnsf; len = strlen(args);
if (len == 0) { plog("[W] No flags are specified!\n"); plog("[*] Continuing with default flags...\n"); return; }
config.dnsf = 0; config.dnsfe = 0;
for (i = 0; i < len; i++){ switch(args[i]) { case 'I': /* HINFO */ config.dnsf |= DNS_CHK_HINFO; dlog("[D] Enabling flag: DNS_CHK_HINFO\n"); ok++; break; case 'H': /* SSHFP */ config.dnsf |= DNS_CHK_SSHFP; dlog("[D] Enabling flag: DNS_CHK_SSHFP\n"); ok++; break; case 'L': /* LOC */ config.dnsf |= DNS_CHK_LOC; dlog("[D] Enabling flag: DNS_CHK_LOC\n"); ok++; break; case 'd': /* DNSSEC */ config.dnsf |= DNS_CHK_DNSSEC; dlog("[D] Enabling flag: DNS_CHK_DNSSEC\n"); ok++; break; case '4': /* A */ config.dnsf |= DNS_CHK_A; dlog("[D] Enabling flag: DNS_CHK_A\n"); ok++; break; case '6': /* AAAA */ config.dnsf |= DNS_CHK_AAAA; dlog("[D] Enabling flag: DNS_CHK_AAAA\n"); ok++; break; case 'P': /* PTR */ config.dnsf |= DNS_CHK_PTR; dlog("[D] Enabling flag: DNS_CHK_PTR\n"); ok++; break; case 'C': /* CNAME */ config.dnsf |= DNS_CHK_CNAME; dlog("[D] Enabling flag: DNS_CHK_CNAME\n"); ok++; break; case 'D': /* DNAME */ config.dnsf |= DNS_CHK_DNAME; dlog("[D] Enabling flag: DNS_CHK_DNAME\n"); ok++; break; case 'N': /* NAPTR */ config.dnsf |= DNS_CHK_NAPTR; dlog("[D] Enabling flag: DNS_CHK_NAPTR\n"); ok++; break; case 'R': /* RP */ config.dnsf |= DNS_CHK_RP; dlog("[D] Enabling flag: DNS_CHK_RP\n"); ok++; break; case 'S': /* SRV */ config.dnsf |= DNS_CHK_SRV; dlog("[D] Enabling flag: DNS_CHK_SRV\n"); ok++; break; case 'F': /* SPF */ config.dnsf |= DNS_CHK_SPF; dlog("[D] Enabling flag: DNS_CHK_SPF\n"); ok++; case 'T': /* TXT */ config.dnsf |= DNS_CHK_TXT; dlog("[D] Enabling flag: DNS_CHK_TXT\n"); ok++; break; case 'O': /* SOA */ config.dnsf |= DNS_CHK_SOA; dlog("[D] Enabling flag: DNS_CHK_SOA\n"); ok++; break; case 'M': /* MX */ config.dnsf |= DNS_CHK_MX; dlog("[D] Enabling flag: DNS_CHK_MX\n"); ok++; break; case 'n': /* NS */ config.dnsf |= DNS_CHK_NS; dlog("[D] Enabling flag: DNS_CHK_NS\n"); ok++; break; case 'f': /* FORMERR */ config.dnsfe |= DNS_SE_CHK_FORMERR; dlog("[D] Enabling flag: DNS_SE_CHK_FORMERR\n"); ok++; break; case 's': /* SERVFAIL */ config.dnsfe |= DNS_SE_CHK_SERVFAIL; dlog("[D] Enabling flag: DNS_SE_CHK_SERVFAIL\n"); ok++; break; case 'x': /* NXDOMAIN */ config.dnsfe |= DNS_SE_CHK_NXDOMAIN; dlog("[D] Enabling flag: DNS_SE_CHK_NXDOMAIN\n"); ok++; break;
case 'o': /* NOTIMPL */ config.dnsfe |= DNS_SE_CHK_NOTIMPL; dlog("[D] Enabling flag: DNS_SE_CHK_NOTIMPL\n"); ok++; break; case 'r': /* REFUSED */ config.dnsfe |= DNS_SE_CHK_REFUSED; dlog("[D] Enabling flag: DNS_SE_CHK_REFUSED\n"); ok++; break; case 'y': /* YXDOMAIN */ config.dnsfe |= DNS_SE_CHK_YXDOMAIN; dlog("[D] Enabling flag: DNS_SE_CHK_YXDOMAIN\n"); ok++; break; case 'e': /* YXRRSET */ config.dnsfe |= DNS_SE_CHK_YXRRSET; dlog("[D] Enabling flag: DNS_SE_CHK_YXRRSET\n"); ok++; break; case 't': /* NXRRSET */ config.dnsfe |= DNS_SE_CHK_NXRRSET; dlog("[D] Enabling flag: DNS_SE_CHK_NXRRSET\n"); ok++; break; case 'a': /* NOTAUTH */ config.dnsfe |= DNS_SE_CHK_NOTAUTH; dlog("[D] Enabling flag: DNS_SE_CHK_NOTAUTH\n"); ok++; break; case 'z': /* NOTZONE */ config.dnsfe |= DNS_SE_CHK_NOTZONE; dlog("[D] Enabling flag: DNS_SE_CHK_NOTZONE\n"); ok++; break; case '\0': dlog("[W] Bad DNS flag - ending flag checks!\n"); ok = 0; continue; default: plog("[*] Unknown DNS flag '%c'\n",args[i]); break; } }
if (ok == 0) { plog("[W] No valid flags parsed, continuing with defaults.\n"); config.dnsf = tmpf; }}
uint16_t pdns_chk_dnsfe(uint16_t rcode){ uint16_t retcode = 0x0000;
switch (rcode) { case 1: retcode = DNS_SE_CHK_FORMERR; break; case 2: retcode = DNS_SE_CHK_SERVFAIL; break; case 3: retcode = DNS_SE_CHK_NXDOMAIN; break; case 4: retcode = DNS_SE_CHK_NOTIMPL; break; case 5: retcode = DNS_SE_CHK_REFUSED; break; case 6: retcode = DNS_SE_CHK_YXDOMAIN; break; case 7: retcode = DNS_SE_CHK_YXRRSET; break; case 8: retcode = DNS_SE_CHK_NXRRSET; break; case 9: retcode = DNS_SE_CHK_NOTAUTH; break; case 10: retcode = DNS_SE_CHK_NOTZONE; break; default: retcode = 0x0000; /* UNKNOWN-ERROR */ break; }
return retcode;}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187/*** This file is a part of PassiveDNS.**** Copyright (C) 2010-2013, Edward Fjellskål <edwardfjellskaal@gmail.com>**** This program is free software; you can redistribute it and/or modify** it under the terms of the GNU General Public License as published by** the Free Software Foundation; either version 2 of the License, or** (at your option) any later version.**** This program is distributed in the hope that it will be useful,** but WITHOUT ANY WARRANTY; without even the implied warranty of** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the** GNU General Public License for more details.**** You should have received a copy of the GNU General Public License** along with this program; if not, write to the Free Software** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.***/
#ifndef DNS_H#define DNS_H
#include <ldns/ldns.h>
/* Default flags for types to handle */#define DNS_CHK_AAAA 0x00000001#define DNS_CHK_A 0x00000002#define DNS_CHK_PTR 0x00000004#define DNS_CHK_CNAME 0x00000008#define DNS_CHK_DNAME 0x00000010#define DNS_CHK_NAPTR 0x00000020#define DNS_CHK_RP 0x00000040#define DNS_CHK_SRV 0x00000080#define DNS_CHK_TXT 0x00000100#define DNS_CHK_SOA 0x00000200#define DNS_CHK_MX 0x00000400#define DNS_CHK_NS 0x00000800#define DNS_CHK_DNSSEC 0x00001000#define DNS_CHK_LOC 0x00002000#define DNS_CHK_SPF 0x00004000#define DNS_CHK_SSHFP 0x00008000#define DNS_CHK_HINFO 0x00010000#define DNS_CHK_ALL 0x80000000/* Default flags for Server Errors to handle */#define DNS_SE_CHK_FORMERR 0x0001#define DNS_SE_CHK_SERVFAIL 0x0002#define DNS_SE_CHK_NXDOMAIN 0x0004#define DNS_SE_CHK_NOTIMPL 0x0008#define DNS_SE_CHK_REFUSED 0x0010#define DNS_SE_CHK_YXDOMAIN 0x0020#define DNS_SE_CHK_YXRRSET 0x0040#define DNS_SE_CHK_NXRRSET 0x0080#define DNS_SE_CHK_NOTAUTH 0x0100#define DNS_SE_CHK_NOTZONE 0x0200#define DNS_SE_CHK_ALL 0x8000
/* Flag for indicating an NXDOMAIN */#define DNS_NXDOMAIN 0x01
/* Flags for which fields to print */#define FIELD_TIMESTAMP_S 0x00001#define FIELD_TIMESTAMP_MS 0x00002#define FIELD_CLIENT 0x00004#define FIELD_SERVER 0x00008#define FIELD_CLASS 0x00010#define FIELD_QUERY 0x00020#define FIELD_TYPE 0x00040#define FIELD_ANSWER 0x00080#define FIELD_TTL 0x00100#define FIELD_COUNT 0x00200#define FIELD_TIMESTAMP_YMDHMS 0x00400#define FIELD_PROTO 0x00800#define FIELD_HOSTNAME 0x01000#define FIELD_QUERY_LEN 0x02000#define FIELD_ANSWER_LEN 0x04000#define FIELD_CLT_HWADDR 0x08000#define FIELD_SRV_HWADDR 0x10000
/* Static values for print_passet() */#define PASSET_ERR_TTL 0#define PASSET_ERR_COUNT 1
/* Syslog */#define PDNS_IDENT "passivedns"
/* JSON fields used when printing PDNS */#define JSON_TIMESTAMP "timestamp"#define JSON_TIMESTAMP_S "timestamp_s"#define JSON_TIMESTAMP_MS "timestamp_ms"#define JSON_CLIENT "client"#define JSON_SERVER "server"#define JSON_PROTO "proto"#define JSON_CLASS "class"#define JSON_QUERY "query"#define JSON_QUERY_LEN "query_len"#define JSON_TYPE "type"#define JSON_ANSWER "answer"#define JSON_ANSWER_LEN "answer_len"#define JSON_TTL "ttl"#define JSON_COUNT "count"#define JSON_HOSTNAME "hostname"
/* To avoid spaming the logfile with duplicate dns info * we only print a dns record one time each 24H. This way * you will get a last seen timestamp update once a day * at least. If the record changes, it will be classified * as a new record, and printent. If a record expires and * it has been updated since last_print time, it will be * printed again. */#define DNSPRINTTIME 86400 /* 24H = 86400 sec */
/* How long we should hold a dns record in our internal * cache. It should preferably not be less than DNSPRINTTIME, * as that will make it possible to get more than one instance * of the record each day in the logfile. That said, setting * DNSCACHETIMEOUT to DNSPRINTTIME/2 etc, might help memory * usage if that is a concern AND you probably will get a better * granularity on the DNS time stamps in the log file. * My recomendations are DNSPRINTTIME == 24h and * DNSCACHETIMEOUT == 12h. */#define DNSCACHETIMEOUT 43200 /* 12h=43200sec */
/* HASH: * [DOMAIN_HASH_BUCKET]_ * |__[Q-TYPE_BUCKET]_<--- PTR,MX,A... * |__[RESPONCE-NAME] <--- FOR PTR is the IPv4/IPv6 */
typedef struct _pdns_asset { struct timeval first_seen; /* First seen (unix timestamp) */ struct timeval last_seen; /* Last seen (unix timestamp) */ struct timeval last_print; /* Last time asset was printet */ struct ldns_struct_rr *rr; /* PTR,MX,TXT,A,AAAA... */ uint64_t seen; /* Number of times seen */ unsigned char *answer; /* Answer, like 8.8.8.8 or 2001:67c:21e0::16 */ uint32_t af; /* IP version (4/6) AF_INET */ struct in6_addr sip; /* DNS Server IP (v4/6) */ u_char smac[6]; /* DNS Server MAC address */ struct in6_addr cip; /* DNS Client IP (v4/6) */ u_char cmac[6]; /* DNS Client MAC address */ struct _pdns_asset *next; /* Next dns asset */ struct _pdns_asset *prev; /* Prev dns asset */} pdns_asset;
typedef struct _pdns_record { struct timeval first_seen; /* First seen (unix timestamp) */ struct timeval last_seen; /* Last seen (unix timestamp) */ struct timeval last_print; /* Last time record(NXD) was printet */ uint64_t seen; /* Number of times seen */ unsigned char *qname; /* Query name (gamelinux.org) */ uint8_t nxflag; /* Flag to indicate if this is a NXDOMAIN */ uint32_t af; /* IP version (4/6) AF_INET */ struct in6_addr sip; /* DNS Server IP (v4/6) */ u_char smac[6]; /* DNS Server MAC address */ struct in6_addr cip; /* DNS Client IP (v4/6) */ u_char cmac[6]; /* DNS Client MAC address */ uint8_t proto; /* Protocol */ pdns_asset *passet; /* Head of dns assets */ struct _pdns_record *next; /* Next dns record */ struct _pdns_record *prev; /* Prev dns record */} pdns_record;
/* Declare */int process_dns_answer (packetinfo *pi, ldns_pkt *decoded_dns);int cache_dns_objects (packetinfo *pi, ldns_rdf *rdf_data, ldns_buffer *buff, ldns_pkt *dns_pkt);pdns_record *get_pdns_record (uint64_t dnshash, packetinfo *pi, unsigned char *domain_name);const char *u_ntop (const struct in6_addr ip_addr, int af, char *dest);void dns_parser (packetinfo *pi);void update_pdns_record_asset (packetinfo *pi, pdns_record *pr, ldns_rr *rr, unsigned char *rdomain_name);void print_passet (pdns_record *l, pdns_asset *p, ldns_rr *rr, ldns_rdf *lname, uint16_t rcode);void expire_dns_assets (pdns_record *pdnsr, time_t expire_t);void expire_dns_records();void expire_all_dns_records();void delete_dns_record (pdns_record *pdnsr, pdns_record **bucket_ptr);void delete_dns_asset (pdns_asset **passet_head, pdns_asset *passet);void update_config_mem_counters();void parse_field_flags (char *args);void parse_dns_flags (char *args);void update_dns_stats(packetinfo *pi, uint8_t code);uint16_t pdns_chk_dnsfe(uint16_t rcode);
#endif /* DNS_H */
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603/*** This file is a part of PassiveDNS.**** Copyright (C) 2010-2013, Edward Fjellskål <edwardfjellskaal@gmail.com>**** This program is free software; you can redistribute it and/or modify** it under the terms of the GNU General Public License as published by** the Free Software Foundation; either version 2 of the License, or** (at your option) any later version.**** This program is distributed in the hope that it will be useful,** but WITHOUT ANY WARRANTY; without even the implied warranty of** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the** GNU General Public License for more details.**** You should have received a copy of the GNU General Public License** along with this program; if not, write to the Free Software** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.***/
/* I N C L U D E S **********************************************************/#include "config.h"#include <stdio.h>#include <stdlib.h>#include <libgen.h>#include <string.h>#include <arpa/inet.h>#include <netinet/in.h>#include <signal.h>#include <pcap.h>#include <getopt.h>#include <time.h>#include <sys/types.h>#include <grp.h>#include <pwd.h>#include <unistd.h>#include <sys/stat.h>#include <sys/types.h>#include <syslog.h>#include <fcntl.h>#include <errno.h>#include <ctype.h>#include <limits.h>#include "passivedns.h"#include "dns.h"
#ifdef HAVE_JSON#include <jansson.h>#endif /* HAVE_JSON */
#ifdef HAVE_PFRING#include <pfring.h>#endif /* HAVE_PFRING */
#ifndef CONFDIR#define CONFDIR "/etc/passivedns/"#endif
/* G L O B A L S *** (or candidates for refactoring, as we say)***********/globalconfig config;connection *bucket[BUCKET_SIZE];static volatile sig_atomic_t signal_reopen_log_files = 0;
/* I N T E R N A L P R O T O T Y P E S ***********************************/static void usage();static void show_version();void check_vlan (packetinfo *pi);void prepare_null (packetinfo *pi);void prepare_raw (packetinfo *pi);void prepare_sll (packetinfo *pi);void prepare_eth (packetinfo *pi);void prepare_ip4 (packetinfo *pi);void prepare_ip4ip (packetinfo *pi);void prepare_ip6 (packetinfo *pi);void prepare_ip6ip (packetinfo *pi);void prepare_udp (packetinfo *pi);void prepare_tcp (packetinfo *pi);void parse_eth (packetinfo *pi);void parse_ip4 (packetinfo *pi);void parse_ip6 (packetinfo *pi);void parse_udp (packetinfo *pi);void parse_tcp (packetinfo *pi);const char *u_ntop_src(packetinfo *pi, char *dest);void set_pkt_end_ptr (packetinfo *pi);void check_interrupt();void end_sessions();void set_end_sessions();void set_end_dns_records();void cxt_init();int connection_tracking(packetinfo *pi);connection *cxt_new(packetinfo *pi);void del_connection(connection *, connection **);void print_pdns_stats();void free_config();void reopen_log_files();void game_over ();void got_packet(u_char *useless, const struct pcap_pkthdr *pheader, const u_char *packet);#ifdef HAVE_PFRINGvoid pfring_got_packet(const struct pfring_pkthdr *pfheader, const u_char *packet, const u_char *useless);#endif /* HAVE_PFRING */
/* F U N C T I O N S ********************************************************/
#ifdef HAVE_PFRING
void pfring_got_packet(const struct pfring_pkthdr *pfheader, const u_char *packet, const u_char *useless){ /* pcap_pkthdr and pfring_pkthdr are identical to each other*/ struct pcap_pkthdr *pheader = (struct pcap_pkthdr *)pfheader;
/* Set timestamp if it's not set */ if (pheader->ts.tv_sec == 0) pheader->ts.tv_sec = time(NULL);
/* pfring_loop orders the arguments differently than pcap_loop */ got_packet((u_char *)useless, (const struct pcap_pkthdr *)pheader, packet);}
#endif /* HAVE_PFRING */
void got_packet(u_char *useless, const struct pcap_pkthdr *pheader, const u_char *packet){ config.p_s.got_packets++; packetinfo pstruct = {0}; packetinfo *pi = &pstruct; pi->packet = packet; pi->pheader = pheader; set_pkt_end_ptr (pi); memcpy( &config.tstamp, &pi->pheader->ts, sizeof( struct timeval ) ); /* Global */
if (signal_reopen_log_files) reopen_log_files();
if (config.intr_flag != 0) { check_interrupt(); } config.inpacket = 1;
switch (config.linktype) { case DLT_NULL: prepare_null(pi); break; case DLT_RAW: prepare_raw(pi); break;#ifdef DLT_LINUX_SLL case DLT_LINUX_SLL: prepare_sll(pi); break;#endif default: prepare_eth(pi); check_vlan(pi); break; }
switch (pi->eth_type) { case ETHERNET_TYPE_IP: prepare_ip4(pi); parse_ip4(pi); break; case ETHERNET_TYPE_IPV6: prepare_ip6(pi); parse_ip6(pi); break; default: config.p_s.otherl_recv++; //vlog(0x3, "[*] ETHERNET TYPE : %x\n",pi->eth_hdr->eth_ip_type); break; }
config.inpacket = 0;}
void prepare_null(packetinfo *pi){ pi->eth_hlen = LOOPBACK_HDR_LEN; if ((u_int32_t)*pi->packet == AF_INET) { pi->eth_type = ETHERNET_TYPE_IP; } else { pi->eth_type = ETHERNET_TYPE_IPV6; }}
void prepare_raw(packetinfo *pi){ pi->eth_hlen = 0; if (IP_V((ip4_header *)pi->packet) == 4) pi->eth_type = ETHERNET_TYPE_IP; else pi->eth_type = ETHERNET_TYPE_IPV6;}
void prepare_sll(packetinfo *pi){ pi->eth_hlen = SLL_HDR_LEN;
if (IP_V((ip4_header *)(pi->packet + SLL_HDR_LEN)) == 4) pi->eth_type = ETHERNET_TYPE_IP; else pi->eth_type = ETHERNET_TYPE_IPV6;}
void prepare_eth(packetinfo *pi){ if (pi->packet + ETHERNET_HEADER_LEN > pi->end_ptr) return;
config.p_s.eth_recv++; pi->eth_hdr = (ether_header *) (pi->packet); pi->eth_type = ntohs(pi->eth_hdr->eth_ip_type); pi->eth_hlen = ETHERNET_HEADER_LEN;}
void check_vlan(packetinfo *pi){ if (pi->eth_type == ETHERNET_TYPE_8021Q) { vlog(0x3, "[*] ETHERNET TYPE 8021Q\n"); config.p_s.vlan_recv++; pi->vlan = pi->eth_hdr->eth_8_vid; pi->eth_type = ntohs(pi->eth_hdr->eth_8_ip_type); pi->eth_hlen += 4; if ( pi->eth_type == ETHERNET_TYPE_8021Q ) { vlog(0x3, "[*] ETHERNET TYPE 8021Q in 8021Q\n"); pi->eth_type = ntohs(pi->eth_hdr->eth_82_ip_type); pi->eth_hlen += 4; pi->vlan = pi->eth_hdr->eth_82_vid; } } else if (pi->eth_type == (ETHERNET_TYPE_802Q1MT | ETHERNET_TYPE_802Q1MT2 | ETHERNET_TYPE_802Q1MT3 | ETHERNET_TYPE_8021AD)) { vlog(0x3, "[*] ETHERNET TYPE 802Q1MT\n"); pi->mvlan = pi->eth_hdr->eth_82_mvid; pi->eth_type = ntohs(pi->eth_hdr->eth_82_ip_type); pi->eth_hlen += 8; }}
void prepare_ip4(packetinfo *pi){ config.p_s.ip4_recv++; pi->af = AF_INET; pi->ip4 = (ip4_header *) (pi->packet + pi->eth_hlen); pi->packet_bytes = (pi->ip4->ip_len - (IP_HL(pi->ip4) * 4));}
void parse_ip4(packetinfo *pi){ /* Paranoia */ if (((pi->packet + pi->eth_hlen) + (IP_HL(pi->ip4) * 4)) > pi->end_ptr) { dlog("[D] Refusing to parse IPv4 packet: IPv4-hdr passed end_ptr\n"); return; }
switch (pi->ip4->ip_p) { case IP_PROTO_TCP: prepare_tcp(pi); parse_tcp(pi); break; case IP_PROTO_UDP: prepare_udp(pi); parse_udp(pi); break; case IP_PROTO_IP4: prepare_ip4ip(pi); break; case IP_PROTO_IP6: prepare_ip4ip(pi); break; default: break; }}
void prepare_ip6ip(packetinfo *pi){ packetinfo pipi; memset(&pipi, 0, sizeof(packetinfo)); config.p_s.ip6ip_recv++; pipi.pheader = pi->pheader; pipi.packet = (pi->packet + pi->eth_hlen + IP6_HEADER_LEN); pipi.end_ptr = pi->end_ptr;
if (pi->ip6->next == IP_PROTO_IP4) { prepare_ip4(&pipi); parse_ip4(&pipi); } else { prepare_ip6(&pipi); parse_ip6(&pipi); }}
void prepare_ip4ip(packetinfo *pi){ packetinfo pipi; memset(&pipi, 0, sizeof(packetinfo)); config.p_s.ip4ip_recv++; pipi.pheader = pi->pheader; pipi.packet = (pi->packet + pi->eth_hlen + (IP_HL(pi->ip4) * 4)); pipi.end_ptr = pi->end_ptr;
if (pi->ip4->ip_p == IP_PROTO_IP4) { prepare_ip4(&pipi); parse_ip4(&pipi); } else { prepare_ip6(&pipi); parse_ip6(&pipi); }}
void prepare_ip6(packetinfo *pi){ config.p_s.ip6_recv++; pi->af = AF_INET6; pi->ip6 = (ip6_header *) (pi->packet + pi->eth_hlen); pi->packet_bytes = pi->ip6->len;}
void parse_ip6(packetinfo *pi){ switch (pi->ip6->next) { case IP_PROTO_TCP: prepare_tcp(pi); parse_tcp(pi); break; case IP_PROTO_UDP: prepare_udp(pi); parse_udp(pi); break; case IP_PROTO_IP4: prepare_ip6ip(pi); break; case IP_PROTO_IP6: prepare_ip6ip(pi); break; default: break; }}
void set_pkt_end_ptr(packetinfo *pi){ /* Paranoia! */ if (pi->pheader->len <= SNAPLENGTH) pi->end_ptr = (pi->packet + pi->pheader->len); else pi->end_ptr = (pi->packet + SNAPLENGTH);}
void prepare_tcp(packetinfo *pi){ config.p_s.tcp_recv++; if (pi->af == AF_INET) { vlog(0x3, "[*] IPv4 PROTOCOL TYPE TCP:\n"); pi->tcph = (tcp_header *) (pi->packet + pi->eth_hlen + (IP_HL(pi->ip4) * 4)); pi->plen = (pi->pheader->caplen - (TCP_OFFSET(pi->tcph)) * 4 - (IP_HL(pi->ip4) * 4) - pi->eth_hlen); pi->payload = (pi->packet + pi->eth_hlen + (IP_HL(pi->ip4) * 4) + (TCP_OFFSET(pi->tcph) * 4)); } else if (pi->af == AF_INET6) { vlog(0x3, "[*] IPv6 PROTOCOL TYPE TCP:\n"); pi->tcph = (tcp_header *) (pi->packet + pi->eth_hlen + IP6_HEADER_LEN); pi->plen = (pi->pheader->caplen - (TCP_OFFSET(pi->tcph)) * 4 - IP6_HEADER_LEN - pi->eth_hlen); pi->payload = (pi->packet + pi->eth_hlen + IP6_HEADER_LEN + (TCP_OFFSET(pi->tcph)*4)); } pi->proto = IP_PROTO_TCP; pi->s_port = pi->tcph->src_port; pi->d_port = pi->tcph->dst_port; connection_tracking(pi);}
void prepare_udp(packetinfo *pi){ config.p_s.udp_recv++; if (pi->af == AF_INET) { vlog(0x3, "[*] IPv4 PROTOCOL TYPE UDP:\n"); pi->udph = (udp_header *) (pi->packet + pi->eth_hlen + (IP_HL(pi->ip4) * 4)); pi->plen = pi->pheader->caplen - UDP_HEADER_LEN - (IP_HL(pi->ip4) * 4) - pi->eth_hlen; pi->payload = (pi->packet + pi->eth_hlen + (IP_HL(pi->ip4) * 4) + UDP_HEADER_LEN); } else if (pi->af == AF_INET6) { vlog(0x3, "[*] IPv6 PROTOCOL TYPE UDP:\n"); pi->udph = (udp_header *) (pi->packet + pi->eth_hlen + IP6_HEADER_LEN); pi->plen = pi->pheader->caplen - UDP_HEADER_LEN - IP6_HEADER_LEN - pi->eth_hlen; pi->payload = (pi->packet + pi->eth_hlen + IP6_HEADER_LEN + UDP_HEADER_LEN); } pi->proto = IP_PROTO_UDP; pi->s_port = pi->udph->src_port; pi->d_port = pi->udph->dst_port; connection_tracking(pi);}
void parse_tcp(packetinfo *pi){ if (pi->plen <= 0) return;
/* Reliable traffic comes from the servers (normally on port 53 or 5353) * and the client has sent at least one packet on that * connecton (Maybe asking for an aswer :) */ dlog("[D] Parsing TCP packet...\n"); dns_parser(pi);}
void parse_udp(packetinfo *pi){ if (pi->plen <= 0) return;
/* Reliable traffic comes from the servers (normally on port 53 or 5353) * and the client has sent at least one packet on that * connecton (Maybe asking for an aswer :) */ dlog("[D] Parsing UDP packet...\n"); dns_parser(pi);}
int connection_tracking(packetinfo *pi){ struct in6_addr *ip_src; struct in6_addr *ip_dst; struct in6_addr ips; struct in6_addr ipd; uint16_t src_port = pi->s_port; uint16_t dst_port = pi->d_port; int af = pi->af; connection *cxt = NULL; connection *head = NULL; uint32_t hash;
if(af == AF_INET6){ ip_src = &PI_IP6SRC(pi); ip_dst = &PI_IP6DST(pi); } else {#ifdef BSD_DERIVED ips.__u6_addr.__u6_addr32[0] = pi->ip4->ip_src; ipd.__u6_addr.__u6_addr32[0] = pi->ip4->ip_dst;#else ips.s6_addr32[0] = pi->ip4->ip_src; ipd.s6_addr32[0] = pi->ip4->ip_dst;#endif ip_src = &ips; ip_dst = &ipd; }
/* Find the right connection bucket */ if (af == AF_INET) hash = CXT_HASH4(IP4ADDR(ip_src), IP4ADDR(ip_dst), src_port, dst_port, pi->proto); else if (af == AF_INET6) hash = CXT_HASH6(ip_src, ip_dst, src_port, dst_port, pi->proto); else { dlog("[D] Only CTX with AF_INET and AF_INET6 are supported: %d\n", af); return 0; }
cxt = bucket[hash]; head = cxt;
/* Search through the bucket */ while (cxt != NULL) { /* Two-way compare of given connection against connection table */ if (af == AF_INET) { if (CMP_CXT4(cxt, IP4ADDR(ip_src), src_port, IP4ADDR(ip_dst), dst_port)) { /* Client sends first packet (TCP/SYN - UDP?) hence this is a client */ dlog("[D] Found existing v4 client connection.\n"); return cxt_update_client(cxt, pi); } else if (CMP_CXT4(cxt, IP4ADDR(ip_dst), dst_port, IP4ADDR(ip_src), src_port)) {
if (pi->sc == SC_SERVER) { /* This is a server */ dlog("[D] Found existing v4 server connection.\n"); return cxt_update_server(cxt, pi); } else { /* This is a client, where we saw a mid-stream DNS response first */ dlog("[D] Found existing unknown v4 server connection.\n"); return cxt_update_client(cxt, pi); } } } else if (af == AF_INET6) { if (CMP_CXT6(cxt, ip_src, src_port, ip_dst, dst_port)) { dlog("[D] Found existing v6 client connection.\n"); return cxt_update_client(cxt, pi); } else if (CMP_CXT6(cxt, ip_dst, dst_port, ip_src, src_port)) { dlog("[D] Found existing v6 client connection.\n"); return cxt_update_server(cxt, pi); } } cxt = cxt->next; } /* Bucket turned upside down didn't yield anything. New connection */ dlog("[D] New connection.\n"); cxt = cxt_new(pi);
/* New connections are pushed on to the head of bucket[s_hash] */ cxt->next = head; if (head != NULL) /* Are we double linked? */ head->prev = cxt;
bucket[hash] = cxt; pi->cxt = cxt; return cxt_update_unknown(cxt, pi);}
/* Freshly smelling connection :d */connection *cxt_new(packetinfo *pi){ struct in6_addr ips; struct in6_addr ipd; connection *cxt; config.cxtrackerid++; cxt = (connection *) calloc(1, sizeof(connection)); cxt->cxid = config.cxtrackerid; cxt->af = pi->af;
if (pi->tcph) cxt->s_tcpFlags |= pi->tcph->t_flags;
cxt->start_time = pi->pheader->ts.tv_sec; cxt->last_pkt_time = pi->pheader->ts.tv_sec;
if (pi->af == AF_INET6){ cxt->s_ip = PI_IP6SRC(pi); cxt->d_ip = PI_IP6DST(pi); } else {#ifdef BSD_DERIVED ips.__u6_addr.__u6_addr32[0] = pi->ip4->ip_src; ipd.__u6_addr.__u6_addr32[0] = pi->ip4->ip_dst;#else ips.s6_addr32[0] = pi->ip4->ip_src; ipd.s6_addr32[0] = pi->ip4->ip_dst;#endif cxt->s_ip = ips; cxt->d_ip = ipd; }
cxt->s_port = pi->s_port; cxt->d_port = pi->d_port; cxt->proto = pi->proto;
cxt->check = 0x00; cxt->reversed = 0; config.curcxt++;
return cxt;}
int cxt_update_client(connection *cxt, packetinfo *pi){ cxt->last_pkt_time = pi->pheader->ts.tv_sec;
if (pi->tcph) cxt->s_tcpFlags |= pi->tcph->t_flags;
cxt->s_total_bytes += pi->packet_bytes; cxt->s_total_pkts += 1;
pi->cxt = cxt; pi->sc = SC_CLIENT;
if (cxt->s_total_bytes > MAX_BYTE_CHECK || cxt->s_total_pkts > MAX_PKT_CHECK) { return 0; /* Don't Check! */ }
return SC_CLIENT;}
int cxt_update_unknown(connection *cxt, packetinfo *pi){ cxt->last_pkt_time = pi->pheader->ts.tv_sec;
if (pi->tcph) cxt->s_tcpFlags |= pi->tcph->t_flags;
cxt->s_total_bytes += pi->packet_bytes; cxt->s_total_pkts += 1;
pi->cxt = cxt; pi->sc = SC_UNKNOWN;
if (cxt->s_total_bytes > MAX_BYTE_CHECK || cxt->s_total_pkts > MAX_PKT_CHECK) { return 0; /* Don't Check! */ }
return SC_UNKNOWN;}
int cxt_update_server(connection *cxt, packetinfo *pi){ cxt->last_pkt_time = pi->pheader->ts.tv_sec;
if (pi->tcph) cxt->d_tcpFlags |= pi->tcph->t_flags;
cxt->d_total_bytes += pi->packet_bytes; cxt->d_total_pkts += 1;
pi->cxt = cxt; pi->sc = SC_SERVER;
if (cxt->d_total_bytes > MAX_BYTE_CHECK || cxt->d_total_pkts > MAX_PKT_CHECK) return 0; /* Don't check! */
return SC_SERVER;}
void end_all_sessions(){ connection *cxt; int cxkey; config.llcxt = 0;
for (cxkey = 0; cxkey < BUCKET_SIZE; cxkey++) { cxt = bucket[cxkey]; while (cxt != NULL) { config.llcxt++; if (cxt->prev) cxt->prev->next = cxt->next; if (cxt->next) cxt->next->prev = cxt->prev; connection *tmp = cxt;
cxt = cxt->next; del_connection(tmp, &bucket[cxkey]); if (cxt == NULL) bucket[cxkey] = NULL; } } dlog("CXT in list before cleaning: %10u\n", config.llcxt); dlog("CXT in list after cleaning: %10u\n", config.curcxt);}
void end_sessions(){ connection *cxt; time_t check_time; check_time = config.tstamp.tv_sec; int ended, expired = 0; config.llcxt = 0;
int iter;
for (iter = 0; iter < BUCKET_SIZE; iter++) { cxt = bucket[iter]; while (cxt != NULL) { ended = 0; config.llcxt++; /* TCP */ if (cxt->proto == IP_PROTO_TCP) { /* FIN from both sides */ if (cxt->s_tcpFlags & TF_FIN && cxt->d_tcpFlags & TF_FIN && (check_time - cxt->last_pkt_time) > 5) ended = 1; /* RST from either side */ else if ((cxt->s_tcpFlags & TF_RST || cxt->d_tcpFlags & TF_RST) && (check_time - cxt->last_pkt_time) > 5) ended = 1; else if ((check_time - cxt->last_pkt_time) > TCP_TIMEOUT) expired = 1; } /* UDP */ else if (cxt->proto == IP_PROTO_UDP && (check_time - cxt->last_pkt_time) > UDP_TIMEOUT) expired = 1; /* ICMP */ else if (cxt->proto == IP_PROTO_ICMP || cxt->proto == IP6_PROTO_ICMP) { if ((check_time - cxt->last_pkt_time) > ICMP_TIMEOUT) expired = 1; } /* All other protocols */ else if ((check_time - cxt->last_pkt_time) > OTHER_TIMEOUT) expired = 1;
if (ended == 1 || expired == 1) { /* Remove from the hash */ if (cxt->prev) cxt->prev->next = cxt->next; if (cxt->next) cxt->next->prev = cxt->prev; connection *tmp = cxt; connection *tmp_pre = cxt->prev;
ended = expired = 0;
cxt = cxt->next;
del_connection(tmp, &bucket[iter]); if (cxt == NULL && tmp_pre == NULL) bucket[iter] = NULL; } else cxt = cxt->next; } } dlog("CXT in list before cleaning: %10u\n", config.llcxt); dlog("CXT in list after cleaning: %10u\n", config.curcxt);}
void del_connection(connection * cxt, connection ** bucket_ptr){ connection *prev = cxt->prev; /* Older connections */ connection *next = cxt->next; /* Newer connections */
if (prev == NULL) { /* Beginning of list */ *bucket_ptr = next; /* Not only entry */ if (next) next->prev = NULL; } else if (next == NULL) { /* At end of list! */ prev->next = NULL; } else { /* A node */ prev->next = next; next->prev = prev; }
/* Free and set to NULL */ free(cxt); cxt = NULL; config.curcxt--;}
const char *u_ntop_src(packetinfo *pi, char *dest){ if (pi->af == AF_INET) { if (!inet_ntop(AF_INET, &pi->ip4->ip_src, dest, INET_ADDRSTRLEN + 1)) { perror("Something died in inet_ntop"); return NULL; } } else if (pi->af == AF_INET6) { if (!inet_ntop(AF_INET6, &pi->ip6->ip_src, dest, INET6_ADDRSTRLEN + 1)) { perror("Something died in inet_ntop"); return NULL; } } return dest;}
void check_interrupt(){ dlog("[D] In interrupt. Flag: %d\n",config.intr_flag); if (ISSET_INTERRUPT_END(config)) game_over();
else if (ISSET_INTERRUPT_SESSION(config)) set_end_sessions();
else if (ISSET_INTERRUPT_DNS(config)) set_end_dns_records();
else config.intr_flag = 0;}
void sig_alarm_handler(){ time_t now_t; now_t = config.tstamp.tv_sec;
dlog("[D] Got SIG ALRM: %lu\n", now_t); /* Each time check for timed out sessions */ set_end_sessions();
/* Only check for timed-out dns records each 10 minutes */ if ((now_t - config.dnslastchk) >= 600) { set_end_dns_records(); } alarm(TIMEOUT);}
void sig_hup_handler(){ signal_reopen_log_files = 1;}
void reopen_log_files(){ if (config.output_log) { if (config.logfile_fd != NULL && config.logfile_fd != stdout) fclose(config.logfile_fd); config.logfile_fd = fopen(config.logfile, "a"); }
if (config.output_log_nxd) { if (config.logfile_all) { /* Do nothing, since both logs use the same file */ } else { if (config.logfile_nxd_fd != NULL && config.logfile_nxd_fd != stdout) fclose(config.logfile_nxd_fd); config.logfile_nxd_fd = fopen(config.logfile_nxd, "a"); } } signal_reopen_log_files = 0;}
void set_end_dns_records(){ config.intr_flag |= INTERRUPT_DNS;
if (config.inpacket == 0) { expire_dns_records(); config.dnslastchk = config.tstamp.tv_sec; config.intr_flag &= ~INTERRUPT_DNS; }}
void set_end_sessions(){ config.intr_flag |= INTERRUPT_SESSION;
if (config.inpacket == 0) { end_sessions(); config.intr_flag &= ~INTERRUPT_SESSION; }}
static int set_chroot(void){ char *absdir;
/* Change to the directory */ if (chdir(config.chroot_dir) != 0) printf("set_chroot: Can not chdir to \"%s\": %s\n", config.chroot_dir,strerror(errno));
/* Always returns an absolute pathname */ absdir = getcwd(NULL, 0);
/* Make the chroot call */ if (chroot(absdir) < 0) printf("Could not chroot to \"%s\": absolute: %s: %s\n", config.chroot_dir, absdir, strerror(errno));
if (chdir("/") < 0) printf("Could not chdir to \"/\" after chroot: %s\n", strerror(errno));
return 0;}
int drop_privs(void){ struct group *gr; struct passwd *pw; char *endptr; int i; int do_setuid = 0; int do_setgid = 0; unsigned long groupid = 0; unsigned long userid = 0;
if (config.group_name != NULL) { do_setgid = 1; if (!isdigit(config.group_name[0])) { gr = getgrnam(config.group_name); if (!gr) { if (config.chroot_dir) { elog("ERROR: you have chrooted and must set numeric group ID.\n"); exit(1); } else { elog("ERROR: couldn't get ID for group %s, group does not exist.", config.group_name); exit(1); } } groupid = gr->gr_gid; } else { groupid = strtoul(config.group_name, &endptr, 10); } }
if (config.user_name != NULL) { do_setuid = 1; do_setgid = 1; if (isdigit(config.user_name[0]) == 0) { pw = getpwnam(config.user_name); if (pw != NULL) { userid = pw->pw_uid; } else { printf("[E] User %s not found!\n", config.user_name); } } else { userid = strtoul(config.user_name, &endptr, 10); pw = getpwuid(userid); }
if (config.group_name == NULL && pw != NULL) groupid = pw->pw_gid; }
if (do_setgid) { if ((i = setgid(groupid)) < 0) printf("Unable to set group ID: %s", strerror(i)); }
endgrent(); endpwent();
if (do_setuid) { if (getuid() == 0 && initgroups(config.user_name, groupid) < 0) printf("Unable to init group names (%s/%lu)", config.user_name, groupid);
if ((i = setuid(userid)) < 0) printf("Unable to set user ID: %s\n", strerror(i)); } return 0;}
int is_valid_path(const char *path){ char dir[STDBUF]; struct stat st;
if (path == NULL) return 0;
memcpy(dir, path, strnlen(path, STDBUF)); dirname(dir);
if (stat(dir, &st) != 0) return 0;
if (!S_ISDIR(st.st_mode) || access(dir, W_OK) == -1) return 0;
return 1;}
int create_pid_file(const char *path){ char pid_buffer[12]; struct flock lock; int fd;
if (!path) path = config.pidfile;
if (!is_valid_path(path)) printf("PID path \"%s\" aint writable", path);
if ((fd = open(path, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1) return ERROR;
/* PID file locking */ lock.l_type = F_WRLCK; lock.l_start = 0; lock.l_whence = SEEK_SET; lock.l_len = 0;
if (fcntl(fd, F_SETLK, &lock) == -1) { close(fd); return ERROR; }
snprintf(pid_buffer, sizeof(pid_buffer), "%d\n", (int)getpid());
if (ftruncate(fd, 0) != 0) { close(fd); return ERROR; }
if (write(fd, pid_buffer, strlen(pid_buffer)) != 0) { close(fd); return ERROR; }
close(fd); return SUCCESS;}
int daemonize(){ pid_t pid; int fd;
pid = fork();
if (pid > 0) exit(0); /* Parent */
if (pid < 0) return ERROR;
setsid();
if ((fd = open("/dev/null", O_RDWR)) >= 0) { dup2(fd, 0); dup2(fd, 1); dup2(fd, 2); if (fd > 2) { close(fd); } }
if (config.pidfile) return create_pid_file(config.pidfile);
return SUCCESS;}
void game_over(){ if (config.inpacket == 0) { expire_all_dns_records(); print_pdns_stats();
if (config.handle != NULL) pcap_close(config.handle);
config.handle = NULL;
if (config.hostname != NULL) free(config.hostname);
#ifdef HAVE_PFRING if (config.use_pfring && config.pfhandle != NULL) { pfring_breakloop(config.pfhandle); pfring_close(config.pfhandle); }#endif /* HAVE_PFRING */
end_all_sessions();
if (config.logfile_fd != NULL && config.logfile_fd != stdout) fclose(config.logfile_fd);
if (config.logfile_nxd_fd != NULL && config.logfile_nxd_fd != stdout) fclose(config.logfile_nxd_fd);
free_config(); olog("\n[*] passivedns ended.\n"); exit(0); } config.intr_flag |= INTERRUPT_END;}
void free_config(){ if (config.cfilter.bf_insns != NULL) free(config.cfilter.bf_insns);}
void print_pdns_stats(){ FILE *handle = stdout; if (config.use_stats_file) { handle = fopen(config.statsfile, "w"); if (handle == NULL) { olog("[!] Error opening stats file %s: %s\n", config.statsfile, strerror(errno)); return; } }
flog(handle, "\n"); flog(handle, "-- Total DNS records allocated :%12u\n", config.p_s.dns_records); flog(handle, "-- Total DNS assets allocated :%12u\n", config.p_s.dns_assets); flog(handle, "-- Total DNS packets over IPv4/TCP :%12u\n", config.p_s.ip4_dns_tcp); flog(handle, "-- Total DNS packets over IPv6/TCP :%12u\n", config.p_s.ip6_dns_tcp); flog(handle, "-- Total DNS packets over TCP decoded :%12u\n", config.p_s.ip4_dec_tcp_ok + config.p_s.ip6_dec_tcp_ok); flog(handle, "-- Total DNS packets over TCP failed :%12u\n", config.p_s.ip4_dec_tcp_er + config.p_s.ip6_dec_tcp_er); flog(handle, "-- Total DNS packets over IPv4/UDP :%12u\n", config.p_s.ip4_dns_udp); flog(handle, "-- Total DNS packets over IPv6/UDP :%12u\n", config.p_s.ip6_dns_udp); flog(handle, "-- Total DNS packets over UDP decoded :%12u\n", config.p_s.ip4_dec_udp_ok + config.p_s.ip6_dec_udp_ok); flog(handle, "-- Total DNS packets over UDP failed :%12u\n", config.p_s.ip4_dec_udp_er + config.p_s.ip6_dec_udp_er); flog(handle, "-- Total packets received from libpcap :%12u\n", config.p_s.got_packets); flog(handle, "-- Total Ethernet packets received :%12u\n", config.p_s.eth_recv); flog(handle, "-- Total VLAN packets received :%12u\n", config.p_s.vlan_recv);
if (config.use_stats_file) { fclose(handle); }}
void usage(){ olog("\n"); olog("USAGE:\n"); olog(" $ passivedns [options]\n\n"); olog(" OPTIONS:\n\n"); olog(" -i <iface> Network device <iface> (default: eth0).\n"); olog(" -r <file> Read pcap <file>.\n"); olog(" -H <hostname> Choose hostname to print in record.\n");#ifdef HAVE_PFRING olog(" -n Use PF_RING.\n"); olog(" -c <cluster_id> Set PF_RING cluster_id.\n");#endif /* HAVE_PFRING */ olog(" -l <file> Logfile normal queries (default: /var/log/passivedns.log).\n"); olog(" -L <file> Logfile for SRC Error queries (default: /var/log/passivedns.log).\n"); olog(" -y Log to syslog (uses local7 syslog facility).\n"); olog(" -Y Log NXDOMAIN to syslog.\n"); olog(" -d <delimiter> Delimiter between fields in log file (default: ||).\n");#ifdef HAVE_JSON olog(" -j Use JSON as output in log file.\n"); olog(" -J Use JSON as output in NXDOMAIN log file.\n");#endif /* HAVE_JSON */ olog(" -f <fields> Choose which fields to print (default: -f SMcsCQTAtn).\n"); olog(" -s <file> Print stats on signal (SIGUSR1) to this file.\n"); olog(" -b 'BPF' Berkley Packet Filter (default: 'port 53').\n"); olog(" -p <file> Name of pid file (default: /var/run/passivedns.pid).\n"); olog(" -S <mem> Soft memory limit in MB (default: 256).\n"); olog(" -C <sec> Seconds to cache DNS objects in memory (default: %u).\n", DNSCACHETIMEOUT); olog(" -P <sec> Seconds between printing duplicate DNS info (default %u).\n", DNSPRINTTIME); olog(" -X <flags> Manually set DNS RR Types to care about (default: -X 46CDNPRS).\n"); olog(" -N Set interface to non promisc. mode.\n"); olog(" -u <uid> User ID to drop privileges to.\n"); olog(" -g <gid> Group ID to drop privileges to.\n"); olog(" -T <dir> Directory to chroot into.\n"); olog(" -q Quiet mode (no output except errors).\n"); olog(" -D Run as daemon.\n"); olog(" -V Show version and exit.\n"); olog(" -h This help message.\n\n"); olog(" FIELDS:\n"); olog("\n"); olog(" H: YMD-HMS Stamp S: Timestamp(s) M: Timestamp(ms) c: Client IP \n"); olog(" s: Server IP C: Class Q: Query T: Type \n"); olog(" A: Answer t: TTL p: Protocol n: Count \n"); olog(" h: hostname L: QueryLength l: AnswerLength w: Client MAC \n"); olog(" W: Server MAC \n"); olog("\n"); olog(" FLAGS:\n"); olog("\n"); olog(" * For Record Types:\n"); olog(" 4:A 6:AAAA C:CNAME D:DNAME N:NAPTR O:SOA L:LOC F:SPF I:HINFO\n"); olog(" P:PTR R:RP S:SRV T:TXT M:MX n:NS d:DNSEC H:SSHFP\n"); olog(" L also enables GPOS\n");#ifdef LDNS_RR_TYPE_NSEC3PARAM olog(" d enables DS, DNSKEY, NSEC, NSEC3, RRSIG\n");#else olog(" d enables DS, DNSKEY, NSEC, NSEC3, NSEC3PARAM, RRSIG\n");#endif /* LDNS_RR_TYPE_NSEC3PARAM */ olog("\n"); olog(" * For Server Return Code (SRC) Errors:\n"); olog(" f:FORMERR s:SERVFAIL x:NXDOMAIN o:NOTIMPL r:REFUSED\n"); olog(" y:YXDOMAIN e:YXRRSET t:NXRRSET a:NOTAUTH z:NOTZONE\n"); olog("\n");}
void show_version(){ olog("\n"); olog("[*] PassiveDNS %s\n", VERSION); olog("[*] By Edward Bjarte Fjellskål <edward.fjellskaal@gmail.com>\n"); olog("[*] Using %s\n", pcap_lib_version()); olog("[*] Using ldns version %s\n",ldns_version());#ifdef HAVE_PFRING /* Print PF_RING version if PF_RING is used */ if (config.use_pfring) { char pfv[50]; u_int32_t pf_version; pfring_version(config.pfhandle, &pf_version); snprintf(pfv, 50, "%d.%d.%d", (pf_version & 0xFFFF0000) >> 16, (pf_version & 0x0000FF00) >> 8, pf_version & 0x000000FF); olog("[*] Using PF_RING version %s\n", pfv); }#endif /* HAVE_PFRING */#ifdef HAVE_JSON if (config.use_json || config.use_json_nxd) { olog("[*] Using jansson version %s\n", JANSSON_VERSION); }#endif /* HAVE_JSON */}
extern int optind, opterr, optopt; // getopt()
/* magic main */int main(int argc, char *argv[]){ int ch = 0; // verbose_already = 0; int daemon = 0; memset(&config, 0, sizeof(globalconfig)); config.inpacket = config.intr_flag = 0; config.dnslastchk = 0; config.bpff = BPFF; config.logfile = "/var/log/passivedns.log"; config.logfile_nxd = "/var/log/passivedns.log"; config.statsfile = "/var/log/passivedns.stats"; config.pidfile = "/var/run/passivedns.pid"; config.promisc = 1; config.output_log = 0; config.output_log_nxd = 0; config.output_syslog = 0; config.output_syslog_nxd = 0; /* Default memory limit: 256 MB */ config.mem_limit_max = (256 * 1024 * 1024); config.dnsprinttime = DNSPRINTTIME; config.dnscachetimeout = DNSCACHETIMEOUT; config.dnsf = 0; config.log_delimiter = "||"; config.fieldsf = 0; config.fieldsf |= FIELD_TIMESTAMP_S; config.fieldsf |= FIELD_TIMESTAMP_MS; config.fieldsf |= FIELD_CLIENT; config.fieldsf |= FIELD_SERVER; config.fieldsf |= FIELD_CLASS; config.fieldsf |= FIELD_QUERY; config.fieldsf |= FIELD_TYPE; config.fieldsf |= FIELD_ANSWER; config.fieldsf |= FIELD_TTL; config.fieldsf |= FIELD_COUNT; config.dnsf |= DNS_CHK_A; config.dnsf |= DNS_CHK_AAAA; config.dnsf |= DNS_CHK_PTR; config.dnsf |= DNS_CHK_CNAME; config.dnsf |= DNS_CHK_DNAME; config.dnsf |= DNS_CHK_NAPTR; config.dnsf |= DNS_CHK_RP; config.dnsf |= DNS_CHK_SRV;#ifdef HAVE_PFRING config.cluster_id = 0; u_int32_t flags = 0;#endif /* HAVE_PFRING */ signal(SIGTERM, game_over); signal(SIGINT, game_over); signal(SIGQUIT, game_over); signal(SIGALRM, sig_alarm_handler); signal(SIGHUP, sig_hup_handler); signal(SIGUSR1, print_pdns_stats); signal(SIGUSR2, expire_all_dns_records);
#define ARGS "i:H:r:qc:nyYNjJl:s:L:d:hb:Dp:C:P:S:f:X:u:g:T:V"
while ((ch = getopt(argc, argv, ARGS)) != -1) switch (ch) { case 'i': config.dev = optarg; break; case 'H': config.hostname = strdup(optarg); break; case 'r': config.pcap_file = optarg; break; case 'q': config.cflags |= CONFIG_QUIET; break; case 'L': config.output_log_nxd = 1; config.logfile_nxd = optarg; break; case 'l': config.output_log = 1; config.logfile = optarg; break; case 'y': config.output_syslog = 1; break; case 'Y': config.output_syslog_nxd = 1; break;#ifdef HAVE_JSON case 'j': config.use_json = 1; break; case 'J': config.use_json_nxd = 1; break;#endif /* HAVE_JSON */ case 'd': config.log_delimiter = optarg; break; case 'b': config.bpff = optarg; break; case 'p': config.pidfile = optarg; break; case 'C': config.dnscachetimeout = strtol(optarg, NULL, 0); break; case 'P': config.dnsprinttime = strtol(optarg, NULL, 0); break; case 'S': config.mem_limit_max = (strtol(optarg, NULL, 0) * 1024 * 1024); break; case 's': config.use_stats_file = 1; config.statsfile = optarg; break; case 'f': parse_field_flags(optarg); break; case 'X': parse_dns_flags(optarg); break; case 'D': daemon = 1; break; case 'T': config.chroot_dir = optarg; config.chroot_flag = 1; break; case 'u': config.user_name = optarg; config.drop_privs_flag = 1; break; case 'g': config.group_name = optarg; config.drop_privs_flag = 1; break; case 'N': config.promisc = 0; break;#ifdef HAVE_PFRING case 'n': config.use_pfring = 1; break; case 'c': config.cluster_id = strtol(optarg, NULL, 0); break;#endif /* HAVE_PFRING */ case 'h': usage(); exit(0); break; case 'V': show_version(); olog("\n"); exit(0); break; case '?': elog("unrecognized argument: '%c'\n", optopt); break; default: elog("Did not recognize argument '%c'\n", ch); }
/* Get hostname if not specified by commandline */ if (config.fieldsf & FIELD_HOSTNAME) { if (config.hostname == NULL) { config.hostname = malloc(HOST_NAME_MAX + 1); gethostname(config.hostname, HOST_NAME_MAX); } }
/* Fall back to log file if syslog is not used */ if (config.output_syslog == 0) config.output_log = 1;
if (config.output_syslog_nxd == 0) config.output_log_nxd = 1;
/* Open log file */ if (config.output_log) { if (config.logfile[0] == '-' && config.logfile[1] == '\0') { config.logfile_fd = stdout; } else { config.logfile_fd = fopen(config.logfile, "a"); if (config.logfile_fd == NULL) { elog("[!] Error opening log file %s\n", config.logfile); exit(1); } } }
/* Open NXDOMAIN log file */ if (config.output_log_nxd) { if (config.output_log && strcmp(config.logfile, config.logfile_nxd) == 0) { config.logfile_all = 1; } else if (config.logfile_nxd[0] == '-' && config.logfile_nxd[1] == '\0') { config.logfile_nxd_fd = stdout; } else { config.logfile_nxd_fd = fopen(config.logfile_nxd, "a"); if (config.logfile_nxd_fd == NULL) { elog("[!] Error opening NXDOMAIN log file %s\n", config.logfile_nxd); exit(1); } } }
show_version();
#ifdef HAVE_PFRING if (config.use_pfring) { /* PF_RING does not have an option to read PCAP files */ if (config.pcap_file) { elog("[!] Reading PCAP files are not supported when using PF_RING\n"); exit(1); }
if (config.dev == NULL) { elog("[!] Must specify capture NIC\n"); exit(1); }
flags |= PF_RING_PROMISC; config.pfhandle = pfring_open(config.dev, SNAPLENGTH, flags);
if (config.pfhandle == NULL) { elog("[!] Could not start PF_RING capture\n"); exit(1); }
config.linktype = DLT_EN10MB; pfring_set_application_name(config.pfhandle, "passivedns");
if (config.cluster_id == 0) config.cluster_id = 99; /* Default cluster_id */
/* Don't add ring to cluster when using ZC or DNA */ if ((strncmp(config.dev, "zc", 2) != 0) && (strncmp(config.dev, "dna", 3)) != 0) { if ((pfring_set_cluster(config.pfhandle, config.cluster_id, cluster_per_flow)) != 0) { elog("[!] Could not set PF_RING cluster_id\n"); } }
#ifdef HAVE_PFRING_BPF if (*config.bpff != '\0') { if ((pfring_set_bpf_filter(config.pfhandle, config.bpff)) != 0) { elog("[!] Unable to set bpf filter\n"); } }#endif /* HAVE_PFRING_BPF */
if ((pfring_enable_ring(config.pfhandle)) != 0) { elog("[!] Could not enable ring\n"); exit(1); }
if (config.chroot_dir) { olog("[*] Chrooting to dir '%s'..\n", config.chroot_dir); if (set_chroot()) { elog("[!] failed to chroot\n"); exit(1); } }
if (config.drop_privs_flag) { olog("[*] Dropping privs...\n"); drop_privs(); }
if (daemon) { if (!is_valid_path(config.pidfile)) elog("[*] Unable to create pidfile '%s'\n", config.pidfile); openlog("passivedns", LOG_PID | LOG_CONS, LOG_DAEMON); olog("[*] Daemonizing...\n\n"); daemonize(); }
alarm(TIMEOUT); olog("[*] Device: %s\n", config.dev); olog("[*] Sniffing...\n\n");
pfring_loop(config.pfhandle, pfring_got_packet, (u_char*)NULL, 1);
game_over(); return 0; }#endif /* HAVE_PFRING */
if (config.pcap_file) { /* Read from PCAP file specified by '-r' switch. */ olog("[*] Reading from file %s\n\n", config.pcap_file); if (!(config.handle = pcap_open_offline(config.pcap_file, config.errbuf))) { elog("[*] Unable to open %s. (%s)", config.pcap_file, config.errbuf); }
} else { /* Look up an available device if non specified */ if (config.dev == 0x0) { pcap_if_t *alldevs; if (0 != pcap_findalldevs(&alldevs, config.errbuf)) { elog("[*] Error pcap_findalldevs: %s \n", config.errbuf); exit(1); } config.dev = strdup(alldevs[0].name); pcap_freealldevs(alldevs); } olog("[*] Device: %s\n", config.dev);
if ((config.handle = pcap_open_live(config.dev, SNAPLENGTH, config.promisc, 500, config.errbuf)) == NULL) { elog("[*] Error pcap_open_live: %s \n", config.errbuf); exit(1); }
if (strlen(config.errbuf) > 0) { /* Fix to enable passivedns to run in an OpenVZ container */ if (strcmp(config.errbuf, "arptype 65535 not supported by libpcap - falling back to cooked socket") == 0) { olog("[*] %s \n", config.errbuf); } else { elog("[*] Error errbuf: %s \n", config.errbuf); exit(1); } }
if (config.chroot_dir) { olog("[*] Chrooting to dir '%s'..\n", config.chroot_dir); if(set_chroot()){ elog("[!] failed to chroot\n"); exit(1); } }
if (config.drop_privs_flag) { olog("[*] Dropping privs...\n"); drop_privs(); }
if (daemon) { if (!is_valid_path(config.pidfile)) elog("[*] Unable to create pidfile '%s'\n", config.pidfile); openlog("passivedns", LOG_PID | LOG_CONS, LOG_DAEMON); olog("[*] Daemonizing...\n\n"); daemonize(); }
}
if (config.handle == NULL) { game_over(); return 1; }
config.linktype = pcap_datalink(config.handle);
/* Segfaults on empty pcap! */ if ((pcap_compile(config.handle, &config.cfilter, config.bpff, 1, config.net_mask)) == -1) { elog("[*] Error pcap_compile user_filter: %s\n", pcap_geterr(config.handle)); exit(1); }
if (pcap_setfilter(config.handle, &config.cfilter)) { olog("[*] Unable to set pcap filter! %s", pcap_geterr(config.handle)); }
alarm(TIMEOUT);
if (!config.pcap_file) olog("[*] Sniffing...\n\n");
pcap_loop(config.handle, -1, got_packet, NULL);
game_over(); return 0;}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580/*** This file is a part of PassiveDNS.**** Copyright (C) 2010-2013, Edward Fjellskål <edwardfjellskaal@gmail.com>**** This program is free software; you can redistribute it and/or modify** it under the terms of the GNU General Public License as published by** the Free Software Foundation; either version 2 of the License, or** (at your option) any later version.**** This program is distributed in the hope that it will be useful,** but WITHOUT ANY WARRANTY; without even the implied warranty of** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the** GNU General Public License for more details.**** You should have received a copy of the GNU General Public License** along with this program; if not, write to the Free Software** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.***/
/* I N C L U D E S **********************************************************/#include "config.h"
#ifdef HAVE_PFRING#include <pfring.h>#endif /* HAVE_PFRING */
/* D E F I N E S ************************************************************/#define TIMEOUT 60#define BUCKET_SIZE 65537#define SNAPLENGTH 1600#define PKT_MAXPAY 255#define MAX_BYTE_CHECK 500000#define MAX_PKT_CHECK 10#define TCP_TIMEOUT 300 /* When idle IP connections should be timed out */#define UDP_TIMEOUT 60#define ICMP_TIMEOUT 60#define OTHER_TIMEOUT 300
#define ETHERNET_TYPE_IP 0x0800#define ETHERNET_TYPE_IPV6 0x86dd
#define ETHERNET_TYPE_8021Q 0x8100#define ETHERNET_TYPE_802Q1MT 0x9100#define ETHERNET_TYPE_802Q1MT2 0x9200#define ETHERNET_TYPE_802Q1MT3 0x9300#define ETHERNET_TYPE_8021AD 0x88a8
#define IP_PROTO_ICMP 1#define IP_PROTO_TCP 6#define IP_PROTO_UDP 17#define IP_PROTO_IP6 41#define IP6_PROTO_ICMP 58
#define SLL_HDR_LEN 16#define LOOPBACK_HDR_LEN 4#define IP4_HEADER_LEN 20#define IP6_HEADER_LEN 40#define TCP_HEADER_LEN 20#define UDP_HEADER_LEN 8#define MAC_ADDR_LEN 6#define ETHERNET_HEADER_LEN 14#define ETHERNET_8021Q_HEADER_LEN 18#define ETHERNET_802Q1MT_HEADER_LEN 22
#define IP_PROTO_TCP 6#define IP_PROTO_UDP 17#define IP_PROTO_IP6 41#define IP_PROTO_IP4 94
#define TF_FIN 0x01#define TF_SYN 0x02#define TF_RST 0x04#define TF_PUSH 0x08#define TF_ACK 0x10#define TF_URG 0x20#define TF_ECE 0x40#define TF_CWR 0x80
#define SUCCESS 0#define ERROR 1#define STDBUF 1024
#define BPFF "port 53" /* Default BPF filter */
#if defined(__FreeBSD__) || defined(__APPLE__)#define s6_addr32 __u6_addr.__u6_addr32#endif /* __FreeBSD__ or __APPLE__ */
#ifndef HOST_NAME_MAX#if defined(__APPLE__)#define HOST_NAME_MAX 255#else#define HOST_NAME_MAX 64#endif /* __APPLE__ */#endif /* HOST_NAME_MAX */
/* D A T A S T R U C T U R E S *********************************************/
/* * Ethernet header */
typedef struct _ether_header { u_char ether_dst[6]; /* Destination MAC */ u_char ether_src[6]; /* Source MAC */
union { struct etht { u_short ether_type; /* Ethernet type (normal) */ } etht;
struct qt { u_short eth_t_8021; /* Ethernet type/802.1Q tag */ u_short eth_t_8_vid; u_short eth_t_8_type; } qt;
struct qot { u_short eth_t_80212; /* Ethernet type/802.1QinQ */ u_short eth_t_82_mvid; u_short eth_t_82_8021; u_short eth_t_82_vid; u_short eth_t_82_type; } qot; } vlantag;
#define eth_ip_type vlantag.etht.ether_type
#define eth_8_type vlantag.qt.eth_t_8021 #define eth_8_vid vlantag.qt.eth_t_8_vid #define eth_8_ip_type vlantag.qt.eth_t_8_type
#define eth_82_type vlantag.qot.eth_t_80212 #define eth_82_mvid vlantag.qot.eth_t_82_mvid #define eth_82_8021 vlantag.qot.eth_t_82_8021 #define eth_82_vid vlantag.qot.eth_t_82_vid #define eth_82_ip_type vlantag.qot.eth_t_82_type
} ether_header;
typedef struct _arphdr { uint16_t ar_hrd; /* Format of hardware address */ uint16_t ar_pro; /* Format of protocol address */ uint8_t ar_hln; /* Length of hardware address */ uint8_t ar_pln; /* Length of protocol address */ uint16_t ar_op; /* ARP opcode (command) */} arphdr;
typedef struct _ether_arp { arphdr ea_hdr; /* Fixed-size header */ uint8_t arp_sha[MAC_ADDR_LEN]; /* Sender hardware address */ uint8_t arp_spa[4]; /* Sender protocol address */ uint8_t arp_tha[MAC_ADDR_LEN]; /* Target hardware address */ uint8_t arp_tpa[4]; /* Target protocol address */} ether_arp;
/* * IPv4 header */
typedef struct _ip4_header { uint8_t ip_vhl; /* Version << 4 | header length >> 2 */ uint8_t ip_tos; /* Type of service */ uint16_t ip_len; /* Total length */ uint16_t ip_id; /* Identification */ uint16_t ip_off; /* Fragment offset field */ uint8_t ip_ttl; /* Time to live */ uint8_t ip_p; /* Protocol */ uint16_t ip_csum; /* Checksum */ uint32_t ip_src; /* Source address */ uint32_t ip_dst; /* Destination address */} ip4_header;
#define IP_RF 0x8000 /* Reserved fragment flag */#define IP_DF 0x4000 /* Don't fragment flag */#define IP_MF 0x2000 /* More fragments flag */#define IP_OFFMASK 0x1fff /* Mask for fragmenting bits */#define IP_HL(ip4_header) (((ip4_header)->ip_vhl) & 0x0f)#define IP_V(ip4_header) (((ip4_header)->ip_vhl) >> 4)
/* * IPv6 header */
typedef struct _ip6_header { uint32_t vcl; /* Version, class, and label */ uint16_t len; /* Length of the payload */ uint8_t next; /* Next header * Uses the same flags as * the IPv4 protocol field */ uint8_t hop_lmt; /* Hop limit */ struct in6_addr ip_src; /* Source address */ struct in6_addr ip_dst; /* Destination address */} ip6_header;
/* * TCP header */
typedef struct _tcp_header { uint16_t src_port; /* Source port */ uint16_t dst_port; /* Destination port */ uint32_t t_seq; /* Sequence number */ uint32_t t_ack; /* Acknowledgement number */ uint8_t t_offx2; /* Data offset, rsvd */ uint8_t t_flags; /* TCP flags */ uint16_t t_win; /* Window */ uint16_t t_csum; /* Checksum */ uint16_t t_urgp; /* Urgent pointer */} tcp_header;
#define TCP_OFFSET(tcp_header) (((tcp_header)->t_offx2 & 0xf0) >> 4)#define TCP_X2(tcp_header) ((tcp_header)->t_offx2 & 0x0f)#define TCP_ISFLAGSET(tcp_header, flags) (((tcp_header)->t_flags & (flags)) == (flags))
/* * UDP header */
typedef struct _udp_header { uint16_t src_port; /* Source port */ uint16_t dst_port; /* Destination port */ uint16_t len; /* Length of the payload */ uint16_t csum; /* Checksum */} udp_header;
/* * Structure for connections */
typedef struct _connection { struct _connection *prev; struct _connection *next; time_t start_time; /* Connection start time */ time_t last_pkt_time; /* Last seen packet time */ uint64_t cxid; /* Connection ID */ uint8_t reversed; /* 1 if the connection is reversed */ uint32_t af; /* IP version (4/6) AF_INET */ uint8_t proto; /* IP protocol type */ struct in6_addr s_ip; /* Source address */ struct in6_addr d_ip; /* Destination address */ uint16_t s_port; /* Source port */ uint16_t d_port; /* Destination port */ uint64_t s_total_pkts; /* Total source packets */ uint64_t s_total_bytes; /* Total source bytes */ uint64_t d_total_pkts; /* Total destination packets */ uint64_t d_total_bytes; /* Total destination bytes */ uint8_t s_tcpFlags; /* TCP flags sent by source */ uint8_t d_tcpFlags; /* TCP flags sent by destination */ uint8_t check; /* Flags specifying checking */ uint16_t plid; /* Protocol layer ID (DNS TID) */} connection;#define CXT_DONT_CHECK_SERVER 0x01 /* Don't check server packets */#define CXT_DONT_CHECK_CLIENT 0x02 /* Don't check client packets */#define CXT_SERVICE_DONT_CHECK 0x04 /* Don't check payload from server */#define CXT_CLIENT_DONT_CHECK 0x08 /* Don't check payload from client */#define CXT_SERVICE_UNKNOWN_SET 0x10 /* If service is set as unknown */#define CXT_CLIENT_UNKNOWN_SET 0x20 /* If client is set as unknown */
#define ISSET_CXT_DONT_CHECK_CLIENT(pi) (pi->cxt->check & CXT_DONT_CHECK_CLIENT)#define ISSET_CXT_DONT_CHECK_SERVER(pi) (pi->cxt->check & CXT_DONT_CHECK_SERVER)#define ISSET_DONT_CHECK_SERVICE(pi) (pi->cxt->check & CXT_SERVICE_DONT_CHECK)#define ISSET_DONT_CHECK_CLIENT(pi) (pi->cxt->check & CXT_CLIENT_DONT_CHECK)#define ISSET_SERVICE_UNKNOWN(pi) (pi->cxt->check & CXT_SERVICE_UNKNOWN_SET)#define ISSET_CLIENT_UNKNOWN(pi) (pi->cxt->check & CXT_CLIENT_UNKNOWN_SET)
#ifdef BSD_DERIVED// sidds darwin ports#define IP4ADDR(ip) (ip)->__u6_addr.__u6_addr32[0]
#define CMP_ADDR6(a1,a2) \ (((a1)->__u6_addr.__u6_addr32[3] == (a2)->__u6_addr.__u6_addr32[3] && \ (a1)->__u6_addr.__u6_addr32[2] == (a2)->__u6_addr.__u6_addr32[2] && \ (a1)->__u6_addr.__u6_addr32[1] == (a2)->__u6_addr.__u6_addr32[1] && \ (a1)->__u6_addr.__u6_addr32[0] == (a2)->__u6_addr.__u6_addr32[0]))
// The reason why we can't get rid of pi->s6_addr32#define CMP_ADDR4(a1,a2) \ (((a1)->__u6_addr.__u6_addr32[0] == (a2)))#define CMP_ADDRA(a1,a2) \ (((a1)->__u6_addr.__u6_addr32[0] == (a2)->__u6_addr.__u6_addr32[0]))
#define CMP_PORT(p1,p2) \ ((p1 == p2))#else#define IP6ADDR0(ip) ((ip)->s6_addr32[0])#define IP6ADDR1(ip) ((ip)->s6_addr32[1])#define IP6ADDR2(ip) ((ip)->s6_addr32[2])#define IP6ADDR3(ip) ((ip)->s6_addr32[3])#define IP6ADDR(ip) \ IP6ADDR0(ip), IP6ADDR1(ip), IP6ADDR2(ip), IP6ADDR3(ip)
#define IP4ADDR(ip) ((ip)->s6_addr32[0])
#define CMP_ADDR6(a1,a2) \ (((a1)->s6_addr32[3] == (a2)->s6_addr32[3] && \ (a1)->s6_addr32[2] == (a2)->s6_addr32[2] && \ (a1)->s6_addr32[1] == (a2)->s6_addr32[1] && \ (a1)->s6_addr32[0] == (a2)->s6_addr32[0]))
// The reason why we can't get rid of pi->s6_addr32// apples and apples#define CMP_ADDR4A(a1,a2) \ ((a1)->s6_addr32[0] == (a2)->s6_addr32[0])// apples and oranges#define CMP_ADDR4(apple,orange) \ (((apple)->s6_addr32[0] == (orange)))#define CMP_PORT(p1,p2) \ ((p1 == p2))#endif /* OSX */
/* Since two or more connections can have the same hash key, we need to * compare the connections with the current hash key. */#define CMP_CXT4(cxt1, src, sp, dst, dp) \ (( \ CMP_PORT((cxt1)->s_port, (sp)) && \ CMP_PORT((cxt1)->d_port, (dp)) && \ CMP_ADDR4(&((cxt1)->s_ip), (src)) && \ CMP_ADDR4(&((cxt1)->d_ip), (dst)) \ ))
#define CMP_CXT6(cxt1, src, sp, dst, dp) \ ((CMP_ADDR6(&(cxt1)->s_ip, (src)) && \ CMP_ADDR6(&(cxt1)->d_ip, (dst)) && \ CMP_PORT((cxt1)->s_port, (sp)) && CMP_PORT((cxt1)->d_port, (dp))))
/* clear the address structure by setting all fields to 0 */#ifdef BSD_DERIVED#define CLEAR_ADDR(a) { \ (a)->__u6_addr.__u6_addr32[0] = 0; \ (a)->__u6_addr.__u6_addr32[1] = 0; \ (a)->__u6_addr.__u6_addr32[2] = 0; \ (a)->__u6_addr.__u6_addr32[3] = 0; \}#else#define CLEAR_ADDR(a) { \ (a)->s6_addr32[0] = 0; \ (a)->s6_addr32[1] = 0; \ (a)->s6_addr32[2] = 0; \ (a)->s6_addr32[3] = 0; \}#endif
#define CXT_HASH4(src,dst,sp,dp,pr) \ ((src + dst + sp + dp + pr) % BUCKET_SIZE)
#ifndef BSD_DERIVED#define CXT_HASH6(src,dst,sp,dp,pr) \ (( \ (src)->s6_addr32[0] + (src)->s6_addr32[1] + \ (src)->s6_addr32[2] + (src)->s6_addr32[3] + \ (dst)->s6_addr32[0] + (dst)->s6_addr32[1] + \ (dst)->s6_addr32[2] + (dst)->s6_addr32[3] + \ sp + dp + pr ) % BUCKET_SIZE)#else#define CXT_HASH6(src,dst,sp,dp,pr) \ (( \ (src)->__u6_addr.__u6_addr32[0] + (src)->__u6_addr.__u6_addr32[1] + \ (src)->__u6_addr.__u6_addr32[2] + (src)->__u6_addr.__u6_addr32[3] + \ (dst)->__u6_addr.__u6_addr32[0] + (dst)->__u6_addr.__u6_addr32[1] + \ (dst)->__u6_addr.__u6_addr32[2] + (dst)->__u6_addr.__u6_addr32[3] + \ sp + dp + pr ) % BUCKET_SIZE)#endif
typedef struct _packetinfo { /* Macro out the need for some of these * eth_type(pi) is same as pi->eth_type, no? * marked candidates for deletion */ const struct pcap_pkthdr *pheader; /* Libpcap packet header struct pointer */ const uint8_t *packet; /* Unsigned char pointer to raw packet */ /* Compute (all) these from packet */ uint32_t eth_hlen; /* Ethernet header length */ uint16_t mvlan; /* Metro vlan tag */ uint16_t vlan; /* VLAN tag */ uint16_t eth_type; /* Ethernet type (IPv4/IPv6/etc) */ uint32_t af; /* IP version (4/6) AF_INET */ ether_header *eth_hdr; /* Ethernet header struct pointer */ ether_arp *arph; /* ARP header struct pointer */ ip4_header *ip4; /* IPv4 header struct pointer */ ip6_header *ip6; /* IPv6 header struct pointer */ uint16_t packet_bytes; /* Length of IP payload in packet */ uint16_t s_port; /* Source port */ uint16_t d_port; /* Destination port */ uint8_t proto; /* IP protocol type */ uint8_t sc; /* SC_SERVER, SC_CLIENT or SC_UNKNOWN */ tcp_header *tcph; /* TCP header struct pointer */ udp_header *udph; /* UDP header struct pointer */ uint16_t gre_hlen; /* Length of dynamic GRE header length */ const uint8_t *end_ptr; /* Paranoid end pointer of packet */ const uint8_t *payload; /* Char pointer to transport payload */ uint32_t plen; /* Transport payload length */ uint32_t our; /* Is the asset in our defined network */ uint8_t up; /* Set if the asset has been updated */ connection *cxt; /* Pointer to the cxt for this packet */} packetinfo;
/* * Packetinfo accessor macros */
#define PI_TOS(pi) ( (pi)->ip4->ip_tos )#define PI_ECN(pi) ( (pi)->tcph->t_flags & (TF_ECE|TF_CWR) )
#define PI_IP4(pi) ((pi)->ip4)#define PI_IP4SRC(pi) ( PI_IP4(pi)->ip_src )#define PI_IP4DST(pi) ( PI_IP4(pi)->ip_dst )
#define PI_IP6(pi) ((pi)->ip6)#define PI_IP6SRC(pi) (PI_IP6(pi)->ip_src)#define PI_IP6DST(pi) (PI_IP6(pi)->ip_dst)
#define PI_TCP_SP(pi) ( ntohs((pi)->tcph->src_port))#define PI_TCP_DP(pi) ( ntohs((pi)->tcph->dst_port))
#define SC_CLIENT 0x01 /* Pi for this session is client */#define SC_SERVER 0x02 /* Pi for this session is server */#define SC_UNKNOWN 0x03 /* Pi for this session is not yet known */
typedef struct _pdns_stat { uint32_t got_packets; /* Number of packets received by program */ uint32_t eth_recv; /* Number of Ethernet packets received */ uint32_t arp_recv; /* Number of ARP packets received */ uint32_t otherl_recv; /* Number of other Link layer packets received */ uint32_t vlan_recv; /* Number of VLAN packets received */ uint32_t ip4_recv; /* Number of IPv4 packets received */ uint32_t ip6_recv; /* Number of IPv6 packets received */
uint32_t ip4_dns_udp; /* Number of IPv4 packets received */ uint32_t ip4_dec_udp_ok; /* Number of IPv4 packets received */ uint32_t ip4_dec_udp_er; /* Number of IPv4 packets received */ uint32_t ip4_dns_tcp; /* Number of IPv4 packets received */ uint32_t ip4_dec_tcp_ok; /* Number of IPv4 packets received */ uint32_t ip4_dec_tcp_er; /* Number of IPv4 packets received */ uint32_t ip4_recv_tcp; /* Number of IPv4 packets received */
uint32_t ip6_dns_udp; /* Number of IPv4 packets received */ uint32_t ip6_dec_udp_ok; /* Number of IPv4 packets received */ uint32_t ip6_dec_udp_er; /* Number of IPv4 packets received */ uint32_t ip6_dns_tcp; /* Number of IPv4 packets received */ uint32_t ip6_dec_tcp_ok; /* Number of IPv4 packets received */ uint32_t ip6_dec_tcp_er; /* Number of IPv4 packets received */ uint32_t ip6_recv_tcp; /* Number of IPv4 packets received */
uint32_t ip4ip_recv; /* Number of IP4/6 packets in IPv4 packets */ uint32_t ip6ip_recv; /* Number of IP4/6 packets in IPv6 packets */ uint32_t gre_recv; /* Number of GRE packets received */ uint32_t tcp_recv; /* Number of TCP packets received */ uint32_t udp_recv; /* Number of UDP packets received */ uint32_t icmp_recv; /* Number of ICMP packets received */ uint32_t othert_recv; /* Number of other transport layer packets received */ uint32_t dns_records; /* Total number of DNS records detected */ uint32_t dns_assets; /* Total number of DNS assets detected */ uint32_t tcp_os_assets; /* Total number of TCP os assets detected */ uint32_t udp_os_assets; /* Total number of UDP os assets detected */ uint32_t icmp_os_assets; /* Total number of ICMP os assets detected */ uint32_t dhcp_os_assets; /* Total number of DHCP os assets detected */ uint32_t tcp_services; /* Total number of TCP services detected */ uint32_t tcp_clients; /* Total number of TCP clients detected */ uint32_t udp_services; /* Total number of UDP services detected */ uint32_t udp_clients; /* Total number of TCP clients detected */} pdns_stat;
#define CONFIG_VERBOSE 0x01#define CONFIG_UPDATES 0x02#define CONFIG_SYSLOG 0x04#define CONFIG_QUIET 0x08#define CONFIG_CONNECT 0x10#define CONFIG_CXWRITE 0x20
#define INTERRUPT_END 0x01#define INTERRUPT_SESSION 0x02#define INTERRUPT_DNS 0x04
typedef struct _globalconfig { pcap_t *handle; /* Pointer to libpcap handle */#ifdef HAVE_PFRING pfring *pfhandle; /* Pointer to libpfring handle */ uint8_t use_pfring; /* Use PF_RING or not */ u_int cluster_id; /* PF_RING cluster ID */#endif /* HAVE_PFRING */ struct pcap_stat ps; /* Libpcap stats */ int linktype; /* Libpcap linktype */ pdns_stat p_s; /* PDNS stats */ struct bpf_program cfilter; bpf_u_int32 net_mask; uint8_t intr_flag; uint8_t inpacket;
time_t dnslastchk; /* Timestamp for last DNS cache expiration check */ struct timeval tstamp; /* Current timestamp from packet-header */ uint8_t cflags; /* Config flags */ uint8_t verbose; /* Verbose or not */ uint8_t print_updates; /* Prints updates */ uint8_t output_log; /* Log to log file */ uint8_t output_log_nxd; /* Log NXDOMAIN to log file */ uint8_t output_syslog; /* Log to syslog */ uint8_t output_syslog_nxd; /* Log NXDOMAIN to syslog */#ifdef HAVE_JSON uint8_t use_json; /* Use JSON as output in log */ uint8_t use_json_nxd; /* Use JSON as output in NXDOMAIN log */#endif /* HAVE_JSON */ uint8_t use_stats_file; /* Print stats on signal to file */ char *statsfile; /* File to print stats to */ uint8_t setfilter; uint8_t promisc; /* set interface promisc mode */ uint8_t drop_privs_flag; /* Flag marking to drop privs */ uint8_t chroot_flag; /* Flag for going chroot */ uint8_t daemon_flag; /* Flag for going daemon */ uint8_t logfile_all; /* Log everything in the same log file */ uint32_t fieldsf; /* flags for fields to print */ uint64_t dnsf; /* Flags for DNS RR Type checks to do */ uint32_t dnsfe; /* Flags for DNS Server Error Types to check */ uint32_t payload; /* Dump how much of the payload ? */ uint32_t curcxt; uint32_t llcxt; uint64_t mem_limit_max; /* Try soft limit memory use */ uint64_t mem_limit_size; /* Current memory size */ uint32_t dns_records; /* Total number of DNS records in memory */ uint32_t dns_assets; /* Total number of DNS assets in memory */ uint64_t cxtrackerid; /* cxtracker ID counter */ char errbuf[PCAP_ERRBUF_SIZE]; char *hostname; char *bpff; char *user_filter; char *net_ip_string; char *log_delimiter; /* Delimiter between fields in log */ char *logfile; /* Filename of /var/log/passivedns.log */ char *logfile_nxd; /* Filename for NXDOMAIN logging /var/log/passivedns-nxd.log */ char *pcap_file; /* Filename to PCAP too read */ FILE *logfile_fd; /* File descriptor for log file */ FILE *logfile_nxd_fd; /* File descriptor for NXDOMAIN log file */ char *dev; /* Device name to use for sniffing */ char *dpath; /* ... ??? seriously ???... */ char *chroot_dir; /* Directory to chroot to */ char *group_name; /* Group to drop privileges too */ char *user_name; /* User to drop privileges too */ char *pidfile; /* Pidfile */ char *configpath; /* Path to config directory */ uint32_t dnsprinttime; /* Minimum time between printing duplicate DNS info */ uint32_t dnscachetimeout; /* Time before a DNS record/asset times out if not updated */} globalconfig;
#define ISSET_CONFIG_VERBOSE(config) ((config).cflags & CONFIG_VERBOSE)#define ISSET_CONFIG_UPDATES(config) ((config).cflags & CONFIG_UPDATES)#define ISSET_CONFIG_SYSLOG(config) ((config).cflags & CONFIG_SYSLOG)#define ISSET_CONFIG_QUIET(config) ((config).cflags & CONFIG_QUIET)
#define ISSET_INTERRUPT_END(config) ((config).intr_flag & INTERRUPT_END)#define ISSET_INTERRUPT_SESSION(config) ((config).intr_flag & INTERRUPT_SESSION)#define ISSET_INTERRUPT_DNS(config) ((config).intr_flag & INTERRUPT_DNS)
#define plog(fmt, ...) do{ fprintf(stdout, (fmt), ##__VA_ARGS__); }while(0)#define flog(h, fmt, ...) \ do{ \ if (!(h == stdout && ISSET_CONFIG_QUIET(config))) \ fprintf(h, fmt, ##__VA_ARGS__); \ } \ while(0)#define olog(fmt, ...) do{ if(!(ISSET_CONFIG_QUIET(config))) fprintf(stdout, (fmt), ##__VA_ARGS__); }while(0)//#define DEBUG 1#ifdef DEBUG#define dlog(fmt, ...) do { fprintf(stderr, ("[%s:%d(%s)] " fmt), __FILE__, __LINE__, __PRETTY_FUNCTION__, ##__VA_ARGS__);} while(0)#define vlog(v, fmt, ...) do{ if(DEBUG == v) fprintf(stderr, ("[%s:%d(%s)] " fmt), __FILE__, __LINE__, __PRETTY_FUNCTION__, ##__VA_ARGS__); }while(0)#define elog(fmt, ...) fprintf(stderr, ("[%s:%d(%s)] " fmt), __FILE__, __LINE__, __PRETTY_FUNCTION__, ##__VA_ARGS__);#else#define elog(fmt, ...) fprintf(stderr, (fmt), ##__VA_ARGS__);#define dlog(fmt, ...) do { ; } while(0)#define vlog(fmt, ...) do { ; } while(0)#endif
int cxt_update_client(connection *cxt, packetinfo *pi);int cxt_update_unknown(connection *cxt, packetinfo *pi);int cxt_update_server(connection *cxt, packetinfo *pi);
12345678910111213141516171819202122232425262728293031323334353637# PassiveDNS (https://github.com/gamelinux/passivedns)# Example file for skiplist, whitelist and blacklist to be read from pdns2db.pl # Lines starting with # are not processed.
# Example 1: STATIC DOMAINS/IPs# work with: --skiplist, --whitelist or --blacklist# One domain on each line. The match has to be exact.www.google.comwww.facebook.comwww.twitter.com8.8.8.88.8.4.4current.cvd.clamav.net
# Example 2: PCRE formated DOMAINS/IPs# work with: --skiplist-pcre, --whitelist-pcre or --blacklist-pcre# One domain on each line.\.google\.com$\.facebook\.com$\.twitter\.com$antivirus\.3322\.org$# blacklist type of services\.mailserveren\.com$\.sorbs\.net$\.spamcop\.net$\.list\.dnswl\.org$\.(zen|sbl|dbl)\.spamhaus\.org$\.bb\.barracudacentral\.org$\.mailspike\.net$\.score\.senderscore\.com$\.bondedsender\.org$\.surbl\.org$\.uribl\.com$\.habeas\.com$\.support-intelligence\.net$\.in-addr\.arpa$123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531#!/usr/bin/perl
# ----------------------------------------------------------------------# PassiveDNS to DB# Copyright (C) 2011-2012, Edward Fjellskål <edwardfjellskaal@gmail.com>## This program is free software; you can redistribute it and/or modify# it under the terms of the GNU General Public License as published by# the Free Software Foundation; either version 2 of the License, or# (at your option) any later version.## This program is distributed in the hope that it will be useful,# but WITHOUT ANY WARRANTY; without even the implied warranty of# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the# GNU General Public License for more details.## You should have received a copy of the GNU General Public License# along with this program; if not, write to the Free Software# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.# ----------------------------------------------------------------------
use strict;use warnings;use POSIX qw(setsid strftime);use DateTime;use Getopt::Long qw/:config auto_version auto_help/;use DBI;
#use Data::Dumper;
=head1 NAME
pdns2db.pl - Load passive DNS data from passivedns into a DB
=head1 VERSION
0.3
=head1 SYNOPSIS
$ pdns2db.pl [options]
OPTIONS:
--file <file> : set the file to monitor for passivedns entries (/var/log/passivedns.log) --batch : process a file and exit when done --skiplist <file> : file with a list of domains to skip DB insertion --onlylist <file> : file with a list of domains to only insert into DB --whitelist <file> : file with a list of domains to not check for in blacklist --blacklist <file> : file with a list of domains to alert on --skiplist-pcre <file> : file with regexp list of domains to skip DB insertion --onlylist-pcre <file> : file with regexp list of domains to only insert into DB --whitelist-pcre <file>: file with regexp list of domains to not check for in blacklist --blacklist-pcre <file>: file with regexp list of domains to alert on --alertlog <file> : file to log alerts to (/var/log/passivedns-alert.log) --nodb : dont talk to the DB at all --daemon : enables daemon mode --verbose : enables some verboseness --debug <int> : enable debug messages (default: 0 (disabled)) --help : this help message --version : show pdns2db.pl version
=cut
our $VERSION = 0.3;our $DEBUG = 0;our $VERBOSE = 0;our $DAEMON = 0;our $TIMEOUT = 1;my $PDNSFILE = q(/var/log/passivedns.log);my $LOGFILE = q(/var/log/passivedns-run.log);my $ALERTLOG = q(/var/log/passivedns-alert.log);my $PIDFILE = q(/var/run/pdns2db.pid);our $DB_NAME = "pdns";our $DB_HOST = "127.0.0.1";our $DB_PORT = "3306";our $DB_USERNAME = "pdns";our $DB_PASSWORD = "pdns";our $DBI = "DBI:mysql:$DB_NAME:$DB_HOST:$DB_PORT";our $TABLE_NAME = "pdns";our $AUTOCOMMIT = 0;our $BATCH = 0;our $dbh;our $NODB = 0;my $DOMAIN_BLACKLIST_FILE = undef;my $DOMAIN_BLACKLIST_FILE_PCRE = undef;my $DOMAIN_WHITELIST_FILE = undef;my $DOMAIN_WHITELIST_FILE_PCRE = undef;my $DOMAIN_DBSKIPLIST_FILE = undef;my $DOMAIN_DBSKIPLIST_FILE_PCRE = undef;my $DOMAIN_DBONLYLIST_FILE = undef;my $DOMAIN_DBONLYLIST_FILE_PCRE = undef;
GetOptions( 'file=s' => \$PDNSFILE, 'skiplist=s' => \$DOMAIN_DBSKIPLIST_FILE, 'skiplist-pcre=s' => \$DOMAIN_DBSKIPLIST_FILE_PCRE, 'whitelist=s' => \$DOMAIN_WHITELIST_FILE, 'whitelist-pcre=s' => \$DOMAIN_WHITELIST_FILE_PCRE, 'blacklist=s' => \$DOMAIN_BLACKLIST_FILE, 'blacklist-pcre=s' => \$DOMAIN_BLACKLIST_FILE_PCRE, 'onlylist=s' => \$DOMAIN_DBONLYLIST_FILE, 'onlylist-pcre=s' => \$DOMAIN_DBONLYLIST_FILE_PCRE, 'alertlog=s' => \$ALERTLOG, 'batch' => \$BATCH, 'nodb' => \$NODB, 'debug=s' => \$DEBUG, 'daemon' => \$DAEMON, 'verbose' => \$VERBOSE,);
our $HASH_BLACKLIST = {};our $HASH_WHITELIST = {};our $HASH_DBSKIPLIST= {};our $HASH_DBONLYLIST= {};$HASH_BLACKLIST->{'pcre'} = [load_domain_list_pcre($DOMAIN_BLACKLIST_FILE_PCRE)] if $DOMAIN_BLACKLIST_FILE_PCRE;$HASH_BLACKLIST->{'static'} = load_domain_list_static($DOMAIN_BLACKLIST_FILE) if $DOMAIN_BLACKLIST_FILE;$HASH_WHITELIST->{'pcre'} = [load_domain_list_pcre($DOMAIN_WHITELIST_FILE_PCRE)] if $DOMAIN_WHITELIST_FILE_PCRE;$HASH_WHITELIST->{'static'} = load_domain_list_static($DOMAIN_WHITELIST_FILE) if $DOMAIN_WHITELIST_FILE;$HASH_DBSKIPLIST->{'pcre'} = [load_domain_list_pcre($DOMAIN_DBSKIPLIST_FILE_PCRE)] if $DOMAIN_DBSKIPLIST_FILE_PCRE;$HASH_DBSKIPLIST->{'static'} = load_domain_list_static($DOMAIN_DBSKIPLIST_FILE) if $DOMAIN_DBSKIPLIST_FILE;$HASH_DBONLYLIST->{'pcre'} = [load_domain_list_pcre($DOMAIN_DBONLYLIST_FILE_PCRE)] if $DOMAIN_DBONLYLIST_FILE_PCRE;$HASH_DBONLYLIST->{'static'} = load_domain_list_static($DOMAIN_DBONLYLIST_FILE) if $DOMAIN_DBONLYLIST_FILE;
if (($HASH_WHITELIST) && (not $HASH_BLACKLIST)){ logger("[W] Whitelist without Blacklist does not make sense!"); $HASH_WHITELIST = undef; }
if ((not defined $HASH_DBONLYLIST->{'static'}) && (not defined $HASH_DBONLYLIST->{'pcre'})) { # Should also check that there are any entries if they are defined. $HASH_DBONLYLIST = undef;}
# Signal handlersuse vars qw(%sources);#$SIG{"HUP"} = \&recreate_merge_table;$SIG{"INT"} = sub { game_over() };$SIG{"TERM"} = sub { game_over() };$SIG{"QUIT"} = sub { game_over() };$SIG{"KILL"} = sub { game_over() };#$SIG{"ALRM"} = sub { file_watch(); alarm $TIMEOUT; };
logger("[*] Starting pdns2db.pl");
# Prepare to meet the world of Daemonsif ( $DAEMON ) { logger("[*] Daemonizing..."); chdir ("/") or die "chdir /: $!\n"; open (STDIN, "/dev/null") or die "open /dev/null: $!\n"; open (STDOUT, "> $LOGFILE") or die "open > $LOGFILE: $!\n"; defined (my $dpid = fork) or die "fork: $!\n"; if ($dpid) { # Write PID file open (PID, "> $PIDFILE") or die "open($PIDFILE): $!\n"; print PID $dpid, "\n"; close (PID); exit 0; } setsid (); open (STDERR, ">&STDOUT");}
if ($NODB == 0) { logger("[*] Connecting to database..."); $dbh = DBI->connect($DBI,$DB_USERNAME,$DB_PASSWORD, {RaiseError => 1, mysql_auto_reconnect=>1}) or die "$DBI::errstr"; # Setup the pdns table, if not exist setup_db();} else { logger("[*] Skipping database operations...");}
# Start file_watch() which looks for new dns data and puts them into dblogger("[*] Looking for passive DNS data in file: $PDNSFILE");file_watch($PDNSFILE);exit;
=head1 FUNCTIONS
=head2 setup_db
Checks if the pdns table exists, if not make it.
=cut
sub setup_db {
if (checkif_table_exist($TABLE_NAME)) { return; } else { if (new_pdns_table($TABLE_NAME)) { die "[E] Table $TABLE_NAME does not exist, and we could not create it! Sorry!\n"; } }}
=head2 file_watch
This sub looks for new DNS data in a file. Takes $filename to watch as input.
=cut
sub file_watch { my $logfile = shift; my $startsize = 0; my $pos = 0; #infinite loop while (1) { $startsize = (stat $logfile)[7];
if (!defined $startsize) { # No such file (Log rotate?) sleep $TIMEOUT; next; }
if (!defined $pos) { # Initial run. $pos = $startsize; }
if ($startsize < $pos) { # Log rotated #parseLogfile ($rotlogfile, $pos, (stat $rotlogfile)[7]); $pos = 0; }
parseLogfile ($logfile, $pos, $startsize); $pos = $startsize;
if ($BATCH == 1) { logger("[*] Processing of $logfile is done, exiting!"); exit 0; } sleep $TIMEOUT; }}
sub parseLogfile { my ($fname, $start, $stop) = @_; open (LOGFILE, $fname) or exit 3; seek (LOGFILE, $start, 0) or exit 2;
LINE: while (tell (LOGFILE) < $stop) { my $line =<LOGFILE>; chomp ($line); my $wret = 0; my $bret = 0; my $sret = 0;
my @elements = split(/\|\|/,$line); unless(@elements == 9) { logger("[W] Not valid Nr. of args in format: '$fname'"); next LINE; }
my ($tst, $cip, $sip, $rr, $query, $type, $answer, $ttl, $count) = @elements; $query =~ s/^(.*)\.$/$1/; $answer =~ s/^(.*)\.$/$1/;
if (($HASH_DBSKIPLIST) && ($sret = match_domain($query, $answer, $HASH_DBSKIPLIST))) { logger("[*] Domain marked to skip DB insertion: $query or $answer") if $VERBOSE; next LINE; }
if (($HASH_WHITELIST) && ($HASH_BLACKLIST) &&($wret = match_domain($query, $answer, $HASH_WHITELIST))) { logger("[*] Whitelisted domain: $query or $answer") if $VERBOSE; } elsif (($HASH_BLACKLIST) && ($bret = match_domain($query, $answer, $HASH_BLACKLIST))) { logger("[*] Blacklisted domain: $query or $answer") if $VERBOSE; if (open (ALOG, ">> $ALERTLOG") ) { print ALOG $line, "\n"; close (ALOG); } else { logger("[W] Problems with open($ALERTLOG): $!"); } }
if (($HASH_DBONLYLIST) && ($sret = match_domain($query, $answer, $HASH_DBONLYLIST))) { logger("[*] Onlylisted domain: $query or $answer") if $VERBOSE; put_dns_to_db(@elements) if $NODB == 0; } elsif (not defined $HASH_DBONLYLIST) { put_dns_to_db(@elements) if $NODB == 0; } else { put_dns_to_db(@elements) if $NODB == 0; } } close(LOGFILE);}
sub put_dns_to_db { # 1322849924.123456||192.168.1.1||8.8.8.8||IN||www.adobe.com.||CNAME||www.wip4.adobe.com.||3600||22 # 1322849924.123456||192.168.1.1||8.8.8.8||IN||www.adobe.com.||A||193.104.215.61||600||11 my ($tst, $cip, $sip, $rr, $query, $type, $answer, $ttl, $count) = @_; my ($ts, $tsu) = split(/\./,$tst); my $tsl = $ts;
$query =~ s/^(.*)\.$/$1/; # Strip trailing dot $answer =~ s/^(.*)\.$/$1/; # Strip trailing dot $query =~ s/(')/\\$1/g; # Wash "user-input" for non-friendly sql chars $answer =~ s/(')/\\$1/g; # Wash "user-input" for non-friendly sql chars
my ($sql, $sth);
eval{ $sql = qq[ INSERT INTO $TABLE_NAME ( QUERY,RR,MAPTYPE,ANSWER,TTL,COUNT,LAST_SEEN,FIRST_SEEN ) VALUES ( '$query','$rr','$type','$answer','$ttl','$count',FROM_UNIXTIME($ts),FROM_UNIXTIME($tsl) ) ON DUPLICATE KEY UPDATE TTL = if (TTL < $ttl, $ttl, TTL), COUNT = COUNT + '$count', LAST_SEEN = if (LAST_SEEN < FROM_UNIXTIME($ts), FROM_UNIXTIME($ts), LAST_SEEN), FIRST_SEEN = if (FIRST_SEEN > FROM_UNIXTIME($ts), FROM_UNIXTIME($ts), FIRST_SEEN) ]; logger("[D] $sql") if $DEBUG > 1; $sth = $dbh->prepare($sql); $sth->execute; $sth->finish; }; if ($@) { # Failed return 1; } return 0;}
=head2 new_pdns_table
Creates a new pdns table. Takes $tablename as input.
=cut
sub new_pdns_table { my ($tablename) = shift; my ($sql, $sth); logger("[*] Creating $TABLE_NAME..."); eval{ $sql = " \ CREATE TABLE IF NOT EXISTS $tablename \ ( \ ID BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, \ QUERY varchar(255) NOT NULL DEFAULT '', \ MAPTYPE varchar(10) NOT NULL DEFAULT '', \ RR varchar(10) NOT NULL DEFAULT '', \ ANSWER varchar(255) NOT NULL DEFAULT '', \ TTL int(10) NOT NULL DEFAULT '0', \ COUNT BIGINT(20) UNSIGNED NOT NULL DEFAULT '1', \ FIRST_SEEN DATETIME NOT NULL, \ LAST_SEEN DATETIME NOT NULL, \ PRIMARY KEY (ID), \ UNIQUE KEY MARQ (MAPTYPE,ANSWER,RR,QUERY), \ KEY query_idx (QUERY), \ KEY answer_idx (ANSWER) \ ) \ "; $sth = $dbh->prepare($sql); $sth->execute; $sth->finish; }; if ($@) { # Failed return 1; } return 0;}
=head2 checkif_table_exist
Checks if a table exists. Takes $tablename as input and returns 1 if $tablename exists, and 0 if not.
=cut
sub checkif_table_exist { my $tablename = shift; my ($sql, $sth); eval { $sql = "select count(*) from pdns where 1=0"; $dbh->do($sql); }; if ($dbh->err) { logger("[D] Table $tablename does not exist.") if $DEBUG; return 0; } else{ return 1; }}
=head2 load_domain_list
Loads domains from file
File format: <domain written in regexp>
Example: ^news\..*daily\.com$
=cut
sub load_domain_list_pcre { my $file = shift; my %signatures; my $cnt = 0;
open(my $FH, "<", $file) or die "[E] Could not open '$file': $!";
LINE: while (my $line = readline $FH) { chomp $line; $line =~ s/\#.*//; $line =~ s/\t//g; $line =~ s/ //g; next LINE unless($line); # empty line # One should check for a more or less sane signature file.
logger("[D] $line") if $DEBUG; $signatures{$line} = [qr{$line}]; $cnt++; } logger("[D] Loaded $cnt domains") if $DEBUG;
return map { $signatures{$_} } sort { length $b <=> length $a } keys %signatures;}
sub load_domain_list_static { my $file = shift; my $signatures = {}; my $cnt = 0;
open(my $FH, "<", $file) or die "[E] Could not open '$file': $!";
LINE: while (my $line = readline $FH) { chomp $line; $line =~ s/\#.*//; $line =~ s/\t//g; $line =~ s/ //g; next LINE unless($line); # empty line # One should check for a more or less sane signature file.
logger("[D] $line") if $DEBUG; $signatures->{"$line"} = 1; $cnt++; } logger("[D] Loaded $cnt static domains") if $DEBUG;
return $signatures;}
=head2 match_domain
Takes input: $domain, $@domain_list_to_match_on Returns 1 if found, 0 if not.
=cut
sub match_domain { my ($query, $answer, $MHASH) = @_;
# First we should match agains "static" domain list. if ($MHASH->{'static'}->{"$query"}) { logger("[D] Domain $query match on static query domain: $query") if $DEBUG; return 1; } elsif ($MHASH->{'static'}->{"$answer"}) { logger("[D] Domain $answer match on static answer domain: $answer") if $DEBUG; return 1; } else { logger("[D] No static match on domain: $query or $answer") if $DEBUG; }
# Check domain against domains in expensive pcre list my $CRAP = $MHASH->{'pcre'}; for my $s (@$CRAP) { my $re = $s->[0]; if ($query =~ /$re/) { logger("[D] Domain $query match on pcre: $re") if $DEBUG; return 1; } elsif ($answer =~ /$re/) { logger("[D] Domain $answer match on pcre: $re") if $DEBUG; return 1; } }
logger("[D] No pcre match on domain: $query or $answer") if $DEBUG; return 0;}
=head2 logger
Adds time prefix to logg output. Takes $msg as input.
=cut
sub logger { my $msg = shift; print strftime('%F %H:%M:%S', localtime), " $msg\n";}=head2 game_over
Terminates the program in a sainfull way.
=cut
sub game_over { logger("[*] Terminating..."); if (defined $dbh) { $dbh->disconnect; } unlink ($PIDFILE); exit 0;}
=head1 AUTHOR
Edward Fjellskaal <edwardfjellskaal@gmail.com>
=head1 COPYRIGHT
This library is free software, you can redistribute it and/or modify it under the same terms as Perl itself.
=cut123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201#!/usr/bin/perl
# ----------------------------------------------------------------------# Search in PassiveDNS DB# Copyright (C) 2011-2012, Edward Fjellskål <edwardfjellskaal@gmail.com>## This program is free software; you can redistribute it and/or modify# it under the terms of the GNU General Public License as published by# the Free Software Foundation; either version 2 of the License, or# (at your option) any later version.## This program is distributed in the hope that it will be useful,# but WITHOUT ANY WARRANTY; without even the implied warranty of# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the# GNU General Public License for more details.## You should have received a copy of the GNU General Public License# along with this program; if not, write to the Free Software# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.# ----------------------------------------------------------------------# Added Resource Record Type : hookol 20180321
use strict;use warnings;use POSIX ('strftime');use Time::Local;use Date::Simple ('date', 'today');use Getopt::Long qw/:config auto_version auto_help/;use DBI;
# You need to set DB user,password and host to connect to...my $db_host = 'localhost';my $DB = 'pdns';my $db_user_name = 'pdns';my $db_password = 'pdns';my $DLIMIT = 100;
=head1 NAME
search-pdns.pl - Search in the PassiveDNS database
=head1 VERSION
0.1.1
=head1 SYNOPSIS
$ search-pdns.pl [options]
OPTIONS:
-s : %IP/Domain% -r : Enables raw search -t : Resource Record Type (A, NS, MX, SOA, etc.) --first-seen : Date to search from in iso format (2010-01-01 etc.) --last-seen : Date to search to in iso format (2020-01-01 etc.) --limit : Limit on search results (100)
EXAMPLES:
# Searches for "%facebook%" search-pdns.pl -s "facebook"
# Searches for "^facebook.%.com$" search-pdns.pl -r -s "facebook.%.com"
# Searches for domains/IPs that existed just one day, 2011-01-01. search-pdns.pl --first-seen 2011-01-01 --last-seen 2011-01-01
=cut
our $DEBUG = 0; # Set to 1 for debugging, 2 to exit before the sql callour $RAW = 0;our $SEARCH = "%";our $FROM_DATE;our $TO_DATE;our $LIMIT;our $TYPE;
GetOptions( 'd=s' => \$DEBUG, 's=s' => \$SEARCH, 'r' => \$RAW, 'first-seen=s' => \$FROM_DATE, 'last-seen=s' => \$TO_DATE, 'limit=s' => \$LIMIT, 't=s' => \$TYPE,);
if ($SEARCH eq "") { print "[*] You need to search for something....\n"; exit 0;}
my $dsn = "DBI:mysql:$DB:" . $db_host;my $dbh = DBI->connect($dsn, $db_user_name, $db_password);
our ($QUERY, $QUERY1, $QUERY2) = q();
$QUERY = qq[SELECT query, answer, first_seen, last_seen, ttl, count, maptype FROM pdns WHERE ];
if (defined $FROM_DATE ) { if ($FROM_DATE=~ /^\d\d\d\d\-\d\d\-\d\d$/) { print "Searching from date: $FROM_DATE 00:00:01\n" if $DEBUG; $QUERY1 = $QUERY . qq[first_seen > '$FROM_DATE 00:00:01' ]; } elsif ($FROM_DATE=~ /^\d\d\d\d\-\d\d\-\d\d \d\d:\d\d:\d\d$/) { print "Searching from date: $FROM_DATE\n" if $DEBUG; $QUERY1 = $QUERY . qq[first_seen > '$FROM_DATE' ]; }} else { print "Searching from date: Thu Jan 1 00:00:00 UTC 1970\n" if $DEBUG; $QUERY1 = $QUERY . qq[first_seen > '1970-01-01 00:00:01' ];}
if (defined $TO_DATE) { if ($TO_DATE =~ /^\d\d\d\d\-\d\d\-\d\d$/) { print "Searching to date: $TO_DATE 23:59:59\n" if $DEBUG; $QUERY1 = $QUERY1 . qq[AND last_seen < '$TO_DATE' ]; } elsif ($TO_DATE =~ /^\d\d\d\d\-\d\d\-\d\d \d\d:\d\d:\d\d$/) { print "Searching to date: $TO_DATE\n" if $DEBUG; $QUERY1 = $QUERY1 . qq[AND last_seen < '$TO_DATE' ]; }}
$QUERY2 = $QUERY1;
if (defined $SEARCH) { print "Searching for: $SEARCH\n" if $DEBUG; if ( $RAW == 1 ) { $QUERY1 = $QUERY1 . qq[AND query like '$SEARCH' ]; $QUERY2 = $QUERY2 . qq[AND answer like '$SEARCH' ]; } else { $QUERY1 = $QUERY1 . qq[AND query like '%$SEARCH%' ]; $QUERY2 = $QUERY2 . qq[AND answer like '%$SEARCH%' ]; }}
if (defined $TYPE) { $QUERY1 = $QUERY1 . qq[AND maptype = '$TYPE' ]; $QUERY2 = $QUERY2 . qq[AND maptype = '$TYPE' ];}
$QUERY = $QUERY1 . qq[ UNION ] . $QUERY2;
if (defined $LIMIT && $LIMIT =~ /^([\d])+$/) { print "Limit: $LIMIT\n" if $DEBUG; $DLIMIT = $LIMIT; $QUERY = $QUERY . qq[ORDER BY last_seen LIMIT $LIMIT ];} else { print "Limit: $DLIMIT\n" if $DEBUG; $QUERY = $QUERY . qq[ORDER BY last_seen LIMIT $DLIMIT ];}
print "\nmysql> $QUERY;\n\n" if $DEBUG;
exit 0 if $DEBUG > 1;
my $pri = $dbh->prepare( qq{ $QUERY } );$pri->execute();
my $cnt = 0;print " === PassiveDNS ===\n\n";print " FirstSeen | LastSeen | TYPE | TTL | Query | Answer | Count\n";print "------------------------------------------------------------------------------------------------------------------------------\n";while (my ($query, $answer, $firstseen, $lastseen, $ttl, $count, $maptype) = $pri->fetchrow_array()) { next if not defined $query or not defined $answer; $cnt++; #printf("%20s | %20s | %5s | %6s | %-34s | %12s\n", $firstseen, $lastseen, $maptype, $ttl, $query, $answer); printf("%20s | %19s | %5s | %6s | %-34s | %14s | %8s\n", $firstseen, $lastseen, $maptype, $ttl, $query, $answer, $count);
}print "Displayed $cnt (sql limit: $DLIMIT)\n";
$pri->finish();$dbh->disconnect();
=head1 AUTHOR
Edward Fjellskaal <edwardfjellskaal@gmail.com>
=head1 COPYRIGHT
Copyright (C) 2011, Edward Fjellskaal (edwardfjellskaal@gmail.com)
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
=cut123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177<?php# --------------------------------------------------------------------------# Copyright (C) 2013 Edward Fjellskål <edward.fjellskaal@gmail.com>## This program is free software; you can redistribute it and/or modify# it under the terms of the GNU General Public License as published by# the Free Software Foundation; either version 2 of the License, or# (at your option) any later version.## This program is distributed in the hope that it will be useful,# but WITHOUT ANY WARRANTY; without even the implied warranty of# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the# GNU General Public License for more details.## You should have received a copy of the GNU General Public License# along with this program; if not, write to the Free Software# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.# --------------------------------------------------------------------------## Configure Start$DATABASE = "127.0.0.1";$DBUSER = "pdns";$DBTABLE = "pdns";$DBPASSWD = "pdns";$DBLIMIT = 500;# Configure End
$query = sanitize("query"); if (empty($query)) $query = "";
print_header();print_search_body();
if ($query) { echo "<center>"; mysql_connect($DATABASE, $DBUSER, $DBPASSWD) or die(mysql_error()); mysql_select_db($DBTABLE) or die(mysql_error()); if ( filter_var($query, FILTER_VALIDATE_IP) ) { echo "<b>PassiveDNS Records for IP: ". $query ."</b><br><br>"; $domains = mysql_query("SELECT * FROM pdns WHERE answer='$query' LIMIT $DBLIMIT"); if(mysql_num_rows($domains)==0){ echo "<b>No records found...</b><br><br>"; } else { 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>"; echo ' '; while ( $r = mysql_fetch_array($domains) ) { echo "<tr>"; echo "<td>". $r['FIRST_SEEN'] ."</td>"; echo "<td>". $r['LAST_SEEN'] ."</td>"; echo "<td>". $r['MAPTYPE'] ."</td>"; echo "<td>". $r['TTL'] ."</td>"; echo "<td><a href='?query=". $r['QUERY'] ."'>". $r['QUERY'] ."</a></td>"; echo "<td><a href='?query=". $r['ANSWER'] ."'>". $r['ANSWER'] ."</a></td>"; echo "<td>". $r['COUNT'] ."</td>"; echo "</tr>"; } } } else { echo "<b>PassiveDNS Records for Domain: ". $query ."</b> <br><br>"; $domains = mysql_query("SELECT * FROM pdns WHERE query LIKE '$query' LIMIT $DBLIMIT"); if(mysql_num_rows($domains)==0){ echo "<b>No records found...</b><br><br>"; } else { 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>"; echo ' '; while ( $r = mysql_fetch_array($domains) ) { echo "<tr>"; echo "<td>". $r['FIRST_SEEN'] ."</td>"; echo "<td>". $r['LAST_SEEN'] ."</td>"; echo "<td>". $r['MAPTYPE'] ."</td>"; echo "<td>". $r['TTL'] ."</td>"; echo "<td><a href='?query=". $r['QUERY'] ."'>". $r['QUERY'] ."</a></td>"; echo "<td><a href='?query=". $r['ANSWER'] ."'>". $r['ANSWER'] ."</a></td>"; echo "<td>". $r['COUNT'] ."</td>"; echo "</tr>"; } } } echo "</center>";}
print_tail();
function getVar($in) {
if (isset($_POST[$in])) { $out = $_POST[$in]; } else { $out = $_GET[$in]; }
if (get_magic_quotes_gpc()) { if (is_array($out)) { foreach ($out as $el) { $array[] = stripslashes($el); } $out = $array; } else { $out = stripslashes($out); } }
return $out;}
function sanitize($in) { $qvar = strip_tags(addslashes(getVar($in))); if ( preg_match('/(\w+\.)*\w{2,}\.\w{2,4}$/i', $qvar) ) { /* Might be a domain */ return $qvar; } 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) ) { /* Might be a IPv4 */ return $qvar; } else if (preg_match('/^[a-f0-9]{1,4}:([a-f0-9]{0,4}:){1,6}[a-f0-9]{1,4}$/i', $qvar)) { /* FE80:0000:0000:0000:0202:B3FF:FE1E:8329 or FE80::0202:B3FF:FE1E:8329 */ /* or even 2001:db8::1 or 0:0:0:0:0:ffff:192.1.56.10 */ /* Might be a IPv6 */ return $qvar; } else { /* B0rked */ echo "B0rked"; return ""; }}
function print_header() { echo "<html><head><title>PassiveDNS</title>"; echo '<style type="text/css"> td,p,div.box { color: #000; margin: 4px; padding: 4px; font-family: verdana, arial, helvetica, sans-serif; font-size: 13px; font-weight: normal; border-bottom: 1px none #BFE9FF; } tr.odd { background-color: #E2F1FF; } table { margin-left: auto; margin-right: auto; } </style> </head> <body><center> <div style="width: 860px; margin:auto;"> <p> This data has been collected using <a href="http://github.com/gamelinux/passivedns">PassiveDNS</a>. </p> </div> <table width="860" cellpadding="2" cellspacing="0">';}
function print_search_body() { echo '<tr><td><center><form name search method="GET">'; echo 'Domain/IP: <input type="text" maxlength="300" name="query">'; echo '<input type="submit" value="Search"></form><center><br>';}
function print_tail() { echo '</center></body></html>';}
?>dns_tunneling/dns_tunneling_processed.csvAdded
dns_tunneling/metadata.jsonAdded+24
dns_tunneling/passivedns-master/.gitignoreAdded+28
dns_tunneling/passivedns-master/Makefile.amAdded+3
dns_tunneling/passivedns-master/READMEAdded+90
dns_tunneling/passivedns-master/bootstrapAdded+19
dns_tunneling/passivedns-master/configure.acAdded+293
dns_tunneling/passivedns-master/doc/AUTHORSAdded+27
dns_tunneling/passivedns-master/doc/ChangeLogAdded+52
dns_tunneling/passivedns-master/doc/How-it-works.txtAdded+37
dns_tunneling/passivedns-master/doc/INSTALLAdded+74
dns_tunneling/passivedns-master/doc/ISSUESAdded+9
dns_tunneling/passivedns-master/doc/LICENSEAdded+339
dns_tunneling/passivedns-master/doc/READMEAdded+38
dns_tunneling/passivedns-master/doc/README.upgradingAdded+18
dns_tunneling/passivedns-master/doc/ROADMAPAdded+62
dns_tunneling/passivedns-master/doc/TODOAdded+12
dns_tunneling/passivedns-master/etc/default/passivedns-debianAdded+44
dns_tunneling/passivedns-master/etc/init.d/passivedns-debianAdded+66
dns_tunneling/passivedns-master/etc/init.d/passivedns-redhatAdded+129
dns_tunneling/passivedns-master/etc/logrotate.d/passivednsAdded+13
dns_tunneling/passivedns-master/etc/sysconfig/passivedns-redhatAdded+66
dns_tunneling/passivedns-master/pdns.patchAdded+57
dns_tunneling/passivedns-master/src/Makefile.amAdded+17
dns_tunneling/passivedns-master/src/dns.cAdded+1886
dns_tunneling/passivedns-master/src/dns.hAdded+187
dns_tunneling/passivedns-master/src/passivedns.cAdded+1603
dns_tunneling/passivedns-master/src/passivedns.hAdded+580
dns_tunneling/passivedns-master/tools/README.skip_white_black-list.txtAdded+37
dns_tunneling/passivedns-master/tools/pdns2db.plAdded+531
dns_tunneling/passivedns-master/tools/search-pdns.plAdded+201
dns_tunneling/passivedns-master/www/index.phpAdded+177