Last active
December 29, 2015 10:59
-
-
Save nansenat16/7660948 to your computer and use it in GitHub Desktop.
tcpdump sniffer DNS query and log it
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Usage: | |
// #tcpdump -i eth1 -n|grep domain|php dns_rec.php | |
// #nohup tcpdump -i eth1 -n|grep domain|php dns_rec.php & | |
// | |
ini_set('memory_limit','256M'); | |
$qmap=array(); | |
define('LOG_PATH','/root/dns_%s.csv'); | |
$f=fopen('php://stdin','r'); | |
while(true){ | |
$line=fgets($f); | |
//echo $line."\n"; | |
$tmp=split(' ',$line); | |
//echo $tmp[4].' '.$tmp[5].' '.$tmp[6]."\n"; | |
if(count($tmp)<6){exit();} | |
if($tmp[6]=='A?'){ | |
$qid=$tmp[2].'_'.substr($tmp[5],0,strlen($tmp[5])-1); | |
$sip=substr($tmp[2],0,strrpos($tmp[2],'.')); | |
$dip=substr($tmp[4],0,strrpos($tmp[4],'.')); | |
if(!isset($qmap[$qid])){ | |
$qmap[$qid]=array('n'=>$tmp[7],'i'=>$sip,'d'=>$dip,'t'=>time()); | |
} | |
} | |
if(strpos($tmp[6],'/')){ | |
$qid=substr($tmp[4],0,strlen($tmp[4])-1).'_'.$tmp[5]; | |
$str_header=$tmp[6]; | |
$str_tmp=implode(' ',$tmp); | |
$int_start=strpos($str_tmp,$str_header)+strlen($str_header); | |
$str_data=substr($str_tmp,$int_start); | |
$list_ans=explode(',', $str_data); | |
for($n=0;$n<count($list_ans);$n++){ | |
$list_ans[$n]=trim($list_ans[$n]); | |
if($n==count($list_ans)-1){ | |
$int_end=strrpos($list_ans[$n],' '); | |
$list_ans[$n]=substr($list_ans[$n],0,$int_end); | |
} | |
} | |
//echo $qid."\n"; | |
//print_r($list_ans); | |
if(isset($qmap[$qid])){ | |
$domain=$qmap[$qid]['n']; | |
$src=$qmap[$qid]['i']; | |
$dns=$qmap[$qid]['d']; | |
$output=array('q'=>$domain,'s'=>$src,'d'=>$dns,'a'=>$list_ans); | |
unset($qmap[$qid]); | |
save_log($output); | |
} | |
} | |
reset($qmap); | |
//print_r($qmap); | |
while(!is_null($k=key($qmap))){ | |
if(time()-$qmap[$k]['t']>10){ | |
//echo 'Timeout '.$qmap[$k]['n']."\n"; | |
unset($qmap[$k]); | |
} | |
next($qmap); | |
} | |
} | |
// DO something you want | |
function save_log($data){ | |
$d=date('Ymd'); | |
$log=sprintf(LOG_PATH,$d); | |
//echo $log."\n"; | |
$l=fopen($log,'a+'); | |
fwrite($l,time().','.json_encode($data)."\n"); | |
fclose($l); | |
//print_r($data); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment