Project

General

Profile

Download (17.4 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
	diag_packet_capture.php
4
	Copyright (C) 2013-2015 Electric Sheep Fencing, LP
5
	All rights reserved
6

    
7
	Redistribution and use in source and binary forms, with or without
8
	modification, are permitted provided that the following conditions are met:
9

    
10
	1. Redistributions of source code must retain the above copyright notice,
11
	this list of conditions and the following disclaimer.
12

    
13
	2. Redistributions in binary form must reproduce the above copyright
14
	notice, this list of conditions and the following disclaimer in the
15
	documentation and/or other materials provided with the distribution.
16

    
17
	THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
18
	INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
19
	AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
20
	AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
21
	OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22
	SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23
	INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24
	CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26
	POSSIBILITY OF SUCH DAMAGE.
27
*/
28

    
29
/*
30
	pfSense_BUILDER_BINARIES:	/bin/ps	/usr/bin/grep	/usr/sbin/tcpdump
31
	pfSense_MODULE:	routing
32
*/
33

    
34
##|+PRIV
35
##|*IDENT=page-diagnostics-packetcapture
36
##|*NAME=Diagnostics: Packet Capture page
37
##|*DESCR=Allow access to the 'Diagnostics: Packet Capture' page.
38
##|*MATCH=diag_packet_capture.php*
39
##|-PRIV
40

    
41
$allowautocomplete = true;
42

    
43
function fixup_host_logic($value) {
44
	return str_replace(array(" ", ",", "+", "|", "!"), array("", "and ", "and ", "or ", "not "), $value);
45
}
46
function strip_host_logic($value) {
47
	return str_replace(array(" ", ",", "+", "|", "!"), array("", "", "", "", ""), $value);
48
}
49
function get_host_boolean($value, $host) {
50
	$value = str_replace(array("!", $host), array("", ""), $value);
51
	$andor = "";
52
	switch (trim($value)) {
53
		case "|":
54
			$andor = "or ";
55
			break;
56
		case ",":
57
		case "+":
58
			$andor = "and ";
59
			break;
60
	}
61
	return $andor;
62
}
63
function has_not($value) {
64
	return strpos($value, '!') !== false;
65
}
66
function fixup_not($value) {
67
	return str_replace("!", "not ", $value);
68
}
69
function strip_not($value) {
70
	return ltrim(trim($value), '!');
71
}
72

    
73
function fixup_host($value, $position) {
74
	$host = strip_host_logic($value);
75
	$not = has_not($value) ? "not " : "";
76
	$andor = ($position > 0) ? get_host_boolean($value, $host) : "";
77
	if (is_ipaddr($host)) {
78
		return "{$andor}host {$not}" . $host;
79
	} elseif (is_subnet($host)) {
80
		return "{$andor}net {$not}" . $host;
81
	} else {
82
		return "";
83
	}
84
}
85

    
86
if ($_POST['downloadbtn'] == gettext("Download Capture")) {
87
	$nocsrf = true;
88
}
89

    
90
$pgtitle = array(gettext("Diagnostics"), gettext("Packet Capture"));
91
require_once("guiconfig.inc");
92
require_once("pfsense-utils.inc");
93

    
94
$fp = "/root/";
95
$fn = "packetcapture.cap";
96
$snaplen = 0;//default packet length
97
$count = 100;//default number of packets to capture
98

    
99
$fams = array('ip', 'ip6');
100
$protos = array('icmp', 'icmp6', 'tcp', 'udp', 'arp', 'carp', 'esp',
101
		'!icmp', '!icmp6', '!tcp', '!udp', '!arp', '!carp', '!esp');
102

    
103
$input_errors = array();
104

    
105
$interfaces = get_configured_interface_with_descr();
106
if (isset($config['ipsec']['enable'])) {
107
	$interfaces['ipsec'] = "IPsec";
108
}
109
foreach (array('server', 'client') as $mode) {
110
	if (is_array($config['openvpn']["openvpn-{$mode}"])) {
111
		foreach ($config['openvpn']["openvpn-{$mode}"] as $id => $setting) {
112
			if (!isset($setting['disable'])) {
113
				$interfaces['ovpn' . substr($mode, 0, 1) . $setting['vpnid']] = gettext("OpenVPN") . " ".$mode.": ".htmlspecialchars($setting['description']);
114
			}
115
		}
116
	}
117
}
118

    
119
if ($_POST) {
120
	$host = $_POST['host'];
121
	$selectedif = $_POST['interface'];
122
	$count = $_POST['count'];
123
	$snaplen = $_POST['snaplen'];
124
	$port = $_POST['port'];
125
	$detail = $_POST['detail'];
126
	$fam = $_POST['fam'];
127
	$proto = $_POST['proto'];
128

    
129
	if (!array_key_exists($selectedif, $interfaces)) {
130
		$input_errors[] = gettext("Invalid interface.");
131
	}
132
	if ($fam !== "" && $fam !== "ip" && $fam !== "ip6") {
133
		$input_errors[] = gettext("Invalid address family.");
134
	}
135
	if ($proto !== "" && !in_array(strip_not($proto), $protos)) {
136
		$input_errors[] = gettext("Invalid protocol.");
137
	}
138

    
139
	if ($host != "") {
140
		$host_string = str_replace(array(" ", "|", ","), array("", "#|", "#+"), $host);
141
		if (strpos($host_string, '#') === false) {
142
			$hosts = array($host);
143
		} else {
144
			$hosts = explode('#', $host_string);
145
		}
146
		foreach ($hosts as $h) {
147
			if (!is_subnet(strip_host_logic($h)) && !is_ipaddr(strip_host_logic($h))) {
148
				$input_errors[] = sprintf(gettext("A valid IP address or CIDR block must be specified. [%s]"), $h);
149
			}
150
		}
151
	}
152
	if ($port != "") {
153
		if (!is_port(strip_not($port))) {
154
			$input_errors[] = gettext("Invalid value specified for port.");
155
		}
156
	}
157
	if ($snaplen == "") {
158
		$snaplen = 0;
159
	} else {
160
		if (!is_numeric($snaplen) || $snaplen < 0) {
161
			$input_errors[] = gettext("Invalid value specified for packet length.");
162
		}
163
	}
164
	if ($count == "") {
165
		$count = 0;
166
	} else {
167
		if (!is_numeric($count) || $count < 0) {
168
			$input_errors[] = gettext("Invalid value specified for packet count.");
169
		}
170
	}
171

    
172
	if (!count($input_errors)) {
173
		$do_tcpdump = true;
174

    
175
		conf_mount_rw();
176

    
177
		if ($_POST['promiscuous']) {
178
			//if promiscuous mode is checked
179
			$disablepromiscuous = "";
180
		} else {
181
			//if promiscuous mode is unchecked
182
			$disablepromiscuous = "-p";
183
		}
184

    
185
		if ($_POST['dnsquery']) {
186
			//if dns lookup is checked
187
			$disabledns = "";
188
		} else {
189
			//if dns lookup is unchecked
190
			$disabledns = "-n";
191
		}
192

    
193
		if ($_POST['startbtn'] != "" ) {
194
			$action = gettext("Start");
195

    
196
			//delete previous packet capture if it exists
197
			if (file_exists($fp.$fn)) {
198
				unlink ($fp.$fn);
199
			}
200

    
201
		} elseif ($_POST['stopbtn']!= "") {
202
			$action = gettext("Stop");
203
			$processes_running = trim(shell_exec("/bin/ps axw -O pid= | /usr/bin/grep tcpdump | /usr/bin/grep {$fn} | /usr/bin/egrep -v '(pflog|grep)'"));
204

    
205
			//explode processes into an array, (delimiter is new line)
206
			$processes_running_array = explode("\n", $processes_running);
207

    
208
			//kill each of the packetcapture processes
209
			foreach ($processes_running_array as $process) {
210
				$process_id_pos = strpos($process, ' ');
211
				$process_id = substr($process, 0, $process_id_pos);
212
				exec("kill $process_id");
213
			}
214

    
215
		} elseif ($_POST['downloadbtn']!= "") {
216
			//download file
217
			$fs = filesize($fp.$fn);
218
			header("Content-Type: application/octet-stream");
219
			header("Content-Disposition: attachment; filename=$fn");
220
			header("Content-Length: $fs");
221
			readfile($fp.$fn);
222
			exit;
223
		}
224
	}
225
} else {
226
	$do_tcpdump = false;
227
}
228

    
229
include("head.inc"); ?>
230

    
231
<body link="#000000" vlink="#0000CC" alink="#0000CC">
232

    
233
<?php
234
include("fbegin.inc");
235
?>
236

    
237
<?php if ($input_errors) print_input_errors($input_errors); ?>
238

    
239
<table width="100%" border="0" cellpadding="0" cellspacing="0" summary="diag packet capture">
240
	<tr><td>
241
	<form action="diag_packet_capture.php" method="post" name="iform" id="iform">
242
	<table width="100%" border="0" cellpadding="6" cellspacing="0" summary="table">
243
		<tr>
244
			<td colspan="3" valign="top" class="listtopic"><?=gettext("Packet capture");?></td>
245
		</tr>
246
		<tr>
247
			<td width="17%" valign="top" class="vncellreq"><?=gettext("Interface");?></td>
248
			<td width="32%" class="vtable">
249
			<select name="interface">
250
			<?php foreach ($interfaces as $iface => $ifacename): ?>
251
				<option value="<?=$iface;?>" <?php if ($selectedif == $iface) echo "selected=\"selected\""; ?>>
252
				<?php echo $ifacename;?>
253
				</option>
254
			<?php endforeach; ?>
255
			</select>
256
			<br /><?=gettext("Select the interface on which to capture traffic.");?>
257
			</td>
258
		</tr>
259
		<tr>
260
			<td width="17%" valign="top" class="vncellreq"><?=gettext("Promiscuous");?></td>
261
			<td width="51%" class="vtable">
262
			<input name="promiscuous" type="checkbox"<?php if ($_POST['promiscuous']) echo " checked=\"checked\""; ?> />
263
			<br /><?=gettext("If checked, the");?> <a target="_blank" href="http://www.freebsd.org/cgi/man.cgi?query=tcpdump&amp;apropos=0&amp;sektion=0&amp;manpath=FreeBSD+8.3-stable&amp;arch=default&amp;format=html"><?= gettext("packet capture")?></a> <?= gettext("will be performed using promiscuous mode.");?>
264
			<br /><b><?=gettext("Note");?>: </b><?=gettext("Some network adapters do not support or work well in promiscuous mode.");?>
265
			</td>
266
		</tr>
267
		<tr>
268
			<td width="17%" valign="top" class="vncellreq"><?=gettext("Address Family");?></td>
269
			<td colspan="2" width="83%" class="vtable">
270
			<select name="fam">
271
				<option value="">Any</option>
272
				<option value="ip" <?php if ($fam == "ip") echo "selected=\"selected\""; ?>>IPv4 Only</option>
273
				<option value="ip6" <?php if ($fam == "ip6") echo "selected=\"selected\""; ?>>IPv6 Only</option>
274
			</select>
275
			<br /><?=gettext("Select the type of traffic to be captured, either Any, IPv4 only or IPv6 only.");?>
276
			</td>
277
		</tr>
278
		<tr>
279
			<td width="17%" valign="top" class="vncellreq"><?=gettext("Protocol");?></td>
280
			<td colspan="2" width="83%" class="vtable">
281
			<select name="proto">
282
				<option value="">Any</option>
283
				<option value="icmp" <?php if ($proto == "icmp") echo "selected=\"selected\""; ?>>ICMP</option>
284
				<option value="!icmp" <?php if ($proto == "!icmp") echo "selected=\"selected\""; ?>>Exclude ICMP</option>
285
				<option value="icmp6" <?php if ($proto == "icmp6") echo "selected=\"selected\""; ?>>ICMPv6</option>
286
				<option value="!icmp6" <?php if ($proto == "!icmp6") echo "selected=\"selected\""; ?>>Exclude ICMPv6</option>
287
				<option value="tcp" <?php if ($proto == "tcp") echo "selected=\"selected\""; ?>>TCP</option>
288
				<option value="!tcp" <?php if ($proto == "!tcp") echo "selected=\"selected\""; ?>>Exclude TCP</option>
289
				<option value="udp" <?php if ($proto == "udp") echo "selected=\"selected\""; ?>>UDP</option>
290
				<option value="!udp" <?php if ($proto == "!udp") echo "selected=\"selected\""; ?>>Exclude UDP</option>
291
				<option value="arp" <?php if ($proto == "arp") echo "selected=\"selected\""; ?>>ARP</option>
292
				<option value="!arp" <?php if ($proto == "!arp") echo "selected=\"selected\""; ?>>Exclude ARP</option>
293
				<option value="carp" <?php if ($proto == "carp") echo "selected=\"selected\""; ?>>CARP (VRRP)</option>
294
				<option value="!carp" <?php if ($proto == "!carp") echo "selected=\"selected\""; ?>>Exclude CARP (VRRP)</option>
295
				<option value="esp" <?php if ($proto == "esp") echo "selected=\"selected\""; ?>>ESP</option>
296
			</select>
297
			<br /><?=gettext("Select the protocol to capture, or Any.");?>
298
			</td>
299
		</tr>
300
		<tr>
301
			<td width="17%" valign="top" class="vncellreq"><?=gettext("Host Address");?></td>
302
			<td colspan="2" width="83%" class="vtable">
303
			<input name="host" class="formfld host" id="host" size="20" value="<?=htmlspecialchars($host);?>" />
304
			<br /><?=gettext("This value is either the Source or Destination IP address or subnet in CIDR notation. The packet capture will look for this address in either field.");?>
305
			<br /><?=gettext("Matching can be negated by preceding the value with \"!\". Multiple IP addresses or CIDR subnets may be specified. Comma (\",\") separated values perform a boolean \"and\". Separating with a pipe (\"|\") performs a boolean \"or\".");?>
306
			<br /><?=gettext("If you leave this field blank, all packets on the specified interface will be captured.");?>
307
			</td>
308
		</tr>
309
		<tr>
310
			<td width="17%" valign="top" class="vncellreq"><?=gettext("Port");?></td>
311
			<td colspan="2" width="83%" class="vtable">
312
			<input name="port" class="formfld unknown" id="port" size="5" value="<?=$port;?>" />
313
			<br /><?=gettext("The port can be either the source or destination port. The packet capture will look for this port in either field.");?>
314
			<br /><?=gettext("Leave blank if you do not want to filter by port.");?>
315
			</td>
316
		</tr>
317
		<tr>
318
			<td width="17%" valign="top" class="vncellreq"><?=gettext("Packet Length");?></td>
319
			<td colspan="2" width="83%" class="vtable">
320
			<input name="snaplen" class="formfld unknown" id="snaplen" size="5" value="<?=$snaplen;?>" />
321
			<br /><?=gettext("The Packet length is the number of bytes of each packet that will be captured. Default value is 0, which will capture the entire frame regardless of its size.");?>
322
			</td>
323
		</tr>
324
		<tr>
325
			<td width="17%" valign="top" class="vncellreq"><?=gettext("Count");?></td>
326
			<td colspan="2" width="83%" class="vtable">
327
			<input name="count" class="formfld unknown" id="count" size="5" value="<?=$count;?>" />
328
			<br /><?=gettext("This is the number of packets the packet capture will grab. Default value is 100.") . "<br />" . gettext("Enter 0 (zero) for no count limit.");?>
329
			</td>
330
		</tr>
331
		<tr>
332
			<td width="17%" valign="top" class="vncellreq"><?=gettext("Level of Detail");?></td>
333
			<td colspan="2" width="83%" class="vtable">
334
			<select name="detail" class="formselect" id="detail" size="1">
335
				<option value="normal" <?php if ($detail == "normal") echo "selected=\"selected\""; ?>><?=gettext("Normal");?></option>
336
				<option value="medium" <?php if ($detail == "medium") echo "selected=\"selected\""; ?>><?=gettext("Medium");?></option>
337
				<option value="high"   <?php if ($detail == "high")   echo "selected=\"selected\""; ?>><?=gettext("High");?></option>
338
				<option value="full"   <?php if ($detail == "full")   echo "selected=\"selected\""; ?>><?=gettext("Full");?></option>
339
			</select>
340
			<br /><?=gettext("This is the level of detail that will be displayed after hitting 'Stop' when the packets have been captured.") .  "<br /><b>" .
341
					gettext("Note:") . "</b> " .
342
					gettext("This option does not affect the level of detail when downloading the packet capture.");?>
343
			</td>
344
		</tr>
345
		<tr>
346
			<td width="17%" valign="top" class="vncellreq"><?=gettext("Reverse DNS Lookup");?></td>
347
			<td colspan="2" width="83%" class="vtable">
348
			<input name="dnsquery" type="checkbox" <?php if ($_POST['dnsquery']) echo " checked=\"checked\""; ?> />
349
			<br /><?=gettext("This check box will cause the packet capture to perform a reverse DNS lookup associated with all IP addresses.");?>
350
			<br /><b><?=gettext("Note");?>: </b><?=gettext("This option can cause delays for large packet captures.");?>
351
			</td>
352
		</tr>
353
		<tr>
354
			<td width="17%" valign="top">&nbsp;</td>
355
			<td colspan="2" width="83%">
356
<?php
357

    
358
			/* check to see if packet capture tcpdump is already running */
359
			$processcheck = (trim(shell_exec("/bin/ps axw -O pid= | /usr/bin/grep tcpdump | /usr/bin/grep {$fn} | /usr/bin/egrep -v '(pflog|grep)'")));
360

    
361
			if ($processcheck != "") {
362
				$processisrunning = true;
363
			} else {
364
				$processisrunning = false;
365
			}
366

    
367
			if (($action == gettext("Stop") or $action == "") and $processisrunning != true) {
368
				echo "<input type=\"submit\" name=\"startbtn\" value=\"" . gettext("Start") . "\" />&nbsp;";
369
			} else {
370
				echo "<input type=\"submit\" name=\"stopbtn\" value=\"" . gettext("Stop") . "\" />&nbsp;";
371
			}
372
			if (file_exists($fp.$fn) and $processisrunning != true) {
373
				echo "<input type=\"submit\" name=\"viewbtn\" value=\"" . gettext("View Capture") . "\" />&nbsp;";
374
				echo "<input type=\"submit\" name=\"downloadbtn\" value=\"" . gettext("Download Capture") . "\" />";
375
				echo "<br />" . gettext("The packet capture file was last updated:") . " " . date("F jS, Y g:i:s a.", filemtime($fp.$fn));
376
			}
377
?>
378
			</td>
379
		</tr>
380
	</table>
381
	</form>
382
	<table width="100%" border="0" cellpadding="6" cellspacing="0" summary="results">
383
		<tr>
384
		<td valign="top" colspan="2">
385
<?php
386
		echo "<font face=\"terminal\" size=\"2\">";
387
		if ($processisrunning == true) {
388
			echo("<strong>" . gettext("Packet Capture is running.") . "</strong><br />");
389
		}
390

    
391
		if ($do_tcpdump) {
392
			$matches = array();
393

    
394
			if (in_array($fam, $fams)) {
395
				$matches[] = $fam;
396
			}
397

    
398
			if (in_array($proto, $protos)) {
399
				$matches[] = fixup_not($proto);
400
			}
401

    
402
			if ($port != "") {
403
				$matches[] = "port ".fixup_not($port);
404
			}
405

    
406
			if ($host != "") {
407
				$hostmatch = "";
408
				$hostcount = 0;
409
				foreach ($hosts as $h) {
410
					$h = fixup_host($h, $hostcount++);
411
					if (!empty($h)) {
412
						$hostmatch .= " " . $h;
413
					}
414
				}
415
				if (!empty($hostmatch)) {
416
					$matches[] = "({$hostmatch})";
417
				}
418
			}
419

    
420
			if ($count != "0" ) {
421
				$searchcount = "-c " . $count;
422
			} else {
423
				$searchcount = "";
424
			}
425

    
426
			$selectedif = convert_friendly_interface_to_real_interface_name($selectedif);
427

    
428
			if ($action == gettext("Start")) {
429
				$matchstr = implode($matches, " and ");
430
				echo("<strong>" . gettext("Packet Capture is running.") . "</strong><br />");
431
				$cmd = "/usr/sbin/tcpdump -i {$selectedif} {$disablepromiscuous} {$searchcount} -s {$snaplen} -w {$fp}{$fn} " . escapeshellarg($matchstr);
432
				// Debug
433
				//echo $cmd;
434
				mwexec_bg ($cmd);
435
			} else {
436
				//action = stop
437
				echo("<strong>" . gettext("Packet Capture stopped.") . "<br /><br />" . gettext("Packets Captured:") . "</strong><br />");
438
?>
439
				<script type="text/javascript">
440
				//<![CDATA[
441
				window.onload=function() {
442
					document.getElementById("packetsCaptured").wrap='off';
443
				}
444
				//]]>
445
				</script>
446
				<textarea id="packetsCaptured" style="width:98%" name="code" rows="15" cols="66" readonly="readonly">
447
<?php
448
				$detail_args = "";
449
				switch ($detail) {
450
					case "full":
451
						$detail_args = "-vv -e";
452
						break;
453
					case "high":
454
						$detail_args = "-vv";
455
						break;
456
					case "medium":
457
						$detail_args = "-v";
458
						break;
459
					case "normal":
460
					default:
461
						$detail_args = "-q";
462
						break;
463
				}
464
				system("/usr/sbin/tcpdump {$disabledns} {$detail_args} -r {$fp}{$fn}");
465

    
466
				conf_mount_ro();
467
?>
468
				</textarea>
469
<?php
470
			}
471
		}
472
?>
473
		&nbsp;</font>
474
		</td>
475
		</tr>
476
	</table>
477
	</td></tr>
478
</table>
479

    
480
<?php
481
include("fend.inc");
482
?>
483
</body>
484
</html>
(39-39/256)