diag_packet_capture.php 18.3 KB
Newer Older
Ad Schellevis's avatar
Ad Schellevis committed
1
<?php
2

Ad Schellevis's avatar
Ad Schellevis committed
3
/*
4
	Copyright (C) 2014 Deciso B.V.
Ad Schellevis's avatar
Ad Schellevis committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73

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

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

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

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

function fixup_host_logic($value) {
	return str_replace(array(" ", ",", "+", "|", "!"), array("", "and ", "and ", "or ", "not "), $value);
}
function strip_host_logic($value) {
	return str_replace(array(" ", ",", "+", "|", "!"), array("", "", "", "", ""), $value);
}
function get_host_boolean($value, $host) {
	$value = str_replace(array("!", $host), array("", ""), $value);
	$andor = "";
	switch (trim($value)) {
		case "|":
			$andor = "or ";
			break;
		case ",":
		case "+":
			$andor = "and ";
			break;
	}
	return $andor;
}
function has_not($value) {
	return strpos($value, '!') !== false;
}
function fixup_not($value) {
	return str_replace("!", "not ", $value);
}
function strip_not($value) {
	return ltrim(trim($value), '!');
}

function fixup_host($value, $position) {
	$host = strip_host_logic($value);
	$not = has_not($value) ? "not " : "";
	$andor = ($position > 0) ? get_host_boolean($value, $host) : "";
	if (is_ipaddr($host))
		return "{$andor}host {$not}" . $host;
	elseif (is_subnet($host))
		return "{$andor}net {$not}" . $host;
	else
		return "";
}

if ($_POST['downloadbtn'] == gettext("Download Capture"))
	$nocsrf = true;

require_once("guiconfig.inc");
74
require_once("pfsense-utils.inc");
75
require_once("interfaces.inc");
Ad Schellevis's avatar
Ad Schellevis committed
76 77 78 79 80 81 82 83 84 85 86 87 88

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

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

$input_errors = array();

$interfaces = get_configured_interface_with_descr();
89 90 91 92 93

if (isset($config['ipsec']['enable'])) {
	$interfaces['ipsec'] = 'IPsec';
}

Ad Schellevis's avatar
Ad Schellevis committed
94
foreach (array('server', 'client') as $mode) {
95
	if (isset($config['openvpn']["openvpn-{$mode}"])) {
Ad Schellevis's avatar
Ad Schellevis committed
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
		foreach ($config['openvpn']["openvpn-{$mode}"] as $id => $setting) {
			if (!isset($setting['disable'])) {
				$interfaces['ovpn' . substr($mode, 0, 1) . $setting['vpnid']] = gettext("OpenVPN") . " ".$mode.": ".htmlspecialchars($setting['description']);
			}
		}
	}
}

if ($_POST) {
	$host = $_POST['host'];
	$selectedif = $_POST['interface'];
	$count = $_POST['count'];
	$snaplen = $_POST['snaplen'];
	$port = $_POST['port'];
	$detail = $_POST['detail'];
	$fam = $_POST['fam'];
	$proto = $_POST['proto'];

	if (!array_key_exists($selectedif, $interfaces)) {
		$input_errors[] = gettext("Invalid interface.");
	}
	if ($fam !== "" && $fam !== "ip" && $fam !== "ip6") {
		$input_errors[] = gettext("Invalid address family.");
	}
	if ($proto !== "" && !in_array(strip_not($proto), $protos)) {
		$input_errors[] = gettext("Invalid protocol.");
	}
123

Ad Schellevis's avatar
Ad Schellevis committed
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
	if ($host != "") {
		$host_string = str_replace(array(" ", "|", ","), array("", "#|", "#+"), $host);
		if (strpos($host_string, '#') === false) {
			$hosts = array($host);
		} else {
			$hosts = explode('#', $host_string);
		}
		foreach ($hosts as $h) {
			if (!is_subnet(strip_host_logic($h)) && !is_ipaddr(strip_host_logic($h))) {
				$input_errors[] = sprintf(gettext("A valid IP address or CIDR block must be specified. [%s]"), $h);
			}
		}
	}
	if ($port != "") {
		if (!is_port(strip_not($port))) {
			$input_errors[] = gettext("Invalid value specified for port.");
		}
	}
	if ($snaplen == "") {
		$snaplen = 0;
	} else {
		if (!is_numeric($snaplen) || $snaplen < 0) {
			$input_errors[] = gettext("Invalid value specified for packet length.");
		}
	}
	if ($count == "") {
		$count = 0;
	} else {
		if (!is_numeric($count) || $count < 0) {
			$input_errors[] = gettext("Invalid value specified for packet count.");
		}
	}

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

		if ($_POST['promiscuous']) {
			//if promiscuous mode is checked
			$disablepromiscuous = "";
		} else {
			//if promiscuous mode is unchecked
			$disablepromiscuous = "-p";
		}

		if ($_POST['dnsquery']) {
			//if dns lookup is checked
			$disabledns = "";
		} else {
			//if dns lookup is unchecked
			$disabledns = "-n";
		}

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

			//delete previous packet capture if it exists
			if (file_exists($fp.$fn))
				unlink ($fp.$fn);

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

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

			//kill each of the packetcapture processes
			foreach ($processes_running_array as $process) {
				$process_id_pos = strpos($process, ' ');
				$process_id = substr($process, 0, $process_id_pos);
				exec("kill $process_id");
			}

		} elseif ($_POST['downloadbtn']!= "") {
			//download file
			$fs = filesize($fp.$fn);
			header("Content-Type: application/octet-stream");
			header("Content-Disposition: attachment; filename=$fn");
			header("Content-Length: $fs");
			readfile($fp.$fn);
			exit;
		}
	}
} else {
	$do_tcpdump = false;
}

include("head.inc"); ?>

213
<body>
Ad Schellevis's avatar
Ad Schellevis committed
214 215 216 217 218

<?php
include("fbegin.inc");
?>

219
<section class="page-content-main">
220
	<div class="container-fluid">
221
		<div class="row">
222

223
			<section class="col-xs-12">
224 225
                <div class="content-box">

226
					<?php if (isset($input_errors) && count($input_errors) > 0) print_input_errors($input_errors); ?>
227

Ad Schellevis's avatar
Ad Schellevis committed
228
                    <header class="content-box-head container-fluid">
229 230
				        <h3><?=gettext("Packet capture");?></h3>
				    </header>
231

Ad Schellevis's avatar
Ad Schellevis committed
232
				    <div class="content-box-main">
233 234
				    <div class="table-responsive">
					    <form action="<?=$_SERVER['REQUEST_URI'];?>" method="post" name="iform" id="iform">
235 236 237 238 239 240
			        <table class="table table-striped">
				        <tbody>
					        <tr>
							<td><?=gettext("Interface");?></td>
									<td>
										<select name="interface" class="form-control">
241 242 243 244 245 246 247 248
										<?php foreach ($interfaces as $iface => $ifacename): ?>
											<option value="<?=$iface;?>" <?php if ($selectedif == $iface) echo "selected=\"selected\""; ?>>
											<?php echo $ifacename;?>
											</option>
										<?php endforeach; ?>
										</select>
										<p class="text-muted"><em><small><?=gettext("Select the interface on which to capture traffic.");?></small></em></p>
									</td>
249 250 251 252 253 254
					        </tr>
					        <tr>
					          <td><?=gettext("Promiscuous");?></td>
					          <td>
						          <input name="promiscuous" type="checkbox"<?php if($_POST['promiscuous']) echo " checked=\"checked\""; ?> />
						          <p class="text-muted"><em><small><?=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.");?>
255
			<br /><b><?=gettext("Note");?>: </b><?=gettext("Some network adapters do not support or work well in promiscuous mode.");?></small></em></p>
256 257 258 259 260 261
						      </td>
					        </tr>
					        <tr>
					          <td><?=gettext("Address Family");?></td>
					          <td>
						          <select name="fam" class="form-control">
262
											<option value=""><?=gettext('Any') ?></option>
Fabian Franz's avatar
Fabian Franz committed
263 264
                      <option value="ip" <?php if ($fam == "ip") echo "selected=\"selected\""; ?>><?= gettext('IPv4 Only') ?></option>
                      <option value="ip6" <?php if ($fam == "ip6") echo "selected=\"selected\""; ?>><?= gettext('IPv6 Only') ?></option>
265 266 267
										</select>
										<p class="text-muted"><em><small><?=gettext("Select the type of traffic to be captured, either Any, IPv4 only or IPv6 only.");?></small></em></p>
									</td>
268 269 270 271 272
					        </tr>
					        <tr>
					          <td><?=gettext("Protocol");?></td>
					          <td>
						          <select name="proto" class="form-control">
273
											<option value=""><?=gettext('Any') ?></option>
Fabian Franz's avatar
Fabian Franz committed
274 275 276 277 278 279 280 281 282 283 284 285 286
                      <option value="icmp" <?php if ($proto == "icmp") echo "selected=\"selected\""; ?>><?= gettext('ICMP') ?></option>
                      <option value="!icmp" <?php if ($proto == "!icmp") echo "selected=\"selected\""; ?>><?= gettext('Exclude ICMP') ?></option>
                      <option value="icmp6" <?php if ($proto == "icmp6") echo "selected=\"selected\""; ?>><?= gettext('ICMPv6') ?></option>
                      <option value="!icmp6" <?php if ($proto == "!icmp6") echo "selected=\"selected\""; ?>><?= gettext('Exclude ICMPv6') ?></option>
                      <option value="tcp" <?php if ($proto == "tcp") echo "selected=\"selected\""; ?>><?= gettext('TCP') ?></option>
                      <option value="!tcp" <?php if ($proto == "!tcp") echo "selected=\"selected\""; ?>><?= gettext('Exclude TCP') ?></option>
                      <option value="udp" <?php if ($proto == "udp") echo "selected=\"selected\""; ?>><?= gettext('UDP') ?></option>
                      <option value="!udp" <?php if ($proto == "!udp") echo "selected=\"selected\""; ?>><?= gettext('Exclude UDP') ?></option>
                      <option value="arp" <?php if ($proto == "arp") echo "selected=\"selected\""; ?>><?= gettext('ARP') ?></option>
                      <option value="!arp" <?php if ($proto == "!arp") echo "selected=\"selected\""; ?>><?= gettext('Exclude ARP') ?></option>
                      <option value="carp" <?php if ($proto == "carp") echo "selected=\"selected\""; ?>><?= gettext('CARP (VRRP)') ?></option>
                      <option value="!carp" <?php if ($proto == "!carp") echo "selected=\"selected\""; ?>><?= gettext('Exclude CARP (VRRP)') ?></option>
                      <option value="esp" <?php if ($proto == "esp") echo "selected=\"selected\""; ?>><?= gettext('ESP') ?></option>
287 288
										</select>
										<p class="text-muted"><em><small><?=gettext("Select the protocol to capture, or Any.");?></small></em></p>
289 290 291 292 293 294
					          </td>
					        </tr>
					        <tr>
					          <td><?=gettext("Host Address");?></td>
					          <td>
						          <input name="host" class="form-control host" id="host" size="20" value="<?=htmlspecialchars($host);?>" />
295 296 297 298
									  <p class="text-muted"><em><small><?=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.");?>
										<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\".");?>
										<br /><?=gettext("If you leave this field blank, all packets on the specified interface will be captured.");?>
									  </small></em></p>
299 300 301 302 303 304 305
					          </td>
					        </tr>
					        <tr>
					          <td><?=gettext("Port");?></td>
					          <td>
						          <input name="port" class="formfld unknown" id="port" size="5" value="<?=$port;?>" />

306 307
										<p class="text-muted"><em><small><?=gettext("The port can be either the source or destination port. The packet capture will look for this port in either field.");?> <?=gettext("Leave blank if you do not want to filter by port.");?></small></em></p>
									</td>
308 309 310 311 312
					        </tr>
					        <tr>
					          <td><?=gettext("Packet Length");?></td>
					          <td>
						          <input name="snaplen" class="formfld unknown" id="snaplen" size="5" value="<?=$snaplen;?>" />
313
									  <p class="text-muted"><em><small><?=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.");?></small></em></p>
314 315 316 317 318 319
					          </td>
					        </tr>
					        <tr>
					          <td><?=gettext("Count");?></td>
					          <td>
						          <input name="count" class="formfld unknown" id="count" size="5" value="<?=$count;?>" />
320
									  <p class="text-muted"><em><small><?=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.");?></small></em></p>
321 322 323 324 325 326 327
					          </td>
					        </tr>

					        <tr>
					          <td><?=gettext("Level of Detail");?></td>
					          <td>
						          <select name="detail" class="formselect" id="detail" size="1">
328 329 330 331 332 333
											<option value="normal" <?php if ($detail == "normal") echo "selected=\"selected\""; ?>><?=gettext("Normal");?></option>
											<option value="medium" <?php if ($detail == "medium") echo "selected=\"selected\""; ?>><?=gettext("Medium");?></option>
											<option value="high"   <?php if ($detail == "high")   echo "selected=\"selected\""; ?>><?=gettext("High");?></option>
											<option value="full"   <?php if ($detail == "full")   echo "selected=\"selected\""; ?>><?=gettext("Full");?></option>
										</select>
										 <p class="text-muted"><em><small><?=gettext("This is the level of detail that will be displayed after hitting 'Stop' when the packets have been captured.") .  "<br /><b>" .
Ad Schellevis's avatar
Ad Schellevis committed
334
					gettext("Note:") . "</b> " .
335
					gettext("This option does not affect the level of detail when downloading the packet capture.");?></small></em></p>
336 337 338 339 340 341 342 343 344 345 346 347 348
					          </td>
					        </tr>

					        <tr>
					          <td><?=gettext("Reverse DNS Lookup");?></td>
					          <td>
						          <input name="dnsquery" type="checkbox" <?php if($_POST['dnsquery']) echo " checked=\"checked\""; ?> />
						           <p class="text-muted"><em><small><?=gettext("This check box will cause the packet capture to perform a reverse DNS lookup associated with all IP addresses.");?>
			<br /><b><?=gettext("Note");?>: </b><?=gettext("This option can cause delays for large packet captures.");?></small></em></p>
					          </td>
					        </tr>

					       <tr>
349 350 351
									<td>&nbsp;</td>
									<td>
									<?php
352

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

356 357 358 359
									if ($processcheck != "")
										$processisrunning = true;
									else
										$processisrunning = false;
360

361 362 363 364 365 366 367 368 369 370 371 372 373
									if (($action == gettext("Stop") or $action == "") and $processisrunning != true)
										echo "<input type=\"submit\" class=\"btn\" name=\"startbtn\" value=\"" . gettext("Start") . "\" />&nbsp;";
									else {
										echo "<input type=\"submit\" class=\"btn\" name=\"stopbtn\" value=\"" . gettext("Stop") . "\" />&nbsp;";
									}
									if (file_exists($fp.$fn) and $processisrunning != true) {
										echo "<input type=\"submit\" class=\"btn\" name=\"viewbtn\" value=\"" . gettext("View Capture") . "\" />&nbsp;";
										echo "<input type=\"submit\" class=\"btn\" name=\"downloadbtn\" value=\"" . gettext("Download Capture") . "\" />";
										echo "<br />" . gettext("The packet capture file was last updated:") . " " . date("F jS, Y g:i:s a.", filemtime($fp.$fn));
									}
									?>
									</td>
								</tr>
374 375 376

				        </tbody>
				    </table>
377 378 379 380
					    </form>
				    </div>
				</div>
			</section>
381 382 383



Ad Schellevis's avatar
Ad Schellevis committed
384 385
<?php

386
$title = '';
Ad Schellevis's avatar
Ad Schellevis committed
387

388 389 390
if ($processisrunning == true) {
	$title = gettext("Packet Capture is running.");
}
Ad Schellevis's avatar
Ad Schellevis committed
391

392 393
if ($do_tcpdump) {
	$matches = array();
Ad Schellevis's avatar
Ad Schellevis committed
394

395 396
	if (in_array($fam, $fams))
		$matches[] = $fam;
Ad Schellevis's avatar
Ad Schellevis committed
397

398 399 400
	if (in_array($proto, $protos)) {
		$matches[] = fixup_not($proto);
	}
Ad Schellevis's avatar
Ad Schellevis committed
401

402 403
	if ($port != "")
		$matches[] = "port ".fixup_not($port);
Ad Schellevis's avatar
Ad Schellevis committed
404

405 406 407 408 409 410 411 412 413 414 415
	if ($host != "") {
		$hostmatch = "";
		$hostcount = 0;
		foreach ($hosts as $h) {
			$h = fixup_host($h, $hostcount++);
			if (!empty($h))
				$hostmatch .= " " . $h;
		}
		if (!empty($hostmatch))
			$matches[] = "({$hostmatch})";
	}
Ad Schellevis's avatar
Ad Schellevis committed
416

417 418 419 420 421 422
	if ($count != "0" ) {
		$searchcount = "-c " . $count;
	} else {
		$searchcount = "";
	}

423
	$selectedif = get_real_interface($selectedif);
424 425 426 427

	if ($action == gettext("Start")) {
		$matchstr = implode($matches, " and ");
		$title = gettext("Packet Capture is running.");
428

429 430 431 432 433 434 435 436 437 438 439 440
		$cmd = "/usr/sbin/tcpdump -i {$selectedif} {$disablepromiscuous} {$searchcount} -s {$snaplen} -w {$fp}{$fn} " . escapeshellarg($matchstr);
		// Debug
		//echo $cmd;
		mwexec_bg ($cmd);
	} else {
		$show_data = true;
		//action = stop
		$title = gettext("Packet Capture stopped.") . " " . gettext("Packets Captured:");
	}
}

if (!empty($title)): ?>
441

442
			<section class="col-xs-12">
443
                <div class="content-box">
Ad Schellevis's avatar
Ad Schellevis committed
444
	                <header class="content-box-head container-fluid">
445 446
				        <h3><?=$title; ?></h3>
				    </header>
447
				    <?php if (!empty($show_data)): ?>
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
				    <div class="content-box-main col-xs-12">

						<script type="text/javascript">
						//<![CDATA[
						window.onload=function(){
							document.getElementById("packetsCaptured").wrap='off';
						}
						//]]>
						</script>
						<pre id="packetsCaptured" style="width:98%" readonly="readonly"><?php
						$detail_args = "";
						switch ($detail) {
						case "full":
							$detail_args = "-vv -e";
							break;
						case "high":
							$detail_args = "-vv";
							break;
						case "medium":
							$detail_args = "-v";
							break;
						case "normal":
						default:
							$detail_args = "-q";
							break;
						}
						system("/usr/sbin/tcpdump {$disabledns} {$detail_args} -r {$fp}{$fn}");
475

476 477 478 479
		?>
						</pre>


480
			</div>
481
			<?php endif; ?>
482
                </div>
483 484
			</section>

485
<?php endif; ?>
486
		</div>
487

488 489
	</div>
</section>
Ad Schellevis's avatar
Ad Schellevis committed
490 491 492


<?php
493
include("foot.inc");
Ad Schellevis's avatar
Ad Schellevis committed
494
?>