Project

General

Profile

Download (47.4 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/*
3
 * syslog.inc
4
 *
5
 * part of pfSense (https://www.pfsense.org)
6
 * Copyright (c) 2004-2013 BSD Perimeter
7
 * Copyright (c) 2013-2016 Electric Sheep Fencing
8
 * Copyright (c) 2014-2020 Rubicon Communications, LLC (Netgate)
9
 * All rights reserved.
10
 *
11
 * originally part of m0n0wall (http://m0n0.ch/wall)
12
 * Copyright (c) 2003-2004 Manuel Kasper <mk@neon1.net>.
13
 * All rights reserved.
14
 *
15
 * Licensed under the Apache License, Version 2.0 (the "License");
16
 * you may not use this file except in compliance with the License.
17
 * You may obtain a copy of the License at
18
 *
19
 * http://www.apache.org/licenses/LICENSE-2.0
20
 *
21
 * Unless required by applicable law or agreed to in writing, software
22
 * distributed under the License is distributed on an "AS IS" BASIS,
23
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
24
 * See the License for the specific language governing permissions and
25
 * limitations under the License.
26
 */
27

    
28
require_once('config.inc');
29

    
30
global $buffer_rules_rdr, $buffer_rules_normal;
31
$buffer_rules_rdr = array();
32
$buffer_rules_normal = array();
33

    
34
global $syslog_formats;
35
$syslog_formats = array(
36
	'rfc3164' => gettext('BSD (RFC 3164, default)'),
37
	'rfc5424' => gettext('syslog (RFC 5424, with RFC 3339 microsecond-precision timestamps)'),
38
);
39

    
40
function system_syslogd_fixup_server($server) {
41
	/* If it's an IPv6 IP alone, encase it in brackets */
42
	if (is_ipaddrv6($server)) {
43
		return "[$server]";
44
	} else {
45
		return $server;
46
	}
47
}
48

    
49
function system_syslogd_get_remote_servers($syslogcfg, $facility = "*.*") {
50
	// Rather than repeatedly use the same code, use this function to build a list of remote servers.
51
	$facility .= " ".
52
	$remote_servers = "";
53
	$pad_to  = max(strlen($facility), 56);
54
	$padding = ceil(($pad_to - strlen($facility))/8)+1;
55
	if (isset($syslogcfg['enable'])) {
56
		if ($syslogcfg['remoteserver']) {
57
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver']) . "\n";
58
		}
59
		if ($syslogcfg['remoteserver2']) {
60
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver2']) . "\n";
61
		}
62
		if ($syslogcfg['remoteserver3']) {
63
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server($syslogcfg['remoteserver3']) . "\n";
64
		}
65
	}
66
	return $remote_servers;
67
}
68

    
69
function system_syslogd_get_all_logfilenames($add_extension = false) {
70
	global $config, $g, $system_log_files;
71

    
72
	if ($add_extension) {
73
		$all_syslog_files = array();
74
		foreach ($system_log_files as $syslogfile) {
75
			$all_syslog_files[] = "{$syslogfile}.log";
76
		}
77
	} else {
78
		$all_syslog_files = $system_log_files;
79
	}
80

    
81
	if ($config['installedpackages']['package']) {
82
		foreach ($config['installedpackages']['package'] as $package) {
83
			if (isset($package['logging']['logfilename'])) {
84
				$all_syslog_files[] = $package['logging']['logfilename'];
85
			}
86
		}
87
	}
88

    
89
	return $all_syslog_files;
90
}
91

    
92
/* For a given log filename prefix, return a list with the filename and
93
 * rotated copies sorted in a way that utilities such as cat/bzcat/bzgrep will
94
 * see all log entries in chronological order (e.g. name.log.2 name.log.1 name.log)
95
 */
96
function sort_related_log_files($logfile = "/var/log/system.log", $string = true, $escape = false) {
97
	$related_files = glob("{$logfile}*");
98
	usort($related_files, "rsort_log_filename");
99

    
100
	if ($escape) {
101
		$related_files = array_map("escapeshellarg", $related_files);
102
	}
103

    
104
	if ($string) {
105
		$related_files = implode(" ", $related_files);
106
	}
107

    
108
	return $related_files;
109
}
110

    
111
function rsort_log_filename($a, $b) {
112
	list($abasename, $anumber, $aext) = explode('.', $a);
113
	list($bbasename, $bnumber, $bext) = explode('.', $b);
114
	return ($anumber > $bnumber) ? -1 : 1;
115
}
116

    
117
function clear_log_file($logfile = "/var/log/system.log", $restart_syslogd = true, $remove_rotated = true) {
118
	global $config, $g;
119

    
120
	if ($restart_syslogd) {
121
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
122
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
123
		}
124
	}
125
	exec("/usr/bin/truncate -s 0 " . escapeshellarg($logfile));
126
	if ($remove_rotated) {
127
		unlink_if_exists("{$logfile}.*");
128
	}
129
	if ($restart_syslogd) {
130
		system_syslogd_start();
131
	}
132
	// Bug #6915
133
	if ($logfile == "/var/log/resolver.log") {
134
		services_unbound_configure(true);
135
	}
136
}
137

    
138
function clear_all_log_files($restart = false) {
139
	global $g, $system_log_files, $system_log_non_syslog_files;
140
	if ($restart) {
141
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
142
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
143
		}
144
	}
145

    
146
	/* Combine list of syslog and non-syslog log files */
147
	foreach (array_merge(system_syslogd_get_all_logfilenames(true), $system_log_non_syslog_files) as $lfile) {
148
		clear_log_file("{$g['varlog_path']}/{$lfile}", false);
149
	}
150

    
151
	if ($restart) {
152
		system_syslogd_start();
153
		killbyname("dhcpd");
154
		if (!function_exists('services_dhcpd_configure')) {
155
			require_once('services.inc');
156
		}
157
		services_dhcpd_configure();
158
		// Bug #6915
159
		services_unbound_configure(false);
160
	}
161
	return;
162
}
163

    
164
function system_syslogd_start($sighup = false) {
165
	global $config, $g;
166
	if (isset($config['system']['developerspew'])) {
167
		$mt = microtime();
168
		echo "system_syslogd_start() being called $mt\n";
169
	}
170

    
171
	mwexec("/etc/rc.d/hostid start");
172

    
173
	$syslogcfg = $config['syslog'];
174

    
175
	if (platform_booting()) {
176
		echo gettext("Starting syslog...");
177
	}
178

    
179
	$mainsyslogconf = <<<EOD
180
# Automatically generated, do not edit!
181
# Place configuration files in {$g['varetc_path']}/syslog.d
182
!*\n
183
include						{$g['varetc_path']}/syslog.d
184
# /* Manually added files with non-conflicting names will not be automatically removed */
185

    
186
EOD;
187

    
188
	if (!@file_put_contents("{$g['etc_path']}/syslog.conf", $mainsyslogconf)) {
189
		printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
190
		unset($syslogconf);
191
		return 1;
192
	}
193
	safe_mkdir("{$g['varetc_path']}/syslog.d");
194

    
195
	$syslogd_extra = "";
196
	if (isset($syslogcfg)) {
197
		$separatelogfacilities = array('ntp', 'ntpd', 'ntpdate', 'charon', 'ipsec_starter', 'openvpn', 'poes', 'l2tps', 'hostapd', 'dnsmasq', 'named', 'filterdns', 'unbound', 'dhcpd', 'dhcrelay', 'dhclient', 'dhcp6c', 'dpinger', 'radvd', 'routed', 'zebra', 'ospfd', 'ospf6d', 'bgpd', 'miniupnpd', 'igmpproxy', 'filterlog');
198
		$syslogconf = "# Automatically generated, do not edit!\n";
199

    
200
		if ($config['installedpackages']['package']) {
201
			foreach ($config['installedpackages']['package'] as $package) {
202
				if (isset($package['logging']['facilityname']) && isset($package['logging']['logfilename'])) {
203
					array_push($separatelogfacilities, $package['logging']['facilityname']);
204
					if (!is_file($g['varlog_path'].'/'.$package['logging']['logfilename'])) {
205
						mwexec("/usr/bin/touch {$g['varlog_path']}/{$package['logging']['logfilename']}");
206
					}
207
					$pkgsyslogconf = "# Automatically generated for package {$package['name']}. Do not edit.\n";
208
					$pkgsyslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$g['varlog_path']}/{$package['logging']['logfilename']}\n";
209
					@file_put_contents("{$g['varetc_path']}/syslog.d/" . basename($package['logging']['logfilename']) . ".conf", $pkgsyslogconf);
210
				}
211
			}
212
		}
213
		$facilitylist = implode(',', array_unique($separatelogfacilities));
214

    
215
		$syslogconf .= "!*\n";
216
		if (!isset($syslogcfg['disablelocallogging'])) {
217
			$syslogconf .= "auth.*;authpriv.* 						{$g['varlog_path']}/auth.log\n";
218
		}
219
		if (isset($syslogcfg['auth'])) {
220
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "auth.*;authpriv.*");
221
		}
222

    
223
		$syslogconf .= "!radvd,routed,zebra,ospfd,ospf6d,bgpd,miniupnpd,igmpproxy\n";
224
		if (!isset($syslogcfg['disablelocallogging'])) {
225
			$syslogconf .= "*.*								{$g['varlog_path']}/routing.log\n";
226
		}
227
		if (isset($syslogcfg['routing'])) {
228
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
229
		}
230

    
231
		$syslogconf .= "!ntp,ntpd,ntpdate\n";
232
		if (!isset($syslogcfg['disablelocallogging'])) {
233
			$syslogconf .= "*.*								{$g['varlog_path']}/ntpd.log\n";
234
		}
235
		if (isset($syslogcfg['ntpd'])) {
236
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
237
		}
238

    
239
		$syslogconf .= "!ppp\n";
240
		if (!isset($syslogcfg['disablelocallogging'])) {
241
			$syslogconf .= "*.*								{$g['varlog_path']}/ppp.log\n";
242
		}
243
		if (isset($syslogcfg['ppp'])) {
244
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
245
		}
246

    
247
		$syslogconf .= "!poes\n";
248
		if (!isset($syslogcfg['disablelocallogging'])) {
249
			$syslogconf .= "*.*								{$g['varlog_path']}/poes.log\n";
250
		}
251
		if (isset($syslogcfg['vpn'])) {
252
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
253
		}
254

    
255
		$syslogconf .= "!l2tps\n";
256
		if (!isset($syslogcfg['disablelocallogging'])) {
257
			$syslogconf .= "*.*								{$g['varlog_path']}/l2tps.log\n";
258
		}
259
		if (isset($syslogcfg['vpn'])) {
260
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
261
		}
262

    
263
		$syslogconf .= "!charon,ipsec_starter\n";
264
		if (!isset($syslogcfg['disablelocallogging'])) {
265
			$syslogconf .= "*.*								{$g['varlog_path']}/ipsec.log\n";
266
		}
267
		if (isset($syslogcfg['vpn'])) {
268
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
269
		}
270

    
271
		$syslogconf .= "!openvpn\n";
272
		if (!isset($syslogcfg['disablelocallogging'])) {
273
			$syslogconf .= "*.*								{$g['varlog_path']}/openvpn.log\n";
274
		}
275
		if (isset($syslogcfg['vpn'])) {
276
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
277
		}
278

    
279
		$syslogconf .= "!dpinger\n";
280
		if (!isset($syslogcfg['disablelocallogging'])) {
281
			$syslogconf .= "*.*								{$g['varlog_path']}/gateways.log\n";
282
		}
283
		if (isset($syslogcfg['dpinger'])) {
284
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
285
		}
286

    
287
		$syslogconf .= "!dnsmasq,named,filterdns,unbound\n";
288
		if (!isset($syslogcfg['disablelocallogging'])) {
289
			$syslogconf .= "*.*								{$g['varlog_path']}/resolver.log\n";
290
		}
291
		if (isset($syslogcfg['resolver'])) {
292
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
293
		}
294

    
295
		$syslogconf .= "!dhcpd,dhcrelay,dhclient,dhcp6c,dhcpleases,dhcpleases6\n";
296
		if (!isset($syslogcfg['disablelocallogging'])) {
297
			$syslogconf .= "*.*								{$g['varlog_path']}/dhcpd.log\n";
298
		}
299
		if (isset($syslogcfg['dhcp'])) {
300
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
301
		}
302

    
303
		$syslogconf .= "!hostapd\n";
304
		if (!isset($syslogcfg['disablelocallogging'])) {
305
			$syslogconf .= "*.* 								{$g['varlog_path']}/wireless.log\n";
306
		}
307
		if (isset($syslogcfg['hostapd'])) {
308
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
309
		}
310

    
311
		$syslogconf .= "!filterlog\n";
312
		if (!isset($syslogcfg['disablelocallogging'])) {
313
			$syslogconf .= "*.* 								{$g['varlog_path']}/filter.log\n";
314
		}
315
		if (isset($syslogcfg['filter'])) {
316
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
317
		}
318

    
319
		$syslogconf .= "!logportalauth\n";
320
		if (!isset($syslogcfg['disablelocallogging'])) {
321
			$syslogconf .= "*.* 								{$g['varlog_path']}/portalauth.log\n";
322
		}
323
		if (isset($syslogcfg['portalauth'])) {
324
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
325
		}
326

    
327
		$syslogconf .= "!-{$facilitylist}\n";
328
		if (!isset($syslogcfg['disablelocallogging'])) {
329
			$syslogconf .= <<<EOD
330
local3.*							{$g['varlog_path']}/vpn.log
331
local5.*							{$g['varlog_path']}/nginx.log
332
*.notice;kern.debug;lpr.info;mail.crit;daemon.none;news.err;local0.none;local3.none;local4.none;local7.none;security.*;auth.info;authpriv.info;daemon.info	{$g['varlog_path']}/system.log
333
auth.info;authpriv.info 					|exec /usr/local/sbin/sshguard -i /var/run/sshguard.pid
334
*.emerg								*
335

    
336
EOD;
337
		}
338
		if (isset($syslogcfg['vpn'])) {
339
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
340
		}
341
		if (isset($syslogcfg['system'])) {
342
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.emerg;*.notice;kern.debug;lpr.info;mail.crit;news.err;local0.none;local3.none;local7.none;security.*;auth.info;authpriv.info;daemon.info");
343
		}
344
		if (isset($syslogcfg['logall'])) {
345
			// Make everything mean everything, including facilities excluded above.
346
			$syslogconf .= "!*\n";
347
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
348
		}
349

    
350
		if (isset($syslogcfg['zmqserver'])) {
351
				$syslogconf .= <<<EOD
352
*.*								^{$syslogcfg['zmqserver']}
353

    
354
EOD;
355
		}
356
		/* write syslog config to pfSense.conf */
357
		if (!@file_put_contents("{$g['varetc_path']}/syslog.d/pfSense.conf", $syslogconf)) {
358
			printf(gettext("Error: cannot open pfSense.conf in system_syslogd_start().%s"), "\n");
359
			unset($syslogconf);
360
			return 1;
361
		}
362
		unset($syslogconf);
363

    
364
		$sourceip = "";
365
		if (!empty($syslogcfg['sourceip'])) {
366
			if ($syslogcfg['ipproto'] == "ipv6") {
367
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
368
				if (!is_ipaddr($ifaddr)) {
369
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
370
				}
371
			} else {
372
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
373
				if (!is_ipaddr($ifaddr)) {
374
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
375
				}
376
			}
377
			if (is_ipaddr($ifaddr)) {
378
				$sourceip = "-b {$ifaddr}";
379
			}
380
		}
381

    
382
		$syslogd_extra = "-f {$g['etc_path']}/syslog.conf {$sourceip}";
383
	}
384

    
385
	$log_sockets = array("{$g['dhcpd_chroot_path']}/var/run/log");
386

    
387
	if (isset($config['installedpackages']['package'])) {
388
		foreach ($config['installedpackages']['package'] as $package) {
389
			if (isset($package['logging']['logsocket']) && $package['logging']['logsocket'] != '' &&
390
			    !in_array($package['logging']['logsocket'], $log_sockets)) {
391
				$log_sockets[] = $package['logging']['logsocket'];
392
			}
393
		}
394
	}
395

    
396
	$syslogd_format = empty($config['syslog']['format']) ? '' : '-O ' . escapeshellarg($config['syslog']['format']);
397

    
398
	$syslogd_sockets = "";
399
	foreach ($log_sockets as $log_socket) {
400
		// Ensure that the log directory exists
401
		$logpath = dirname($log_socket);
402
		safe_mkdir($logpath);
403
		$syslogd_sockets .= " -l {$log_socket}";
404
	}
405

    
406
	/* Setup log rotation */
407
	system_log_rotation_setup();
408

    
409
	/* If HUP was requested, but syslogd is not running, restart it instead. */
410
	if ($sighup && !isvalidpid("{$g['varrun_path']}/syslog.pid")) {
411
		$sighup = false;
412
	}
413

    
414
	$sshguard_whitelist = array();
415
	if (!empty($config['system']['sshguard_whitelist'])) {
416
		$sshguard_whitelist = explode(' ',
417
		    $config['system']['sshguard_whitelist']);
418
	}
419

    
420
	$sshguard_config = array();
421
	$sshguard_config[] = 'LOGREADER="/bin/cat"' . "\n";
422
	$sshguard_config[] = 'BACKEND="/usr/local/libexec/sshg-fw-pf"' . "\n";
423
	if (!empty($config['system']['sshguard_threshold'])) {
424
		$sshguard_config[] = 'THRESHOLD=' .
425
		    $config['system']['sshguard_threshold'] . "\n";
426
	}
427
	if (!empty($config['system']['sshguard_blocktime'])) {
428
		$sshguard_config[] = 'BLOCK_TIME=' .
429
		    $config['system']['sshguard_blocktime'] . "\n";
430
	}
431
	if (!empty($config['system']['sshguard_detection_time'])) {
432
		$sshguard_config[] = 'DETECTION_TIME=' .
433
		    $config['system']['sshguard_detection_time'] . "\n";
434
	}
435
	if (!empty($sshguard_whitelist)) {
436
		@file_put_contents("/usr/local/etc/sshguard.whitelist",
437
		    implode(PHP_EOL, $sshguard_whitelist));
438
		$sshguard_config[] =
439
		    'WHITELIST_FILE=/usr/local/etc/sshguard.whitelist' . "\n";
440
	} else {
441
		unlink_if_exists("/usr/local/etc/sshguard.whitelist");
442
	}
443
	file_put_contents("/usr/local/etc/sshguard.conf", $sshguard_config);
444

    
445
	if (!$sighup) {
446
		sigkillbyname("sshguard", "TERM");
447
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
448
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "TERM");
449
			usleep(100000); // syslogd often doesn't respond to a TERM quickly enough for the starting of syslogd below to be successful
450
		}
451

    
452
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
453
			// if it still hasn't responded to the TERM, KILL it.
454
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
455
			usleep(100000);
456
		}
457

    
458
		$retval = mwexec_bg("/usr/sbin/syslogd {$syslogd_format} -s -c -c {$syslogd_sockets} -P {$g['varrun_path']}/syslog.pid {$syslogd_extra}");
459
	} else {
460
		$retval = sigkillbypid("{$g['varrun_path']}/syslog.pid", "HUP");
461
	}
462

    
463
	if (platform_booting()) {
464
		echo gettext("done.") . "\n";
465
	}
466

    
467
	return $retval;
468
}
469

    
470
function system_log_get_compression() {
471
	global $config, $g, $system_log_compression_types;
472
	/* Default is bzip2 */
473
	if (empty($config['syslog']['logcompressiontype']) ||
474
	    !array_key_exists($config['syslog']['logcompressiontype'], $system_log_compression_types)) {
475
		$compressiontype = 'bzip2';
476
	} else {
477
		$compressiontype = $config['syslog']['logcompressiontype'];
478
	}
479
	return $compressiontype;
480
}
481

    
482
function system_log_get_cat() {
483
	global $system_log_compression_types;
484
	return $system_log_compression_types[system_log_get_compression()]['cat'];
485
}
486

    
487
/* Setup newsyslog log rotation */
488
function system_log_rotation_setup() {
489
	global $config, $g, $system_log_files, $system_log_compression_types;
490
	$syslogcfg = $config['syslog'];
491

    
492
	$mainnewsyslogconf = <<<EOD
493
# Automatically generated, do not edit!
494
# Place configuration files in {$g['varetc_path']}/newsyslog.conf.d
495
<include> {$g['varetc_path']}/newsyslog.conf.d/*
496
# /* Manually added files with non-conflicting names will not be automatically removed */
497

    
498
EOD;
499

    
500
	file_put_contents("{$g['etc_path']}/newsyslog.conf", $mainnewsyslogconf);
501
	safe_mkdir("{$g['varetc_path']}/newsyslog.conf.d");
502
	$log_size = isset($syslogcfg['logfilesize']) ? $syslogcfg['logfilesize'] : $g['default_log_size'];
503
	$log_size = ($log_size < (2**32)/2) ? $log_size : $g['default_log_size'];
504
	$log_size = (int)$log_size/1024;
505

    
506
	$rotatecount = is_numericint($syslogcfg['rotatecount']) ? $syslogcfg['rotatecount'] : 7;
507

    
508
	$compression_flag = $system_log_compression_types[system_log_get_compression()]['flag'];
509

    
510

    
511
	if (isset($syslogcfg)) {
512
		$separatelogfacilities = array('ntp', 'ntpd', 'ntpdate', 'charon', 'ipsec_starter', 'openvpn', 'poes', 'l2tps', 'hostapd', 'dnsmasq', 'named', 'filterdns', 'unbound', 'dhcpd', 'dhcrelay', 'dhclient', 'dhcp6c', 'dpinger', 'radvd', 'routed', 'zebra', 'ospfd', 'ospf6d', 'bgpd', 'miniupnpd', 'igmpproxy', 'filterlog');
513
		$newsyslogconf = <<<EOD
514
/var/log/userlog		root:wheel	600	3	{$log_size}	*	B
515
/var/log/utx.log		root:wheel	644	3	{$log_size}	*	B
516

    
517
EOD;
518

    
519
		if ($config['installedpackages']['package']) {
520
			foreach ($config['installedpackages']['package'] as $package) {
521

    
522
				if (isset($package['logging']['logfilename'])) {
523

    
524
					$pkg_log_owner = isset($package['logging']['logowner']) ? $package['logging']['logowner'] : 'root:wheel';
525
					$pkg_log_mode = isset($package['logging']['logmode']) ? $package['logging']['logmode'] : 600;
526
					$pkg_rotate_count = isset($package['logging']['rotatecount']) ? (int) $package['logging']['rotatecount'] : $rotatecount;
527
					$pkg_log_size = isset($package['logging']['logfilesize']) ? (int) $package['logging']['logfilesize'] / 1024: $log_size;
528
					$pkg_rotate_time = isset($package['logging']['rotatetime']) ? $package['logging']['rotatetime'] : '*';
529
					$pkg_extra_flags = isset($package['logging']['rotateflags']) ? $package['logging']['rotateflags'] : '';
530
					$pkg_pidcmd = isset($package['logging']['pidcmd']) ? $package['logging']['pidcmd'] : '';
531
					$pkg_signal = isset($package['logging']['signal']) ? $package['logging']['signal'] : '';
532

    
533
					$pkgnewsyslogconf = "# Automatically generated for package {$package['name']}. Do not edit.\n";
534
					$pkgnewsyslogconf .= system_log_rotation_make_line("{$g['varlog_path']}/{$package['logging']['logfilename']}",
535
												$pkg_log_owner,
536
												$pkg_log_mode,
537
												$pkg_rotate_count,
538
												$pkg_log_size,
539
												$pkg_rotate_time,
540
												"{$compression_flag}C{$pkg_extra_flags}",
541
												$pkg_pidcmd,
542
												$pkg_signal);
543
					@file_put_contents("{$g['varetc_path']}/newsyslog.conf.d/" . basename($package['logging']['logfilename']) . ".conf", $pkgnewsyslogconf);
544
				}
545
			}
546
		}
547

    
548
		foreach($system_log_files as $logfile) {
549
			$local_log_size = isset($syslogcfg[basename($logfile, '.log') . '_settings']['logfilesize']) ? (int) $syslogcfg[basename($logfile, '.log') . '_settings']['logfilesize'] / 1024: $log_size;
550
			$local_rotate_count = isset($syslogcfg[basename($logfile, '.log') . '_settings']['rotatecount']) ? (int) $syslogcfg[basename($logfile, '.log') . '_settings']['rotatecount'] : $rotatecount;
551

    
552
			$newsyslogconf .= system_log_rotation_make_line("{$g['varlog_path']}/{$logfile}.log", 'root:wheel', 600, $local_rotate_count, $local_log_size, '*', "{$compression_flag}C");
553
		}
554

    
555
		if (!@file_put_contents("{$g['varetc_path']}/newsyslog.conf.d/pfSense.conf", $newsyslogconf)) {
556
			printf(gettext("Error: cannot open pfSense.conf in system_log_rotation_setup().%s"), "\n");
557
		}
558
		unset($newsyslogconf);
559
	}
560
}
561

    
562
function system_log_rotation_make_line($filename, $owner = 'root:wheel', $mode='644', $count=7, $size=1000, $time='*', $flags='C', $pidcmd = '', $signal = '') {
563
	/* TODO: Fix default size, flags, etc. */
564
	$nslline = $filename;
565
	$nslline .= "		{$owner}";
566
	$nslline .= "	{$mode}";
567
	$nslline .= "	{$count}";
568
	$nslline .= "	{$size}";
569
	$nslline .= "	{$time}";
570
	$nslline .= "	{$flags}";
571
	if (!empty($pidcmd)) {
572
		$nslline .= "	{$pidcmd}";
573
	}
574
	if (!empty($signal)) {
575
		$nslline .= "	{$signal}";
576
	}
577
	$nslline .= "\n";
578
	return $nslline;
579
}
580

    
581
function dump_log($logfile, $tail, $withorig = true, $grepfor = "", $grepinvert = "", $format = 'table', $grepreverse = false) {
582
	global $g, $config;
583
	$sor = (isset($config['syslog']['reverse']) || $grepreverse) ? "-r" : "";
584
	$specific_log = basename($logfile, '.log') . '_settings';
585
	if (($config['syslog'][$specific_log]['cronorder'] == 'forward') && !$grepreverse) $sor = "";
586
	if (($config['syslog'][$specific_log]['cronorder'] == 'reverse') ||  $grepreverse) $sor = "-r";
587
	$logarr = array();
588
	$grepline = "  ";
589
	if (is_array($grepfor)) {
590
		$invert = '';
591
		if ((strpos($grepfor[0], '!') === 0)) {
592
			$grepfor[0] = substr($grepfor[0], 1);
593
			$invert = '-v';
594
		}
595
		$grepline .= " | /usr/bin/egrep {$invert} " . escapeshellarg(implode("|", $grepfor));
596
	}
597
	if (is_array($grepinvert)) {
598
		$grepline .= " | /usr/bin/egrep -v " . escapeshellarg(implode("|", $grepinvert));
599
	}
600
	if (is_dir($logfile)) {
601
		$logarr = array(sprintf(gettext("File %s is a directory."), $logfile));
602
	} elseif (file_exists($logfile) && filesize($logfile) == 0) {
603
		$logarr = array(gettext("Log file started."));
604
	} else {
605
		exec(system_log_get_cat() . ' ' . sort_related_log_files($logfile, true, true) . "{$grepline} | /usr/bin/tail {$sor} -n " . escapeshellarg($tail), $logarr);
606
	}
607

    
608
	if ($format == 'none') {
609
		return($logarr);
610
	}
611

    
612
	$rows = 0;
613
	foreach ($logarr as $logent) {
614
		$rows++;
615
		$entry_date_time = "";
616

    
617
		/* Determine log entry content */
618
		$splitlogent = preg_split("/\s+/", $logent, 10);
619
		if (strpos($splitlogent[0], '>') === false) {
620
			/* RFC 3164 Format */
621
			$syslogformat = 'rfc3164';
622
		} else {
623
			/* RFC 5424 Format */
624
			$syslogformat = 'rfc5424';
625
		}
626

    
627
		if ($format == 'raw') {
628
			$entry_text = $logent;
629
		} elseif ($withorig) {
630
			if ($syslogformat == 'rfc3164') {
631
				$entry_date_time = htmlspecialchars(join(" ", array_slice($splitlogent, 0, 3)));
632
				$entry_text = ($splitlogent[3] == $config['system']['hostname']) ? "" : $splitlogent[3] . " ";
633
				$entry_text .= implode(' ', array_slice($splitlogent, 4));
634
			} else {
635
				$entry_date_time = htmlspecialchars($splitlogent[1]);
636
				$entry_text = ($splitlogent[2] == "{$config['system']['hostname']}.{$config['system']['domain']}" ) ? '' : $splitlogent[2] . ' ';
637
				$entry_text .= implode(' ', array_slice($splitlogent, 3));
638
			}
639
		} else {
640
			$entry_text = implode(' ', array_slice($splitlogent, ($syslogformat == 'rfc3164') ? 5 : 9));
641
		}
642
		$entry_text = htmlspecialchars($entry_text);
643

    
644
		/* Output content in desired format. */
645
		switch ($format) {
646
			case 'notable':
647
				echo implode(' ', array($entry_date_time, $entry_text)) . "\n";
648
				break;
649
			case 'raw':
650
				$span = 'colspan="2"';
651
			case 'table':
652
			default:
653
				echo "<tr>\n";
654
				if (!empty($entry_date_time)) {
655
					echo "	<td class=\"text-nowrap\">{$entry_date_time}</td>\n";
656
				}
657
				echo "	<td {$span} style=\"word-wrap:break-word; word-break:break-all; white-space:normal\">{$entry_text}</td>\n";
658
				echo "</tr>\n";
659
				break;
660
		}
661
	}
662

    
663
	return($rows);
664
}
665

    
666
/* format filter logs */
667
function conv_log_filter($logfile, $nentries, $tail = 500, $filtertext = "", $filterinterface = null) {
668
	global $config, $g, $pattern;
669

    
670
	/* Make sure this is a number before using it in a system call */
671
	if (!(is_numeric($tail))) {
672
		return;
673
	}
674

    
675
	/* Safety belt to ensure we get enough lines for filtering without overloading the parsing code */
676
	if ($filtertext) {
677
		$tail = 10000;
678
	}
679

    
680
	/* Always do a reverse tail, to be sure we're grabbing the 'end' of the log. */
681
	$logarr = "";
682

    
683
	$logtypecheck = preg_replace('/\.log$/', '', basename($logfile));
684
	if (in_array($logtypecheck, array('system', 'gateways', 'routing', 'resolver', 'wireless', 'nginx', 'dmesg.boot', 'portalauth', 'dhcpd', 'ipsec', 'ppp', 'openvpn', 'ntpd', 'userlog', 'auth'))) {
685
		$logfile_type = "system";
686
	} elseif (in_array($logtypecheck, array('filter'))) {
687
		$logfile_type = "firewall";
688
	} elseif (in_array($logtypecheck, array('vpn'))) {
689
		$logfile_type = "vpn_login";
690
	} elseif (in_array($logtypecheck, array('poes', 'l2tps'))) {
691
		$logfile_type = "vpn_service";
692
	} elseif (in_array($logtypecheck, array('utx'))) {
693
		$logfile_type = "utx";
694
	} else {
695
		$logfile_type = "unknown";
696
	}
697

    
698
# Common Regular Expression Patterns
699
	$base_patterns = array(
700
		'rfc3164' => array('start_pattern' => "^"),
701
		'rfc5424' => array('start_pattern' => "^<[0-9]{1,3}>[0-9]*\ "),
702
	);
703

    
704
	/* bsd log date */
705
	$base_patterns['rfc3164']['date_pattern'] = "\([a-zA-Z]{3}\ +[0-9]{1,2}\ +[0-9]{2}:[0-9]{2}:[0-9]{2}\)";
706
	/* RFC3339 Extended format date */
707
	$base_patterns['rfc5424']['date_pattern'] = "\((?:[0-9]+)-(?:0[1-9]|1[012])-(?:0[1-9]|[12][0-9]|3[01])[Tt](?:[01][0-9]|2[0-3]):(?:[0-5][0-9]):(?:[0-5][0-9]|60)(?:\.[0-9]+)?(?:(?:[Zz])|(?:[\+|\-](?:[01][0-9]|2[0-3]):[0-5][0-9]))\)";
708

    
709
	/* hostname only, might not be present */
710
	$base_patterns['rfc3164']['host_pattern'] = "\(.*?\)";
711
	/* FQDN, always present */
712
	$base_patterns['rfc5424']['host_pattern'] = "\(\S+?\)";
713

    
714
	/* name[pid]:, pid may not be present */
715
	$base_patterns['rfc3164']['process_pattern'] = "\(.*?\)\(?::\ +\)?";
716
	/* name alone, nothing special */
717
	$base_patterns['rfc5424']['process_pattern'] = "\(\S+?\)\ ";
718

    
719
	/* pid in brackets, may not be present */
720
	$base_patterns['rfc3164']['pid_pattern'] = "\(?:\\\[\([0-9:]*\)\\\]\)?:?";
721
	/* pid (which we want) alone, always present but may be '-', message ID is next, but we ignore it */
722
	$base_patterns['rfc5424']['pid_pattern'] = "\(\S+?\)\ \S+?\ \S+?";
723

    
724
	/* match anything from here on */
725
	$base_patterns['rfc3164']['log_message_pattern'] = "\(.*\)";
726
	$base_patterns['rfc5424']['log_message_pattern'] = "\(.*\)";
727

    
728
	$patterns = array(
729
		'rfc3164' => $base_patterns['rfc3164']['start_pattern'],
730
		'rfc5424' => $base_patterns['rfc5424']['start_pattern'],
731
	);
732

    
733
	# Construct RegEx for specific log file type.
734
	switch ($logfile_type) {
735
		case 'firewall':
736
			$patterns['rfc3164'] = "filterlog\[[0-9]+\]:";
737
			$patterns['rfc5424'] = "filterlog";
738
			break;
739
		case 'system':
740
		case 'vpn_service':
741
			$patterns['rfc3164'] .= $base_patterns['rfc3164']['date_pattern'] . "\ +" .
742
						$base_patterns['rfc3164']['host_pattern'] . "\ +" .
743
						$base_patterns['rfc3164']['process_pattern'] .
744
						$base_patterns['rfc3164']['pid_pattern'] . "\ +" .
745
						$base_patterns['rfc3164']['log_message_pattern'] . "$";
746
			$patterns['rfc5424'] .= $base_patterns['rfc5424']['date_pattern'] . "\ " .
747
						$base_patterns['rfc5424']['host_pattern'] . "\ " .
748
						$base_patterns['rfc5424']['process_pattern'] .
749
						$base_patterns['rfc5424']['pid_pattern'] . "\ " .
750
						$base_patterns['rfc5424']['log_message_pattern'] . "$";
751
			break;
752
		case 'vpn_login':
753
			$action_pattern = "\(.*?\)";
754
			$type_pattern = "\(.*?\)";
755
			$ip_address_pattern = "\(.*?\)";
756
			$user_pattern = "\(.*?\)";
757
			$patterns['rfc3164'] .= $base_patterns['rfc3164']['date_pattern'] . "\ +" .
758
						$base_patterns['rfc3164']['host_pattern'] . "\ +" .
759
						$base_patterns['rfc3164']['process_pattern'] . "\ +" .
760
						"\(.*?\)\,\ *" .
761
						"\(.*?\)\,\ *" .
762
						"\(.*?\)\,\ *" .
763
						"\(.*?\)$";
764
			$patterns['rfc5424'] .= $base_patterns['rfc5424']['date_pattern'] . "\ " .
765
						$base_patterns['rfc5424']['host_pattern'] . "\ " .
766
						$base_patterns['rfc5424']['process_pattern'] .
767
						"\S+?\ \S+?\ \S+?\ " .
768
						"\(\S*?\)\,\ *" .
769
						"\(\S*?\)\,\ *" .
770
						"\(\S*?\)\,\ *" .
771
						"\(\S*?\)$";
772
			break;
773
		case 'unknown':
774
			$patterns['rfc3164'] .= $base_patterns['rfc3164']['date_pattern'] . "*\ +" .
775
						$base_patterns['rfc3164']['log_message_pattern'] . "$";
776
			$patterns['rfc5424'] .= $base_patterns['rfc5424']['date_pattern'] . "*\ " .
777
						$base_patterns['rfc5424']['log_message_pattern'] . "$";
778
			break;
779
		default:
780
			$patterns['rfc3164'] .= "\(.*\)$";
781
			$patterns['rfc5424'] .= "\(.*\)$";
782
	}
783

    
784
	if ($logfile_type != 'utx') {
785
		# Get a bunch of log entries.
786
		exec(system_log_get_cat() . ' ' . sort_related_log_files($logfile, true, true) . " | /usr/bin/tail -r -n {$tail}", $logarr);
787
	} else {
788
		$_gb = exec("/usr/bin/last --libxo=json", $rawdata, $rc);
789
		if ($rc == 0) {
790
			$logarr = json_decode(implode(" ", $rawdata), JSON_OBJECT_AS_ARRAY);
791
			$logarr = $logarr['last-information']['last'];
792
		}
793
	}
794

    
795
	# Remove escapes and fix up the pattern for preg_match.
796
	$patterns['rfc3164'] = '/' . str_replace(array('\(', '\)', '\[', '\]'), array('(', ')', '[', ']'), $patterns['rfc3164']) . '/';
797
	$patterns['rfc5424'] = '/' . str_replace(array('\(', '\)', '\[', '\]'), array('(', ')', '[', ']'), $patterns['rfc5424']) . '/';
798

    
799
	$filterlog = array();
800
	$counter = 0;
801

    
802
	$filterinterface = strtoupper($filterinterface);
803
	foreach ($logarr as $logent) {
804
		if ($counter >= $nentries) {
805
			break;
806
		}
807
		if ($logfile_type != 'utx') {
808
			$pattern = (substr($logent, 0, 1) == '<') ? $patterns['rfc5424'] : $patterns['rfc3164'];
809
		}
810
		switch($logfile_type) {
811
			case 'firewall':
812
				$flent = parse_firewall_log_line($logent);
813
				break;
814
			case 'system':
815
				$flent = parse_system_log_line($logent);
816
				break;
817
			case 'vpn_login':
818
				$flent = parse_vpn_login_log_line($logent);
819
				break;
820
			case 'vpn_service':
821
				$flent = parse_vpn_service_log_line($logent);
822
				break;
823
			case 'utx':
824
				$flent = parse_utx_log_line($logent);
825
				break;
826
			case 'unknown':
827
				$flent = parse_unknown_log_line($logent);
828
				break;
829
			default:
830
				$flent = array();
831
				break;
832
		}
833

    
834
		if (!$filterinterface || ($filterinterface == $flent['interface'])) {
835
			if ((($flent != "") && (!is_array($filtertext)) && (match_filter_line($flent, $filtertext))) ||
836
			    (($flent != "") && (is_array($filtertext)) && (match_filter_field($flent, $filtertext)))) {
837
				$counter++;
838
				$filterlog[] = $flent;
839
			}
840
		}
841
	}
842
	/* Since the lines are in reverse order, flip them around if needed based on the user's preference */
843
	# First get the "General Logging Options" (global) chronological order setting.  Then apply specific log override if set.
844
	$reverse = isset($config['syslog']['reverse']);
845
	$specific_log = basename($logfile, '.log') . '_settings';
846
	if (isset($config['syslog'][$specific_log]['cronorder']) && ($config['syslog'][$specific_log]['cronorder'] == 'forward')) $reverse = false;
847
	if (isset($config['syslog'][$specific_log]['cronorder']) && ($config['syslog'][$specific_log]['cronorder'] == 'reverse')) $reverse = true;
848

    
849
	return ($reverse) ? $filterlog : array_reverse($filterlog);
850
}
851

    
852
function escape_filter_regex($filtertext) {
853
	/* If the caller (user) has not already put a backslash before a slash, to escape it in the regex, */
854
	/* then this will do it. Take out any "\/" already there, then turn all ordinary "/" into "\/".    */
855
	return str_replace('/', '\/', str_replace('\/', '/', $filtertext));
856
}
857

    
858
function match_filter_line($flent, $filtertext = "") {
859
	if (!$filtertext) {
860
		return true;
861
	}
862
	$filtertext = escape_filter_regex(str_replace(' ', '\s+', $filtertext));
863
	return @preg_match("/{$filtertext}/i", implode(" ", array_values($flent)));
864
}
865

    
866
function match_filter_field($flent, $fields) {
867
	foreach ($fields as $key => $field) {
868
		if ($field == "All") {
869
			continue;
870
		}
871
		if ((strpos($field, '!') === 0)) {
872
			$field = substr($field, 1);
873
			if (strtolower($key) == 'act') {
874
				if (in_arrayi($flent[$key], explode(" ", $field))) {
875
					return false;
876
				}
877
			} else {
878
				$field_regex = escape_filter_regex($field);
879
				if (@preg_match("/{$field_regex}/i", $flent[$key])) {
880
					return false;
881
				}
882
			}
883
		} else {
884
			if (strtolower($key) == 'act') {
885
				if (!in_arrayi($flent[$key], explode(" ", $field))) {
886
					return false;
887
				}
888
			} else {
889
				$field_regex = escape_filter_regex($field);
890
				if (!@preg_match("/{$field_regex}/i", $flent[$key])) {
891
					return false;
892
				}
893
			}
894
		}
895
	}
896
	return true;
897
}
898

    
899
// Case Insensitive in_array function
900
function in_arrayi($needle, $haystack) {
901
	return in_array(strtolower($needle), array_map('strtolower', $haystack));
902
}
903

    
904
function parse_vpn_login_log_line($line) {
905
	global $config, $g, $pattern;
906

    
907
	$flent = array();
908
	$log_split = "";
909

    
910
	if (!preg_match($pattern, $line, $log_split))
911
		return "";
912

    
913
	list($all, $flent['time'], $flent['host'], $flent['process'], $flent['action'], $flent['type'], $flent['ip_address'], $flent['user']) = $log_split;
914
	$flent['time'] = str_replace('T', ' ', $flent['time']);
915

    
916
	/* If there is time, action, user, and IP address fields, then the line should be usable/good */
917
	if (!( (trim($flent['time']) == "") && (trim($flent['action']) == "") && (trim($flent['user']) == "") && (trim($flent['ip_address']) == "") )) {
918
		return $flent;
919
	} else {
920
		if ($g['debug']) {
921
			log_error(sprintf(gettext("There was a error parsing log entry: %s. Please report to mailing list or forum."), $line));
922
		}
923
		return "";
924
	}
925
}
926

    
927
function parse_vpn_service_log_line($line) {
928
	global $config, $g, $pattern;
929

    
930
	$flent = array();
931
	$log_split = "";
932

    
933
	if (!preg_match($pattern, $line, $log_split))
934
		return "";
935

    
936
	list($all, $flent['time'], $flent['host'], $flent['type'], $flent['pid'], $flent['message']) = $log_split;
937
	$flent['time'] = str_replace('T', ' ', $flent['time']);
938

    
939
	/* If there is time, type, and message fields, then the line should be usable/good */
940
	if (!( (trim($flent['time']) == "") && (trim($flent['type']) == "") && (trim($flent['message']) == "") )) {
941
		return $flent;
942
	} else {
943
		if ($g['debug']) {
944
			log_error(sprintf(gettext("There was a error parsing log entry: %s. Please report to mailing list or forum."), $line));
945
		}
946
		return "";
947
	}
948
}
949

    
950
function parse_utx_log_line($line) {
951
	$flent['time'] = "{$line['login-time']}";
952
	if ($line['logout-time']) {
953
		$flent['time'] .= " - {$line['logout-time']}";
954
	}
955
	$flent['host'] = $line['from'];
956
	$flent['pid'] = $line['tty'];
957
	$flent['message'] = $line['user'];
958
	if ($line['session-length']) {
959
		$flent['process'] = $line['session-length'];
960
	}
961
	return $flent;
962
}
963

    
964
function parse_unknown_log_line($line) {
965
	global $config, $g, $pattern;
966

    
967
	$flent = array();
968
	$log_split = "";
969

    
970
	if (!preg_match($pattern, $line, $log_split)) {
971
		return "";
972
	}
973

    
974
	list($all, $flent['time'], $flent['message']) = $log_split;
975
	$flent['time'] = str_replace('T', ' ', $flent['time']);
976

    
977
	/* If there is time, and message, fields, then the line should be usable/good */
978
	if (!((trim($flent['time']) == "") && (trim($flent['message']) == ""))) {
979
		return $flent;
980
	} else {
981
		if ($g['debug']) {
982
			log_error(sprintf(gettext("There was a error parsing log entry: %s. Please report to mailing list or forum."), $line));
983
		}
984
		return "";
985
	}
986
}
987

    
988
function parse_system_log_line($line) {
989
	global $config, $g, $pattern;
990

    
991
	$flent = array();
992
	$log_split = "";
993

    
994
	if (!preg_match($pattern, $line, $log_split)) {
995
		return "";
996
	}
997

    
998
	list($all, $flent['time'], $flent['host'], $flent['process'], $flent['pid'], $flent['message']) = $log_split;
999
	$flent['time'] = str_replace('T', ' ', $flent['time']);
1000

    
1001
	/* If there is time, process, and message, fields, then the line should be usable/good */
1002
	if (!((trim($flent['time']) == "") && (trim($flent['process']) == "") && (trim($flent['message']) == ""))) {
1003
		return $flent;
1004
	} else {
1005
		if ($g['debug']) {
1006
			log_error(sprintf(gettext("There was a error parsing log entry: %s. Please report to mailing list or forum."), $line));
1007
		}
1008
		return "";
1009
	}
1010
}
1011

    
1012
function parse_firewall_log_line($line) {
1013
	global $config, $g;
1014

    
1015
	$flent = array();
1016
	$log_split = "";
1017

    
1018
	if (substr($line, 0, 1) == '<') {
1019
		/* RFC 5424 */;
1020
		$pattern = "/^<[0-9]{1,3}>[0-9]*\ (\S+?)\ (\S+?)\ filterlog\ \S+?\ \S+?\ \S+?\ (.*)$/U";
1021
	} else {
1022
		/* RFC 3164 */
1023
		$pattern = "/(.*)\s(.*)\sfilterlog\[[0-9]+\]:\s(.*)$/";
1024
	}
1025

    
1026
	if (!preg_match($pattern, $line, $log_split)) {
1027
		return "";
1028
	}
1029

    
1030
	list($all, $flent['time'], $host, $rule) = $log_split;
1031
	$flent['time'] = str_replace('T', ' ', $flent['time']);
1032

    
1033
	$rule_data = explode(",", $rule);
1034
	$field = 0;
1035

    
1036
	$flent['rulenum'] = $rule_data[$field++];
1037
	$flent['subrulenum'] = $rule_data[$field++];
1038
	$flent['anchor'] = $rule_data[$field++];
1039
	$flent['tracker'] = $rule_data[$field++];
1040
	$flent['realint'] = $rule_data[$field++];
1041
	$flent['interface'] = convert_real_interface_to_friendly_descr($flent['realint']);
1042
	$flent['reason'] = $rule_data[$field++];
1043
	$flent['act'] = $rule_data[$field++];
1044
	$flent['direction'] = $rule_data[$field++];
1045
	$flent['version'] = $rule_data[$field++];
1046

    
1047
	if ($flent['version'] == '4' || $flent['version'] == '6') {
1048
		if ($flent['version'] == '4') {
1049
			$flent['tos'] = $rule_data[$field++];
1050
			$flent['ecn'] = $rule_data[$field++];
1051
			$flent['ttl'] = $rule_data[$field++];
1052
			$flent['id'] = $rule_data[$field++];
1053
			$flent['offset'] = $rule_data[$field++];
1054
			$flent['flags'] = $rule_data[$field++];
1055
			$flent['protoid'] = $rule_data[$field++];
1056
			$flent['proto'] = strtoupper($rule_data[$field++]);
1057
		} else {
1058
			$flent['class'] = $rule_data[$field++];
1059
			$flent['flowlabel'] = $rule_data[$field++];
1060
			$flent['hlim'] = $rule_data[$field++];
1061
			$flent['proto'] = $rule_data[$field++];
1062
			$flent['protoid'] = $rule_data[$field++];
1063
		}
1064

    
1065
		$flent['length'] = $rule_data[$field++];
1066
		$flent['srcip'] = $rule_data[$field++];
1067
		$flent['dstip'] = $rule_data[$field++];
1068

    
1069
		if ($flent['protoid'] == '6' || $flent['protoid'] == '17') { // TCP or UDP
1070
			$flent['srcport'] = $rule_data[$field++];
1071
			$flent['dstport'] = $rule_data[$field++];
1072

    
1073
			$flent['src'] = $flent['srcip'] . ':' . $flent['srcport'];
1074
			$flent['dst'] = $flent['dstip'] . ':' . $flent['dstport'];
1075

    
1076
			$flent['datalen'] = $rule_data[$field++];
1077
			if ($flent['protoid'] == '6') { // TCP
1078
				$flent['tcpflags'] = $rule_data[$field++];
1079
				$flent['seq'] = $rule_data[$field++];
1080
				$flent['ack'] = $rule_data[$field++];
1081
				$flent['window'] = $rule_data[$field++];
1082
				$flent['urg'] = $rule_data[$field++];
1083
				$flent['options'] = explode(";", $rule_data[$field++]);
1084
			}
1085
		} else if ($flent['protoid'] == '1' || $flent['protoid'] == '58') {	// ICMP (IPv4 & IPv6)
1086
			$flent['src'] = $flent['srcip'];
1087
			$flent['dst'] = $flent['dstip'];
1088

    
1089
			$flent['icmp_type'] = $rule_data[$field++];
1090

    
1091
			switch ($flent['icmp_type']) {
1092
				case "request":
1093
				case "reply":
1094
					$flent['icmp_id'] = $rule_data[$field++];
1095
					$flent['icmp_seq'] = $rule_data[$field++];
1096
					break;
1097
				case "unreachproto":
1098
					$flent['icmp_dstip'] = $rule_data[$field++];
1099
					$flent['icmp_protoid'] = $rule_data[$field++];
1100
					break;
1101
				case "unreachport":
1102
					$flent['icmp_dstip'] = $rule_data[$field++];
1103
					$flent['icmp_protoid'] = $rule_data[$field++];
1104
					$flent['icmp_port'] = $rule_data[$field++];
1105
					break;
1106
				case "unreach":
1107
				case "timexceed":
1108
				case "paramprob":
1109
				case "redirect":
1110
				case "maskreply":
1111
					$flent['icmp_descr'] = $rule_data[$field++];
1112
					break;
1113
				case "needfrag":
1114
					$flent['icmp_dstip'] = $rule_data[$field++];
1115
					$flent['icmp_mtu'] = $rule_data[$field++];
1116
					break;
1117
				case "tstamp":
1118
					$flent['icmp_id'] = $rule_data[$field++];
1119
					$flent['icmp_seq'] = $rule_data[$field++];
1120
					break;
1121
				case "tstampreply":
1122
					$flent['icmp_id'] = $rule_data[$field++];
1123
					$flent['icmp_seq'] = $rule_data[$field++];
1124
					$flent['icmp_otime'] = $rule_data[$field++];
1125
					$flent['icmp_rtime'] = $rule_data[$field++];
1126
					$flent['icmp_ttime'] = $rule_data[$field++];
1127
					break;
1128
				default :
1129
					$flent['icmp_descr'] = $rule_data[$field++];
1130
					break;
1131
			}
1132

    
1133
		} else if ($flent['protoid'] == '2') { // IGMP
1134
			$flent['src'] = $flent['srcip'];
1135
			$flent['dst'] = $flent['dstip'];
1136
		} else if ($flent['protoid'] == '112') { // CARP
1137
			$flent['type'] = $rule_data[$field++];
1138
			$flent['ttl'] = $rule_data[$field++];
1139
			$flent['vhid'] = $rule_data[$field++];
1140
			$flent['version'] = $rule_data[$field++];
1141
			$flent['advskew'] = $rule_data[$field++];
1142
			$flent['advbase'] = $rule_data[$field++];
1143
			$flent['src'] = $flent['srcip'];
1144
			$flent['dst'] = $flent['dstip'];
1145
		}
1146
	} else {
1147
		if ($g['debug']) {
1148
			log_error(sprintf(gettext("There was a error parsing rule number: %s. Please report to mailing list or forum."), $flent['rulenum']));
1149
		}
1150
		return "";
1151
	}
1152

    
1153
	/* If there is a src, a dst, and a time, then the line should be usable/good */
1154
	if (!((trim($flent['src']) == "") || (trim($flent['dst']) == "") || (trim($flent['time']) == ""))) {
1155
		return $flent;
1156
	} else {
1157
		if ($g['debug']) {
1158
			log_error(sprintf(gettext("There was a error parsing rule: %s. Please report to mailing list or forum."), $line));
1159
		}
1160
		return "";
1161
	}
1162
}
1163

    
1164
function get_port_with_service($port, $proto) {
1165
	if (!$port || !is_port($port)) {
1166
		return '';
1167
	}
1168

    
1169
	$service = getservbyport($port, $proto);
1170
	$portstr = "";
1171
	if ($service) {
1172
		$portstr = sprintf('<span title="' . gettext('Service %1$s/%2$s: %3$s') . '">' . htmlspecialchars($port) . '</span>', $port, $proto, $service);
1173
	} else {
1174
		$portstr = htmlspecialchars($port);
1175
	}
1176
	return ':' . $portstr;
1177
}
1178

    
1179
function find_rule_by_number($rulenum, $trackernum, $type="block") {
1180
	global $g;
1181

    
1182
	/* Passing arbitrary input to grep could be a Very Bad Thing(tm) */
1183
	if (!is_numeric($rulenum) || !is_numeric($trackernum) || !in_array($type, array('pass', 'block', 'match', 'rdr'))) {
1184
		return;
1185
	}
1186

    
1187
	if ($trackernum == "0") {
1188
		$lookup_pattern = "^@{$rulenum}\([0-9]+\)[[:space:]]{$type}[[:space:]].*[[:space:]]log[[:space:]]";
1189
	} else {
1190
		$lookup_pattern = "^@[0-9]+\({$trackernum}\)[[:space:]]{$type}[[:space:]].*[[:space:]]log[[:space:]]";
1191
	}
1192

    
1193
	/* At the moment, miniupnpd is the only thing I know of that
1194
	   generates logging rdr rules */
1195
	unset($buffer);
1196
	if ($type == "rdr") {
1197
		$_gb = exec("/sbin/pfctl -vvPsn -a \"miniupnpd\" | /usr/bin/egrep " . escapeshellarg("^@{$rulenum}"), $buffer);
1198
	} else {
1199
		$_gb = exec("/sbin/pfctl -vvPsr | /usr/bin/egrep " . escapeshellarg($lookup_pattern), $buffer);
1200
	}
1201
	if (is_array($buffer)) {
1202
		return $buffer[0];
1203
	}
1204

    
1205
	return "";
1206
}
1207

    
1208
function buffer_rules_load() {
1209
	global $g, $buffer_rules_rdr, $buffer_rules_normal;
1210
	unset($buffer, $buffer_rules_rdr, $buffer_rules_normal);
1211
	/* Redeclare globals after unset to work around PHP */
1212
	global $buffer_rules_rdr, $buffer_rules_normal;
1213
	$buffer_rules_rdr = array();
1214
	$buffer_rules_normal = array();
1215

    
1216
	$_gb = exec("/sbin/pfctl -vvPsn -a \"miniupnpd\" | /usr/bin/grep '^@'", $buffer);
1217
	if (is_array($buffer)) {
1218
		foreach ($buffer as $line) {
1219
			list($key, $value) = explode (" ", $line, 2);
1220
			$buffer_rules_rdr[$key] = $value;
1221
		}
1222
	}
1223
	unset($buffer, $_gb);
1224
	$_gb = exec("/sbin/pfctl -vvPsr | /usr/bin/egrep '^@[0-9]+\([0-9]+\)[[:space:]].*[[:space:]]log[[:space:]]'", $buffer);
1225

    
1226
	if (is_array($buffer)) {
1227
		foreach ($buffer as $line) {
1228
			list($key, $value) = explode (" ", $line, 2);
1229
			# pfctl rule number output with tracker number: @dd(dddddddddd)
1230
			$matches = array();
1231
			if (preg_match('/\@(?P<rulenum>\d+)\((?<trackernum>\d+)\)/', $key, $matches) == 1) {
1232
				if ($matches['trackernum'] > 0) {
1233
					$key = $matches['trackernum'];
1234
				} else {
1235
					$key = "@{$matches['rulenum']}";
1236
				}
1237
			}
1238
			$buffer_rules_normal[$key] = $value;
1239
		}
1240
	}
1241
	unset($_gb, $buffer);
1242
}
1243

    
1244
function buffer_rules_clear() {
1245
	unset($GLOBALS['buffer_rules_normal']);
1246
	unset($GLOBALS['buffer_rules_rdr']);
1247
}
1248

    
1249
function find_rule_by_number_buffer($rulenum, $trackernum, $type) {
1250
	global $g, $buffer_rules_rdr, $buffer_rules_normal;
1251

    
1252
	if ($trackernum == "0") {
1253
		$lookup_key = "@{$rulenum}";
1254
	} else {
1255
		$lookup_key = $trackernum;
1256
	}
1257

    
1258
	if ($type == "rdr") {
1259
		$ruleString = $buffer_rules_rdr[$lookup_key];
1260
		//TODO: get the correct 'description' part of a RDR log line. currently just first 30 characters..
1261
		$rulename = substr($ruleString, 0, 30);
1262
	} else {
1263
		$ruleString = $buffer_rules_normal[$lookup_key];
1264
		list(,$rulename,) = explode("\"", $ruleString);
1265
		$rulename = str_replace("USER_RULE: ", '<i class="fa fa-user"></i> ', $rulename);
1266
	}
1267
	return "{$rulename} ({$lookup_key})";
1268
}
1269

    
1270
function find_action_image($action) {
1271
	global $g;
1272
	if ((strstr(strtolower($action), "p")) || (strtolower($action) == "rdr")) {
1273
		return "fa-check-circle-o";
1274
	} else if (strstr(strtolower($action), "r")) {
1275
		return "fa-times-circle-o";
1276
	} else {
1277
		return "fa-ban";
1278
	}
1279
}
1280

    
1281
/* AJAX specific handlers */
1282
function handle_ajax() {
1283
	global $config;
1284
	if ($_REQUEST['lastsawtime'] && $_REQUEST['logfile']) {
1285

    
1286
		$lastsawtime = getGETPOSTsettingvalue('lastsawtime', null);
1287
		$logfile = getGETPOSTsettingvalue('logfile', null);
1288
		$nentries = getGETPOSTsettingvalue('nentries', null);
1289
		$type = getGETPOSTsettingvalue('type', null);
1290
		$filter = getGETPOSTsettingvalue('filter', null);
1291
		$interfacefilter = getGETPOSTsettingvalue('interfacefilter', null);
1292

    
1293
		if (!empty(trim($filter)) || is_numeric($filter)) {
1294
			$filter = json_decode($filter, true);	# Filter Fields Array or Filter Text
1295
		}
1296

    
1297
		/* compare lastsawrule's time stamp to filter logs.
1298
		 * afterwards return the newer records so that client
1299
		 * can update AJAX interface screen.
1300
		 */
1301
		$new_rules = "";
1302

    
1303
		$filterlog = conv_log_filter($logfile, $nentries, $nentries + 100, $filter, $interfacefilter);
1304

    
1305
		/* We need this to always be in forward order for the AJAX update to work properly */
1306
		/* Since the lines are in reverse order, flip them around if needed based on the user's preference */
1307
		# First get the "General Logging Options" (global) chronological order setting.  Then apply specific log override if set.
1308
		$reverse = isset($config['syslog']['reverse']);
1309
		$specific_log = basename($logfile, '.log') . '_settings';
1310
		if ($config['syslog'][$specific_log]['cronorder'] == 'forward') $reverse = false;
1311
		if ($config['syslog'][$specific_log]['cronorder'] == 'reverse') $reverse = true;
1312

    
1313
		$filterlog = ($reverse) ? array_reverse($filterlog) : $filterlog;
1314

    
1315
		foreach ($filterlog as $log_row) {
1316
			$row_time = strtotime($log_row['time']);
1317
			if ($row_time > $lastsawtime) {
1318
				if ($log_row['proto'] == "TCP") {
1319
					$log_row['proto'] .= ":{$log_row['tcpflags']}";
1320
				}
1321

    
1322
				if ($log_row['act'] == "block") {
1323
					$icon_act = "fa-times text-danger";
1324
				} else {
1325
					$icon_act = "fa-check text-success";
1326
				}
1327

    
1328
				$btn = '<i class="fa ' . $icon_act . ' icon-pointer" title="' . $log_row['act'] . '/' . $log_row['tracker'] . '" onclick="javascript:getURL(\'status_logs_filter.php?getrulenum=' . $log_row['rulenum'] . ',' . $log_row['tracker'] . ',' . $log_row['act'] . '\', outputrule);"></i>';
1329
				$new_rules .= "{$btn}||{$log_row['time']}||{$log_row['interface']}||{$log_row['srcip']}||{$log_row['srcport']}||{$log_row['dstip']}||{$log_row['dstport']}||{$log_row['proto']}||{$log_row['version']}||" . time() . "||\n";
1330
			}
1331
		}
1332
		echo $new_rules;
1333
		exit;
1334
	}
1335
}
1336

    
1337
/* Compatibility stubs for old clog functions until packages catch up.
1338
 * Remove once packages all use the new function names. */
1339
function dump_clog_no_table($logfile, $tail, $withorig = true, $grepfor = "", $grepinvert = "") {
1340
	return dump_log($logfile, $tail, $withorig, $grepfor, $grepinvert, $format = 'notable');
1341
}
1342
function dump_log_no_table($logfile, $tail, $withorig = true, $grepfor = "", $grepinvert = "") {
1343
	return dump_log($logfile, $tail, $withorig, $grepfor, $grepinvert, $format = 'notable');
1344
}
1345
function dump_clog($logfile, $tail, $withorig = true, $grepfor = "", $grepinvert = "") {
1346
	return dump_log($logfile, $tail, $withorig, $grepfor, $grepinvert);
1347
}
1348
function return_clog($logfile, $tail, $withorig = true, $grepfor = "", $grepinvert = "", $grepreverse = false) {
1349
	return dump_log($logfile, $tail, $withorig, $grepfor, $grepinvert, $format = 'none', $grepreverse);
1350
}
1351
function return_log($logfile, $tail, $withorig = true, $grepfor = "", $grepinvert = "", $grepreverse = false) {
1352
	return dump_log($logfile, $tail, $withorig, $grepfor, $grepinvert, $format = 'none', $grepreverse);
1353
}
(48-48/60)