Selective dnsmasq logging (split dnsmasq logging)

My system provides DNS services, using dnsmasq, to several different subnets. I wish to log specific queries to different files – as I want to identify, and maybe even respond to certain DNS queries of the IoT network.

The (excellent) utility dnsmasq is unable to split the logging into multiple log files, or filter logging by expressions, so we need to combine the power of dnsmasq’s logging with rsyslogd’s expression matching.

Let’s assume I have two networks. One is 192.168.1.x – the home LAN, and the other is 172.16.1.x – the IoT network.

I have added to my /etc/dnsmasq.conf file the following lines:

log-facility=DAEMON
log-async
log-queries=extra

I have created a file called /etc/rsyslog.d/dnsmasq.conf with the following contents:

if $programname == 'dnsmasq' and $msg contains ' 192.168.1.' then /var/log/dnsmasq/dnsmasq-lan.log
if $programname == 'dnsmasq' and $msg contains ' 172.16.1.' then /var/log/dnsmasq/dnsmasq-iot.log
if $programname == 'dnsmasq-dhcp' then /var/log/dnsmasq/dnsmasq-dhcp.log
if $programname == 'dnsmasq' then stop
if $programname == 'dnsmasq-dhcp' then stop

Of course – I need to create the directory /var/log/dnsmasq, and create a logrotate entry /etc/logrotate.d/dnsmasq as follows:

/var/log/dnsmasq/dnsmasq-iot.log /var/log/dnsmasq/dnsmasq-lan.log /var/log/dnsmasq/dnsmasq-dhcp.log {
  monthly
  missingok
  notifempty
  maxsize 5M
  rotate 14
  delaycompress
  # create 0640 dnsmasq root
  sharedscripts
  postrotate
    /usr/bin/systemctl kill -s HUP rsyslog.service >/dev/null 2>&1 || true
  endscript
}

Note that the DNS queries of the networks are kept in a dedicated per-network file (dnsmasq-lan.log and dnsmasq-iot.log) and all general (non IP specific) messages are kept in dnsmasq-dhcp.log file. Logrotate makes sure I do not overfill my directory, and I can later on identify which IoT (or home, for that matter) DNS query is sent and by whom.

Tags: , , ,

Leave a Reply