Dump/Online.pm

filter: Statementstmt 100% 9 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 100% 12 / 12 CC 1 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Dump/Offline.pm ↑ Summary Dump/Online2.pm »
1 #
2 # $Id: Online.pm,v a93481b098ec 2020/05/01 08:55:56 gomor $
3 #
4 package Net::Frame::Dump::Online;
5 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 1 ▶use base qw(Net::Frame::Dump);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 our @AS = qw(
10 dev
11 timeoutOnNext
12 timeout
13 promisc
14 snaplen
15 unlinkOnStop
16 onRecv
17 onRecvCount
18 onRecvData
19 _pid
20 _sName
21 _sDataAwaiting
22 _firstTime
23 _son
24 _fcode
25 );
26 __PACKAGE__->cgBuildIndices;
27 __PACKAGE__->cgBuildAccessorsScalar(\@AS);
28  
29 BEGIN {
30 my $osname = {
31 cygwin => [ \&_checkWin32, ],
32 MSWin32 => [ \&_checkWin32, ],
33 };
34  
35 *_check = $osname->{$^O}->[0] || \&_checkOther;
36 }
37  
38 use Net::Frame::Dump qw(:consts);
39  
40 use Net::Pcap;
41 use Time::HiRes qw(gettimeofday);
42 use Storable qw(lock_store lock_retrieve);
43 use Net::Frame::Layer qw(:subs);
44  
45 sub _checkWin32 { return 1; }
46  
47 sub _checkOther {
48 if ($>) {
49 die("[-]: Net::Frame::Dump::Online: Must be EUID 0 (or equivalent) ".
50 "to open a device for live capture\n");
51 }
52 return 1;
53 }
54  
55 sub new {
56 my $self = shift->SUPER::new(
57 timeoutOnNext => 3,
58 timeout => 0,
59 promisc => 0,
60 snaplen => 1514,
61 unlinkOnStop => 1,
62 onRecvCount => -1,
63 _sDataAwaiting => 0,
64 @_,
65 );
66  
67 if (!defined($self->_sName)) {
68 my $int = getRandom32bitsInt();
69 $self->_sName("netframe-tmp-$$.$int.storable");
70 }
71  
72 $SIG{INT} = sub {
73 return unless $self->isFather;
74 $self->_clean;
75 };
76 $SIG{TERM} = sub {
77 return unless $self->isFather;
78 $self->_clean;
79 };
80  
81 if (!defined($self->dev)) {
82 print("[-] ".__PACKAGE__.": You MUST pass `dev' attribute\n");
83 return;
84 }
85  
86 return $self;
87 }
88  
89 sub _sStore {
90 lock_store(\$_[1], $_[0]->_sName) or do {
91 print("[-] ".__PACKAGE__.": lock_store: @{[$_[0]->_sName]}: $!\n");
92 return;
93 };
94 return 1;
95 }
96 sub _sRetrieve {
97 ${lock_retrieve(shift->_sName)};
98 }
99  
100 sub _sWaitFile {
101 my $self = shift;
102 my $startTime = gettimeofday();
103 my $thisTime = $startTime;
104 while (! -f $self->_sName) {
105 if ($thisTime - $startTime > 10) {
106 print("[-] ".__PACKAGE__.": too long for file creation: ".
107 $self->_sName."\n");
108 return;
109 }
110 $thisTime = gettimeofday();
111 }
112 return 1;
113 }
114  
115 sub _sWaitFileSize {
116 my $self = shift;
117  
118 $self->_sWaitFile;
119  
120 my $startTime = gettimeofday();
121 my $thisTime = $startTime;
122 while (! ((stat($self->_sName))[7] > 0)) {
123 if ($thisTime - $startTime > 10) {
124 $self->_clean;
125 print("[-] ".__PACKAGE__.": too long for file creation2: ".
126 $self->_sName."\n");
127 return;
128 }
129 $thisTime = gettimeofday();
130 }
131 return 1;
132 }
133  
134 sub _startOnRecv {
135 my $self = shift;
136  
137 my $err;
138 my $pd = Net::Pcap::open_live(
139 $self->dev,
140 $self->snaplen,
141 $self->promisc,
142 1000,
143 \$err,
144 );
145 unless ($pd) {
146 print("[-] ".__PACKAGE__.": open_live: $err\n");
147 return;
148 }
149 $self->_pcapd($pd);
150  
151 my $net = 0;
152 my $mask = 0;
153 Net::Pcap::lookupnet($self->dev, \$net, \$mask, \$err);
154 if ($err) {
155 print("[!] ".__PACKAGE__.": lookupnet: $err\n");
156 }
157  
158 my $fcode;
159 if (Net::Pcap::compile($pd, \$fcode, $self->filter, $self->filterCodeOptimizer, $mask) < 0) {
160 print("[-] ".__PACKAGE__.": compile: ". Net::Pcap::geterr($pd). "\n");
161 return;
162 }
163 $self->_fcode($fcode); # Used to free it later on, usually on stop call.
164  
165 if (Net::Pcap::setfilter($pd, $fcode) < 0) {
166 print("[-] ".__PACKAGE__.": setfilter: ". Net::Pcap::geterr($pd). "\n");
167 return;
168 }
169  
170 $self->getFirstLayer;
171  
172 # Setup onRecv enforced code, to make it simpler for user
173 my $callback = sub {
174 my ($userData, $hdr, $pkt) = @_;
175 my $h = {
176 raw => $pkt,
177 timestamp => $hdr->{tv_sec}.'.'.sprintf("%06d", $hdr->{tv_usec}),
178 firstLayer => $self->firstLayer,
179 };
180 &{$self->onRecv}($h, $userData);
181 };
182  
183 {
184 # We have to access onRecvData ARRAY indice to pass a ref
185 no strict 'vars';
186  
187 Net::Pcap::loop(
188 $pd, $self->onRecvCount, $callback, $self->[$__onRecvData],
189 );
190 }
191 }
192  
193 sub start {
194 my $self = shift;
195  
196 _check() or return;
197  
198 $self->isRunning(1);
199  
200 if (-f $self->file && !$self->overwrite) {
201 print("[-] ".__PACKAGE__."We will not overwrite a file by default. ".
202 "Use `overwrite' attribute to do it.\n");
203 return;
204 }
205  
206 if ($self->onRecv) {
207 $self->_startOnRecv;
208 }
209 else {
210 $self->_sStore(0);
211 $self->_sWaitFileSize;
212 $self->_startTcpdump;
213 $self->_openFile;
214 }
215  
216 return 1;
217 }
218  
219 sub _clean {
220 my $self = shift;
221 if ($self->unlinkOnStop && $self->file && -f $self->file) {
222 unlink($self->file);
223 $self->cgDebugPrint(1, "@{[$self->file]} removed");
224 }
225 if ($self->_sName && -f $self->_sName) {
226 unlink($self->_sName);
227 }
228 return 1;
229 }
230  
231 sub stop {
232 my $self = shift;
233  
234 if ($self->onRecv && $self->_pcapd) {
235 Net::Pcap::breakloop($self->_pcapd);
236 Net::Pcap::close($self->_pcapd);
237 }
238 else {
239 $self->_killTcpdump;
240 Net::Pcap::breakloop($self->_pcapd);
241 Net::Pcap::close($self->_pcapd);
242 }
243  
244 # Free the pcap filter
245 if (defined($self->_fcode)) {
246 Net::Pcap::pcap_freecode($self->_fcode);
247 $self->_fcode(undef);
248 }
249  
250 $self->isRunning(0);
251 $self->_pcapd(undef);
252  
253 $self->_clean;
254  
255 return 1;
256 }
257  
258 sub getStats {
259 my $self = shift;
260  
261 if (!defined($self->_pcapd)) {
262 print("[-] ".__PACKAGE__.": unable to get stats, no pcap descriptor ".
263 "opened.\n");
264 return;
265 }
266  
267 my %stats;
268 Net::Pcap::stats($self->_pcapd, \%stats);
269 return \%stats;
270 }
271  
272 sub isFather { ! shift->_son }
273 sub isSon { shift->_son }
274  
275 sub _sonPrintStats {
276 my $self = shift;
277  
278 my $stats = $self->getStats;
279 $self->cgDebugPrint(1, 'Frames received : '.$stats->{ps_recv});
280 $self->cgDebugPrint(1, 'Frames dropped : '.$stats->{ps_drop});
281 $self->cgDebugPrint(1, 'Frames if dropped: '.$stats->{ps_ifdrop});
282 return;
283 }
284  
285 sub _startTcpdump {
286 my $self = shift;
287  
288 my $err;
289 my $pd = Net::Pcap::open_live(
290 $self->dev,
291 $self->snaplen,
292 $self->promisc,
293 1000,
294 \$err,
295 );
296 unless ($pd) {
297 print("[-] ".__PACKAGE__.": open_live: $err\n");
298 return;
299 }
300  
301 my $net = 0;
302 my $mask = 0;
303 Net::Pcap::lookupnet($self->dev, \$net, \$mask, \$err);
304 if ($err) {
305 print("[!] ".__PACKAGE__.": lookupnet: $err\n");
306 }
307  
308 my $fcode;
309 if (Net::Pcap::compile($pd, \$fcode, $self->filter, $self->filterCodeOptimizer, $mask) < 0) {
310 print("[-] ".__PACKAGE__.": compile: ". Net::Pcap::geterr($pd). "\n");
311 return;
312 }
313 $self->_fcode($fcode); # Used to free it later on, usually on stop call.
314  
315 if (Net::Pcap::setfilter($pd, $fcode) < 0) {
316 print("[-] ".__PACKAGE__.": setfilter: ". Net::Pcap::geterr($pd). "\n");
317 return;
318 }
319  
320 my $p = Net::Pcap::dump_open($pd, $self->file);
321 unless ($p) {
322 print("[-] ".__PACKAGE__.": dump_open: ". Net::Pcap::geterr($pd). "\n");
323 return;
324 }
325 Net::Pcap::dump_flush($p);
326  
327 my $pid = fork();
328 die("[-] ".__PACKAGE__.": fork: $!\n") unless defined $pid;
329 if ($pid) { # Parent
330 $self->_son(0);
331 $self->_pid($pid);
332 $SIG{CHLD} = 'IGNORE';
333 return 1;
334 }
335 else { # Son
336 $self->_son(1);
337 $self->_pcapd($pd);
338 $SIG{HUP} = sub { $self->_sonPrintStats };
339 $self->cgDebugPrint(1, "dev: [@{[$self->dev]}]\n".
340 "file: [@{[$self->file]}]\n".
341 "filter: [@{[$self->filter]}]");
342 Net::Pcap::loop($pd, -1, \&_tcpdumpCallback, [ $p, $self ]);
343 Net::Pcap::close($pd);
344 exit(0);
345 }
346 }
347  
348 sub _tcpdumpCallback {
349 my ($data, $hdr, $pkt) = @_;
350 my $p = $data->[0];
351 my $self = $data->[1];
352  
353 Net::Pcap::dump($p, $hdr, $pkt);
354 Net::Pcap::dump_flush($p);
355  
356 my $n = $self->_sRetrieve;
357 $self->_sStore(++$n);
358 }
359  
360 sub _killTcpdump {
361 my $self = shift;
362 return if $self->isSon;
363 kill('KILL', $self->_pid);
364 $self->_pid(undef);
365 }
366  
367 sub _openFile {
368 my $self = shift;
369  
370 my $err;
371 my $pcapd = Net::Pcap::open_offline($self->file, \$err);
372 if (!defined($pcapd)) {
373 print("[-] ".__PACKAGE__.": Net::Pcap::open_offline: ".
374 "@{[$self->file]}: $err\n");
375 return;
376 }
377 $self->_pcapd($pcapd);
378  
379 return $self->getFirstLayer;
380 }
381  
382 sub _getNextAwaitingFrame {
383 my $self = shift;
384 my $last = $self->_sDataAwaiting;
385 my $new = $self->_sRetrieve;
386  
387 # Return if nothing new is awaiting
388 return if ($new <= $last);
389  
390 $self->_sDataAwaiting($self->_sDataAwaiting + 1);
391 return $self->SUPER::next;
392 }
393  
394 sub _nextTimeoutHandle {
395 my $self = shift;
396  
397 # Handle timeout
398 my $thisTime = gettimeofday();
399 if ($self->timeoutOnNext && !$self->_firstTime) {
400 $self->_firstTime($thisTime);
401 }
402  
403 if ($self->timeoutOnNext && $self->_firstTime) {
404 if (($thisTime - $self->_firstTime) > $self->timeoutOnNext) {
405 $self->timeout(1);
406 $self->_firstTime(0);
407 $self->cgDebugPrint(1, "Timeout occurred");
408 return;
409 }
410 }
411  
412 return 1;
413 }
414  
415 sub _nextTimeoutReset { shift->_firstTime(0) }
416  
417 sub timeoutReset { shift->timeout(0) }
418  
419 sub next {
420 my $self = shift;
421  
422 $self->_nextTimeoutHandle or return;
423  
424 my $frame = $self->_getNextAwaitingFrame;
425 $self->_nextTimeoutReset if $frame;
426  
427 return $frame;
428 }
429  
430 1;
431  
432 __END__
« Dump/Offline.pm ↑ Summary Dump/Online2.pm »