#!/bin/sh

# Guy Bruneau, guybruneau[@]outlook[.]com, gbruneau[@]ipss[.]ca
# Date: 7 Aug 2019
# Version: 1.0

# Source code put in public domain by Guy Bruneau, no Copyright
# Use at your own risk

# This software is provided "as is" without express or implied warranty or support

# This script is used to extract all metadata associated with DNS Traffic

# Cronjob added to the account running the query

# This script extract DNS metadata on a hourly basis
# 0 * * * * /home/guy/scripts/dnsmeta.sh > /dev/null 2>&1

# Account used to query the metadata
NWSDK="/usr/local/bin/nwsdk_csv.py -c http://192.168.25.30:50103 -u sdk -p netwitness"

NOW=$(date -d "now" "+%Y-%m-%d %H-:00:00")
HOUR=$(date -d "now" "+%h")
TODAY=$(date -d "TODAY" "+%Y-%m-%d")
YESTERDAY=$(date -d "yesterday" "+%Y-%m-%d %H:00:00")
LASTHOUR=$(date -d "-1 hour" "+%Y-%m-%d %H:00:00")
FILENAME=$(date -d "-1 hour" "+%H")

# Last hour query

TIME="time='$LASTHOUR'-'$NOW'"

# Check to ensure today's directory exist

OUTPUTDIR="/opt/Metadata/DNS/$TODAY"

if [[ ! -d $OUTPUTDIR ]]; then
	mkdir -p $OUTPUTDIR
fi

# Metadata keys part of the query
OUTPUT="time,ip.src,udp.srcport,ip.dst,udp.dstport,analysis.service,alias.host,direction,dns.querytype,dns.responsetype,payload.req,payload.res,alias.ip,risk.error,streams,dns.resptext --no-count"

# NetWitness query that check the our and date
# If the time is between 0-22, data is save in today's directory
# If the time is 23, data is will be saved in the previous day's directory

if [ $FILENAME != '23' ]; then
   $NWSDK -k $OUTPUT -w "$TIME && service=53" > /opt/Metadata/DNS/$TODAY/dns$FILENAME.csv
elif [ $FILENAME == '23' ]; then
   $NWSDK -k $OUTPUT -w "$TIME && service=53" > /opt/Metadata/DNS/$YESTERDAY/dns$FILENAME.csv
fi

# Change directory permission to be readable by everyone

chmod 777 -R $OUTPUTDIR
