Networking – How to log all DNS requests made through OpenWRT router

dnsdnsmasqnetworkingopenwrt

I have an OpenWRT router that is running dnsmasq. I want to create a file that has each domain that has been requested through the router. My output should looks something like this:

google.com
cnn.com
wikipedia.com
news.google.com
gmail.com

Ideally there wouldn't be any duplicates. I could probably setup a cron job that would remove duplicates if necessary. Right now I'm trying to figure out a good way to log them. I looked at the options for dnsmasq. I found the following options:

 -q, --log-queries                       Log DNS queries.
 -8, --log-facility=<facilty>|<file>     Log to this syslog facility or file. (defaults to DAEMON)
--log-dhcp                          Extra logging for DHCP.
--log-async[=<integer>]             Enable async. logging; optionally set queue length.

On OpenWRT these settings seem to be buried in the /etc/init.d/dnsmasq file. I tried setting them without any luck. 🙁 Is there an easier way to accomplish my goal?

Ah! With a little hackery I was able to get it to write to a log file. However, it doesn't have the data I need to create this list. Maybe dnsmasq can't do what I want it to?

Best Answer

You can edit the config file:

vi /etc/dnsmasq.conf

    # /etc/dnsmasq.conf
    log-dhcp
    log-queries
    log-facility=/tmp/dnsmasq.log

Or edit another config file:

vi /etc/config/dhcp

    config dnsmasq
        ...
        option logdhcp '1'
        option logqueries '1'
        option logfacility '/tmp/dnsmasq.log'

Then restart service:

/etc/init.d/dnsmasq restart

Log file can be parsed in real-time with tail+awk:

$ vi dnsmasq.awk

    #!/usr/bin/awk -f

    BEGIN {
      OFS = ",";
    }

    $5 == "query[A]" {
      time = mktime( \
        sprintf("%04d %02d %02d %s\n", \
          strftime("%Y", systime()), \
          (match("JanFebMarAprMayJunJulAugSepOctNovDec",$1)+2)/3, \
          $2, \
          gensub(":", " ", "g", $3) \
        ) \
      );
      query = $6;
      host = $8;
      print time, host, query;
    }

$ chmod +x dnsmasq.awk

$ tail -f /tmp/dnsmasq.log | ./dnsmasq.awk

1468999090,192.168.1.100,google.com
1468999092,192.168.1.101,youtube.com
1468999095,192.168.1.102,facebook.com
1468999097,192.168.1.100,qa.sockets.stackexchange.com

More advanced method is sending log via filebeat to ELK in realtime.

Related Question