Saturday, May 5, 2012

tcpdump in Perl


半夜睡不著不知道要幹嘛...

爬起來摸 CPAN 上一些簡單的 packet sniffer in Perl 的 module

玩著玩著就寫(ㄔㄠ)出一個了

基本上還是用 pcap(3) (Packet Capture library)

不過 Perl 有 NetPacket module 把他抽象化了

http://search.cpan.org/search?query=NetPacket

概念上很簡單,就一層一層把 header 拆掉 (encapsulation ?)

把 link layer => IP layer => transport layer 依序拆開

可能有念過 networking 會比較有概念 :P

最後用 Data::HexDumper 把 binary 拆成 hex 跟 ascii 比較好閱讀

http://search.cpan.org/~dcantrell/Data-Hexdumper-3.00/lib/Data/Hexdumper.pm



#!/usr/bin/perl                                                                 
                                                                                
use 5.012;                                                                      
                                                                                
use Net::PcapUtils;                                                             
use NetPacket::Ethernet qw(:strip);                                             
use NetPacket::IP qw(IP_PROTO_TCP);                                             
use NetPacket::TCP;                                                             
use Data::HexDump;                                                              
                                                                                
                                                                                
sub process_pkt {                                                               
    my ($user_data,$header, $packet) = @_;                                      
    # decode the Ethernet and IP headers                                        
    my $ip = NetPacket::IP->decode(eth_strip($packet));                         
                                                                                
    if ($ip->{proto} == IP_PROTO_TCP) {                                         
        # decode TCP headers                                                    
        my $tcp = NetPacket::TCP->decode($ip);                                  
        # now we get TCP packet XD                                              
        say "\n$ip->{src_ip}($tcp->{src_port}) -> $ip->{dest_ip}($tcp->{dest_port})";
        say HexDump $ip->{data};                                                
    }                                                                           
}                                                                               
                                                                                
my $filter = join(" ", @ARGV);                                                  
say $filter;                                                                    
Net::PcapUtils::loop(\&process_pkt, SNAPLEN=> 65536, FILTER => $filter);




Usage


    sudo ./pcap.pl


    sudo ./pcap.pl host 140.113   # 支援簡單的 filter

No comments:

Post a Comment