Project

General

Profile

Download (47.8 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-2022 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
require_once('util.inc');
30

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

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

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

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

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

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

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

    
90
	return $all_syslog_files;
91
}
92

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

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

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

    
109
	return $related_files;
110
}
111

    
112
function rsort_log_filename($a, $b) {
113
	/* Break the filename up into components by '.', it could be in one
114
	 * Of the following formats:
115
	 * Compressed:   /var/log/<name>.log.<number>.<compressed extension>
116
	 * Uncompressed: /var/log/<name>.log.<number>
117
	 *
118
	 * See: https://redmine.pfsense.org/issues/11639
119
	 */
120
	$aparts = explode('.', $a);
121
	/* If the last part is not a number, it's a compressed log extension,
122
	 * pop it off. */
123
	if (!is_numeric($aparts[count($aparts)-1])) {
124
		array_pop($aparts);
125
	}
126

    
127
	$bparts = explode('.', $b);
128
	if (!is_numeric($bparts[count($bparts)-1])) {
129
		array_pop($bparts);
130
	}
131

    
132
	/* Compare the last entry in each filename array which should now be
133
	 * the log number */
134
	return ($aparts[count($aparts)-1] > $bparts[count($bparts)-1]) ? -1 : 1;
135
}
136

    
137
function clear_log_file($logfile = "/var/log/system.log", $restart_syslogd = true, $remove_rotated = true) {
138
	global $config, $g;
139

    
140
	if ($restart_syslogd) {
141
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
142
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
143
		}
144
	}
145
	exec("/usr/bin/truncate -s 0 " . escapeshellarg($logfile));
146
	if ($remove_rotated) {
147
		unlink_if_exists("{$logfile}.*");
148
	}
149
	if ($restart_syslogd) {
150
		system_syslogd_start();
151
	}
152
	// Bug #6915
153
	if ($logfile == "/var/log/resolver.log") {
154
		services_unbound_configure(true);
155
	}
156
}
157

    
158
function clear_all_log_files($restart = false) {
159
	global $g, $system_log_files, $system_log_non_syslog_files;
160
	if ($restart) {
161
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
162
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
163
		}
164
	}
165

    
166
	/* Combine list of syslog and non-syslog log files */
167
	/* exclude dmesg.boot, see https://redmine.pfsense.org/issues/11428 */
168
	foreach (array_merge(system_syslogd_get_all_logfilenames(true), array_diff($system_log_non_syslog_files, array('dmesg.boot'))) as $lfile) {
169
		clear_log_file("{$g['varlog_path']}/{$lfile}", false);
170
	}
171

    
172
	if ($restart) {
173
		system_syslogd_start();
174
		killbyname("dhcpd");
175
		if (!function_exists('services_dhcpd_configure')) {
176
			require_once('services.inc');
177
		}
178
		services_dhcpd_configure();
179
		// Bug #6915
180
		services_unbound_configure(false);
181
	}
182
	return;
183
}
184

    
185
function system_syslogd_start($sighup = false) {
186
	global $config, $g;
187
	if (isset($config['system']['developerspew'])) {
188
		$mt = microtime();
189
		echo "system_syslogd_start() being called $mt\n";
190
	}
191

    
192
	mwexec("/etc/rc.d/hostid start");
193

    
194
	$syslogcfg = $config['syslog'];
195

    
196
	if (platform_booting()) {
197
		echo gettext("Starting syslog...");
198
	}
199

    
200
	$mainsyslogconf = <<<EOD
201
# Automatically generated, do not edit!
202
# Place configuration files in {$g['varetc_path']}/syslog.d
203
!*\n
204
include						{$g['varetc_path']}/syslog.d
205
# /* Manually added files with non-conflicting names will not be automatically removed */
206

    
207
EOD;
208

    
209
	if (!@file_put_contents("{$g['etc_path']}/syslog.conf", $mainsyslogconf)) {
210
		printf(gettext("Error: cannot open syslog.conf in system_syslogd_start().%s"), "\n");
211
		unset($syslogconf);
212
		return 1;
213
	}
214
	safe_mkdir("{$g['varetc_path']}/syslog.d");
215

    
216
	$syslogd_extra = "";
217
	if (isset($syslogcfg)) {
218
		$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', 'watchfrr', 'miniupnpd', 'igmpproxy', 'filterlog');
219
		$syslogconf = "# Automatically generated, do not edit!\n";
220

    
221
		if ($config['installedpackages']['package']) {
222
			foreach ($config['installedpackages']['package'] as $package) {
223
				if (isset($package['logging']['facilityname']) && isset($package['logging']['logfilename'])) {
224
					array_push($separatelogfacilities, $package['logging']['facilityname']);
225
					if (!is_file($g['varlog_path'].'/'.$package['logging']['logfilename'])) {
226
						mwexec("/usr/bin/touch {$g['varlog_path']}/{$package['logging']['logfilename']}");
227
					}
228
					$pkgsyslogconf = "# Automatically generated for package {$package['name']}. Do not edit.\n";
229
					$pkgsyslogconf .= "!{$package['logging']['facilityname']}\n*.*\t\t\t\t\t\t {$g['varlog_path']}/{$package['logging']['logfilename']}\n";
230
					@file_put_contents("{$g['varetc_path']}/syslog.d/" . basename($package['logging']['logfilename']) . ".conf", $pkgsyslogconf);
231
				}
232
			}
233
		}
234
		$facilitylist = implode(',', array_unique($separatelogfacilities));
235

    
236
		$syslogconf .= "!*\n";
237
		if (!isset($syslogcfg['disablelocallogging'])) {
238
			$syslogconf .= "auth.*;authpriv.* 						{$g['varlog_path']}/auth.log\n";
239
		}
240
		if (isset($syslogcfg['auth'])) {
241
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "auth.*;authpriv.*");
242
		}
243

    
244
		$syslogconf .= "!radvd,routed,zebra,ospfd,ospf6d,bgpd,watchfrr,miniupnpd,igmpproxy\n";
245
		if (!isset($syslogcfg['disablelocallogging'])) {
246
			$syslogconf .= "*.*								{$g['varlog_path']}/routing.log\n";
247
		}
248
		if (isset($syslogcfg['routing'])) {
249
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
250
		}
251

    
252
		$syslogconf .= "!ntp,ntpd,ntpdate\n";
253
		if (!isset($syslogcfg['disablelocallogging'])) {
254
			$syslogconf .= "*.*								{$g['varlog_path']}/ntpd.log\n";
255
		}
256
		if (isset($syslogcfg['ntpd'])) {
257
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
258
		}
259

    
260
		$syslogconf .= "!ppp\n";
261
		if (!isset($syslogcfg['disablelocallogging'])) {
262
			$syslogconf .= "*.*								{$g['varlog_path']}/ppp.log\n";
263
		}
264
		if (isset($syslogcfg['ppp'])) {
265
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
266
		}
267

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

    
276
		$syslogconf .= "!l2tps\n";
277
		if (!isset($syslogcfg['disablelocallogging'])) {
278
			$syslogconf .= "*.*								{$g['varlog_path']}/l2tps.log\n";
279
		}
280
		if (isset($syslogcfg['vpn'])) {
281
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
282
		}
283

    
284
		$syslogconf .= "!charon,ipsec_starter\n";
285
		if (!isset($syslogcfg['disablelocallogging'])) {
286
			$syslogconf .= "*.*								{$g['varlog_path']}/ipsec.log\n";
287
		}
288
		if (isset($syslogcfg['vpn'])) {
289
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
290
		}
291

    
292
		$syslogconf .= "!openvpn\n";
293
		if (!isset($syslogcfg['disablelocallogging'])) {
294
			$syslogconf .= "*.*								{$g['varlog_path']}/openvpn.log\n";
295
		}
296
		if (isset($syslogcfg['vpn'])) {
297
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
298
		}
299

    
300
		$syslogconf .= "!dpinger\n";
301
		if (!isset($syslogcfg['disablelocallogging'])) {
302
			$syslogconf .= "*.*								{$g['varlog_path']}/gateways.log\n";
303
		}
304
		if (isset($syslogcfg['dpinger'])) {
305
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
306
		}
307

    
308
		$syslogconf .= "!dnsmasq,named,filterdns,unbound\n";
309
		if (!isset($syslogcfg['disablelocallogging'])) {
310
			$syslogconf .= "*.*								{$g['varlog_path']}/resolver.log\n";
311
		}
312
		if (isset($syslogcfg['resolver'])) {
313
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
314
		}
315

    
316
		$syslogconf .= "!dhcpd,dhcrelay,dhclient,dhcp6c,dhcpleases,dhcpleases6\n";
317
		if (!isset($syslogcfg['disablelocallogging'])) {
318
			$syslogconf .= "*.*								{$g['varlog_path']}/dhcpd.log\n";
319
		}
320
		if (isset($syslogcfg['dhcp'])) {
321
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
322
		}
323

    
324
		$syslogconf .= "!hostapd\n";
325
		if (!isset($syslogcfg['disablelocallogging'])) {
326
			$syslogconf .= "*.* 								{$g['varlog_path']}/wireless.log\n";
327
		}
328
		if (isset($syslogcfg['hostapd'])) {
329
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
330
		}
331

    
332
		$syslogconf .= "!filterlog\n";
333
		if (!isset($syslogcfg['disablelocallogging'])) {
334
			$syslogconf .= "*.* 								{$g['varlog_path']}/filter.log\n";
335
		}
336
		if (isset($syslogcfg['filter'])) {
337
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
338
		}
339

    
340
		$syslogconf .= "!logportalauth\n";
341
		if (!isset($syslogcfg['disablelocallogging'])) {
342
			$syslogconf .= "*.* 								{$g['varlog_path']}/portalauth.log\n";
343
		}
344
		if (isset($syslogcfg['portalauth'])) {
345
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
346
		}
347

    
348
		$syslogconf .= "!-{$facilitylist}\n";
349
		if (!isset($syslogcfg['disablelocallogging'])) {
350
			$syslogconf .= <<<EOD
351
local3.*							{$g['varlog_path']}/vpn.log
352
local5.*							{$g['varlog_path']}/nginx.log
353
*.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
354
auth.info;authpriv.info 					|exec /usr/local/sbin/sshguard -i /var/run/sshguard.pid
355
*.emerg								*
356

    
357
EOD;
358
		}
359
		if (isset($syslogcfg['vpn'])) {
360
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
361
		}
362
		if (isset($syslogcfg['system'])) {
363
			$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");
364
		}
365
		if (isset($syslogcfg['logall'])) {
366
			// Make everything mean everything, including facilities excluded above.
367
			$syslogconf .= "!*\n";
368
			$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
369
		}
370

    
371
		/* write syslog config to pfSense.conf */
372
		if (!@file_put_contents("{$g['varetc_path']}/syslog.d/pfSense.conf", $syslogconf)) {
373
			printf(gettext("Error: cannot open syslog config file in system_syslogd_start().%s"), "\n");
374
			unset($syslogconf);
375
			return 1;
376
		}
377
		unset($syslogconf);
378

    
379
		$sourceip = "";
380
		if (!empty($syslogcfg['sourceip'])) {
381
			if ($syslogcfg['ipproto'] == "ipv6") {
382
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ipv6($syslogcfg['sourceip']);
383
				if (!is_ipaddr($ifaddr)) {
384
					$ifaddr = get_interface_ip($syslogcfg['sourceip']);
385
				}
386
			} else {
387
				$ifaddr = is_ipaddr($syslogcfg['sourceip']) ? $syslogcfg['sourceip'] : get_interface_ip($syslogcfg['sourceip']);
388
				if (!is_ipaddr($ifaddr)) {
389
					$ifaddr = get_interface_ipv6($syslogcfg['sourceip']);
390
				}
391
			}
392
			if (is_ipaddr($ifaddr)) {
393
				$sourceip = "-b {$ifaddr}";
394
			}
395
		}
396

    
397
		$syslogd_extra = "-f {$g['etc_path']}/syslog.conf {$sourceip}";
398
	}
399

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

    
402
	if (isset($config['installedpackages']['package'])) {
403
		foreach ($config['installedpackages']['package'] as $package) {
404
			if (isset($package['logging']['logsocket']) && $package['logging']['logsocket'] != '' &&
405
			    !in_array($package['logging']['logsocket'], $log_sockets)) {
406
				$log_sockets[] = $package['logging']['logsocket'];
407
			}
408
		}
409
	}
410

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

    
413
	$syslogd_sockets = "";
414
	foreach ($log_sockets as $log_socket) {
415
		// Ensure that the log directory exists
416
		$logpath = dirname($log_socket);
417
		safe_mkdir($logpath);
418
		$syslogd_sockets .= " -l {$log_socket}";
419
	}
420

    
421
	/* Setup log rotation */
422
	system_log_rotation_setup();
423

    
424
	/* If HUP was requested, but syslogd is not running, restart it instead. */
425
	if ($sighup && !isvalidpid("{$g['varrun_path']}/syslog.pid")) {
426
		$sighup = false;
427
	}
428

    
429
	$sshguard_whitelist = array();
430
	if (!empty($config['system']['sshguard_whitelist'])) {
431
		$sshguard_whitelist = explode(' ',
432
		    $config['system']['sshguard_whitelist']);
433
	}
434

    
435
	$sshguard_config = array();
436
	$sshguard_config[] = 'LOGREADER="/bin/cat"' . "\n";
437
	$sshguard_config[] = 'BACKEND="/usr/local/libexec/sshg-fw-pf"' . "\n";
438
	if (!empty($config['system']['sshguard_threshold'])) {
439
		$sshguard_config[] = 'THRESHOLD=' .
440
		    $config['system']['sshguard_threshold'] . "\n";
441
	}
442
	if (!empty($config['system']['sshguard_blocktime'])) {
443
		$sshguard_config[] = 'BLOCK_TIME=' .
444
		    $config['system']['sshguard_blocktime'] . "\n";
445
	}
446
	if (!empty($config['system']['sshguard_detection_time'])) {
447
		$sshguard_config[] = 'DETECTION_TIME=' .
448
		    $config['system']['sshguard_detection_time'] . "\n";
449
	}
450
	if (!empty($sshguard_whitelist)) {
451
		@file_put_contents("/usr/local/etc/sshguard.whitelist",
452
		    implode(PHP_EOL, $sshguard_whitelist));
453
		$sshguard_config[] =
454
		    'WHITELIST_FILE=/usr/local/etc/sshguard.whitelist' . "\n";
455
	} else {
456
		unlink_if_exists("/usr/local/etc/sshguard.whitelist");
457
	}
458
	file_put_contents("/usr/local/etc/sshguard.conf", $sshguard_config);
459

    
460
	if (!$sighup) {
461
		sigkillbyname("sshguard", "TERM");
462
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
463
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "TERM");
464
			usleep(100000); // syslogd often doesn't respond to a TERM quickly enough for the starting of syslogd below to be successful
465
		}
466

    
467
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
468
			// if it still hasn't responded to the TERM, KILL it.
469
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
470
			usleep(100000);
471
		}
472

    
473
		$retval = mwexec_bg("/usr/sbin/syslogd {$syslogd_format} -s -c -c {$syslogd_sockets} -P {$g['varrun_path']}/syslog.pid {$syslogd_extra}");
474
	} else {
475
		$retval = sigkillbypid("{$g['varrun_path']}/syslog.pid", "HUP");
476
	}
477

    
478
	if (platform_booting()) {
479
		echo gettext("done.") . "\n";
480
	}
481

    
482
	return $retval;
483
}
484

    
485
function system_log_get_compression() {
486
	global $config, $g, $system_log_compression_types;
487
	/* Default is bzip2 */
488
	if (empty($config['syslog']['logcompressiontype']) ||
489
	    !array_key_exists($config['syslog']['logcompressiontype'], $system_log_compression_types)) {
490
		if (file_exists("{$g['conf_path']}/syslog_default_uncompressed")) {
491
			/* Disable log compression by default when flag file is present. */
492
			$compressiontype = 'none';
493
		} else {
494
			$compressiontype = 'bzip2';
495
		}
496
	} else {
497
		$compressiontype = $config['syslog']['logcompressiontype'];
498
	}
499
	return $compressiontype;
500
}
501

    
502
function system_log_get_cat() {
503
	global $system_log_compression_types;
504
	return $system_log_compression_types[system_log_get_compression()]['cat'];
505
}
506

    
507
/* Setup newsyslog log rotation */
508
function system_log_rotation_setup() {
509
	global $config, $g, $system_log_files, $system_log_compression_types;
510
	$syslogcfg = $config['syslog'];
511

    
512
	$mainnewsyslogconf = <<<EOD
513
# Automatically generated, do not edit!
514
# Place configuration files in {$g['varetc_path']}/newsyslog.conf.d
515
<include> {$g['varetc_path']}/newsyslog.conf.d/*
516
# /* Manually added files with non-conflicting names will not be automatically removed */
517

    
518
EOD;
519

    
520
	file_put_contents("{$g['etc_path']}/newsyslog.conf", $mainnewsyslogconf);
521
	safe_mkdir("{$g['varetc_path']}/newsyslog.conf.d");
522
	$log_size = isset($syslogcfg['logfilesize']) ? $syslogcfg['logfilesize'] : $g['default_log_size'];
523
	$log_size = ($log_size < (2**32)/2) ? $log_size : $g['default_log_size'];
524
	$log_size = (int)$log_size/1024;
525

    
526
	$rotatecount = is_numericint($syslogcfg['rotatecount']) ? $syslogcfg['rotatecount'] : 7;
527

    
528
	$compression_flag = $system_log_compression_types[system_log_get_compression()]['flag'];
529

    
530

    
531
	if (isset($syslogcfg)) {
532
		$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', 'watchfrr', 'miniupnpd', 'igmpproxy', 'filterlog');
533
		$newsyslogconf = <<<EOD
534
/var/log/userlog		root:wheel	600	3	{$log_size}	*	B
535
/var/log/utx.log		root:wheel	644	3	{$log_size}	*	B
536

    
537
EOD;
538

    
539
		if ($config['installedpackages']['package']) {
540
			foreach ($config['installedpackages']['package'] as $package) {
541

    
542
				if (isset($package['logging']['logfilename'])) {
543

    
544
					$pkg_log_owner = isset($package['logging']['logowner']) ? $package['logging']['logowner'] : 'root:wheel';
545
					$pkg_log_mode = isset($package['logging']['logmode']) ? $package['logging']['logmode'] : 600;
546
					$pkg_rotate_count = isset($package['logging']['rotatecount']) ? (int) $package['logging']['rotatecount'] : $rotatecount;
547
					$pkg_log_size = isset($package['logging']['logfilesize']) ? (int) $package['logging']['logfilesize'] / 1024: $log_size;
548
					$pkg_rotate_time = isset($package['logging']['rotatetime']) ? $package['logging']['rotatetime'] : '*';
549
					$pkg_extra_flags = isset($package['logging']['rotateflags']) ? $package['logging']['rotateflags'] : '';
550
					$pkg_pidcmd = isset($package['logging']['pidcmd']) ? $package['logging']['pidcmd'] : '';
551
					$pkg_signal = isset($package['logging']['signal']) ? $package['logging']['signal'] : '';
552

    
553
					$pkgnewsyslogconf = "# Automatically generated for package {$package['name']}. Do not edit.\n";
554
					$pkgnewsyslogconf .= system_log_rotation_make_line("{$g['varlog_path']}/{$package['logging']['logfilename']}",
555
												$pkg_log_owner,
556
												$pkg_log_mode,
557
												$pkg_rotate_count,
558
												$pkg_log_size,
559
												$pkg_rotate_time,
560
												"{$compression_flag}C{$pkg_extra_flags}",
561
												$pkg_pidcmd,
562
												$pkg_signal);
563
					@file_put_contents("{$g['varetc_path']}/newsyslog.conf.d/" . basename($package['logging']['logfilename']) . ".conf", $pkgnewsyslogconf);
564
				}
565
			}
566
		}
567

    
568
		foreach($system_log_files as $logfile) {
569
			$local_log_size = isset($syslogcfg[basename($logfile, '.log') . '_settings']['logfilesize']) ? (int) $syslogcfg[basename($logfile, '.log') . '_settings']['logfilesize'] / 1024: $log_size;
570
			$local_rotate_count = isset($syslogcfg[basename($logfile, '.log') . '_settings']['rotatecount']) ? (int) $syslogcfg[basename($logfile, '.log') . '_settings']['rotatecount'] : $rotatecount;
571

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

    
575
		if (!@file_put_contents("{$g['varetc_path']}/newsyslog.conf.d/pfSense.conf", $newsyslogconf)) {
576
			printf(gettext("Error: cannot open syslog config file in system_log_rotation_setup().%s"), "\n");
577
		}
578
		unset($newsyslogconf);
579
	}
580
}
581

    
582
function system_log_rotation_make_line($filename, $owner = 'root:wheel', $mode='644', $count=7, $size=1000, $time='*', $flags='C', $pidcmd = '', $signal = '') {
583
	/* TODO: Fix default size, flags, etc. */
584
	$nslline = $filename;
585
	$nslline .= "		{$owner}";
586
	$nslline .= "	{$mode}";
587
	$nslline .= "	{$count}";
588
	$nslline .= "	{$size}";
589
	$nslline .= "	{$time}";
590
	$nslline .= "	{$flags}";
591
	if (!empty($pidcmd)) {
592
		$nslline .= "	{$pidcmd}";
593
	}
594
	if (!empty($signal)) {
595
		$nslline .= "	{$signal}";
596
	}
597
	$nslline .= "\n";
598
	return $nslline;
599
}
600

    
601
function dump_log($logfile, $tail, $withorig = true, $grepfor = "", $grepinvert = "", $format = 'table', $grepreverse = false) {
602
	global $g, $config;
603
	$sor = (isset($config['syslog']['reverse']) || $grepreverse) ? "-r" : "";
604
	$specific_log = basename($logfile, '.log') . '_settings';
605
	if (($config['syslog'][$specific_log]['cronorder'] == 'forward') && !$grepreverse) $sor = "";
606
	if (($config['syslog'][$specific_log]['cronorder'] == 'reverse') ||  $grepreverse) $sor = "-r";
607
	$logarr = array();
608
	$grepline = "  ";
609
	if (is_array($grepfor)) {
610
		$invert = '';
611
		if ((strpos($grepfor[0], '!') === 0)) {
612
			$grepfor[0] = substr($grepfor[0], 1);
613
			$invert = '-v';
614
		}
615
		/* Ensure the user-supplied filter is sane */
616
		$filtertext = cleanup_regex_pattern(implode("|", $grepfor));
617
		if (!empty($filtertext)) {
618
			$grepline .= " | /usr/bin/egrep {$invert} -- " . escapeshellarg($filtertext);
619
		}
620
	}
621
	if (is_array($grepinvert)) {
622
		/* Ensure the user-supplied filter is sane */
623
		$filtertext = cleanup_regex_pattern(implode("|", $grepinvert));
624
		if (!empty($filtertext)) {
625
			$grepline .= " | /usr/bin/egrep -v -- " . escapeshellarg($filtertext);
626
		}
627
	}
628
	if (is_dir($logfile)) {
629
		$logarr = array(sprintf(gettext("File %s is a directory."), $logfile));
630
	} elseif (file_exists($logfile) && filesize($logfile) == 0) {
631
		$logarr = array(gettext("Log file started."));
632
	} else {
633
		exec(system_log_get_cat() . ' ' . sort_related_log_files($logfile, true, true) . "{$grepline} | /usr/bin/tail {$sor} -n " . escapeshellarg($tail), $logarr);
634
	}
635

    
636
	if ($format == 'none') {
637
		return($logarr);
638
	}
639

    
640
	$rows = 0;
641
	foreach ($logarr as $logent) {
642
		$rows++;
643
		$entry_date_time = "";
644

    
645
		/* Determine log entry content */
646
		$splitlogent = preg_split("/\s+/", $logent, 10);
647
		if (strpos($splitlogent[0], '>') === false) {
648
			/* RFC 3164 Format */
649
			$syslogformat = 'rfc3164';
650
		} else {
651
			/* RFC 5424 Format */
652
			$syslogformat = 'rfc5424';
653
		}
654

    
655
		if ($format == 'raw') {
656
			$entry_text = $logent;
657
		} elseif ($withorig) {
658
			if ($syslogformat == 'rfc3164') {
659
				$entry_date_time = htmlspecialchars(join(" ", array_slice($splitlogent, 0, 3)));
660
				$entry_text = ($splitlogent[3] == $config['system']['hostname']) ? "" : $splitlogent[3] . " ";
661
				$entry_text .= implode(' ', array_slice($splitlogent, 4));
662
			} else {
663
				$entry_date_time = htmlspecialchars($splitlogent[1]);
664
				$entry_text = ($splitlogent[2] == "{$config['system']['hostname']}.{$config['system']['domain']}" ) ? '' : $splitlogent[2] . ' ';
665
				$entry_text .= implode(' ', array_slice($splitlogent, 3));
666
			}
667
		} else {
668
			$entry_text = implode(' ', array_slice($splitlogent, ($syslogformat == 'rfc3164') ? 5 : 9));
669
		}
670
		$entry_text = htmlspecialchars($entry_text);
671

    
672
		/* Output content in desired format. */
673
		switch ($format) {
674
			case 'notable':
675
				echo implode(' ', array($entry_date_time, $entry_text)) . "\n";
676
				break;
677
			case 'raw':
678
				$span = 'colspan="2"';
679
			case 'table':
680
			default:
681
				echo "<tr>\n";
682
				if (!empty($entry_date_time)) {
683
					echo "	<td class=\"text-nowrap\">{$entry_date_time}</td>\n";
684
				}
685
				echo "	<td {$span} style=\"word-wrap:break-word; word-break:break-all; white-space:normal\">{$entry_text}</td>\n";
686
				echo "</tr>\n";
687
				break;
688
		}
689
	}
690

    
691
	return($rows);
692
}
693

    
694
/* format filter logs */
695
function conv_log_filter($logfile, $nentries, $tail = 500, $filtertext = "", $filterinterface = null) {
696
	global $config, $g, $pattern;
697

    
698
	/* Make sure this is a number before using it in a system call */
699
	if (!(is_numeric($tail))) {
700
		return;
701
	}
702

    
703
	/* Safety belt to ensure we get enough lines for filtering without overloading the parsing code */
704
	if ($filtertext) {
705
		$tail = 10000;
706
	}
707

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

    
711
	$logtypecheck = preg_replace('/\.log$/', '', basename($logfile));
712
	if (in_array($logtypecheck, array('system', 'gateways', 'routing', 'resolver', 'wireless', 'nginx', 'dmesg.boot', 'portalauth', 'dhcpd', 'ipsec', 'ppp', 'openvpn', 'ntpd', 'userlog', 'auth'))) {
713
		$logfile_type = "system";
714
	} elseif (in_array($logtypecheck, array('filter'))) {
715
		$logfile_type = "firewall";
716
	} elseif (in_array($logtypecheck, array('vpn'))) {
717
		$logfile_type = "vpn_login";
718
	} elseif (in_array($logtypecheck, array('poes', 'l2tps'))) {
719
		$logfile_type = "vpn_service";
720
	} elseif (in_array($logtypecheck, array('utx'))) {
721
		$logfile_type = "utx";
722
	} else {
723
		$logfile_type = "unknown";
724
	}
725

    
726
# Common Regular Expression Patterns
727
	$base_patterns = array(
728
		'rfc3164' => array('start_pattern' => "^"),
729
		'rfc5424' => array('start_pattern' => "^<[0-9]{1,3}>[0-9]*\ "),
730
	);
731

    
732
	/* bsd log date */
733
	$base_patterns['rfc3164']['date_pattern'] = "\([a-zA-Z]{3}\ +[0-9]{1,2}\ +[0-9]{2}:[0-9]{2}:[0-9]{2}\)";
734
	/* RFC3339 Extended format date */
735
	$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]))\)";
736

    
737
	/* hostname only, might not be present */
738
	$base_patterns['rfc3164']['host_pattern'] = "\(.*?\)";
739
	/* FQDN, always present */
740
	$base_patterns['rfc5424']['host_pattern'] = "\(\S+?\)";
741

    
742
	/* name[pid]:, pid may not be present */
743
	$base_patterns['rfc3164']['process_pattern'] = "\(.*?\)\(?::\ +\)?";
744
	/* name alone, nothing special */
745
	$base_patterns['rfc5424']['process_pattern'] = "\(\S+?\)\ ";
746

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

    
752
	/* match anything from here on */
753
	$base_patterns['rfc3164']['log_message_pattern'] = "\(.*\)";
754
	$base_patterns['rfc5424']['log_message_pattern'] = "\(.*\)";
755

    
756
	$patterns = array(
757
		'rfc3164' => $base_patterns['rfc3164']['start_pattern'],
758
		'rfc5424' => $base_patterns['rfc5424']['start_pattern'],
759
	);
760

    
761
	# Construct RegEx for specific log file type.
762
	switch ($logfile_type) {
763
		case 'firewall':
764
			$patterns['rfc3164'] = "filterlog\[[0-9]+\]:";
765
			$patterns['rfc5424'] = "filterlog";
766
			break;
767
		case 'system':
768
		case 'vpn_service':
769
			$patterns['rfc3164'] .= $base_patterns['rfc3164']['date_pattern'] . "\ +" .
770
						$base_patterns['rfc3164']['host_pattern'] . "\ +" .
771
						$base_patterns['rfc3164']['process_pattern'] .
772
						$base_patterns['rfc3164']['pid_pattern'] . "\ +" .
773
						$base_patterns['rfc3164']['log_message_pattern'] . "$";
774
			$patterns['rfc5424'] .= $base_patterns['rfc5424']['date_pattern'] . "\ " .
775
						$base_patterns['rfc5424']['host_pattern'] . "\ " .
776
						$base_patterns['rfc5424']['process_pattern'] .
777
						$base_patterns['rfc5424']['pid_pattern'] . "\ " .
778
						$base_patterns['rfc5424']['log_message_pattern'] . "$";
779
			break;
780
		case 'vpn_login':
781
			$action_pattern = "\(.*?\)";
782
			$type_pattern = "\(.*?\)";
783
			$ip_address_pattern = "\(.*?\)";
784
			$user_pattern = "\(.*?\)";
785
			$patterns['rfc3164'] .= $base_patterns['rfc3164']['date_pattern'] . "\ +" .
786
						$base_patterns['rfc3164']['host_pattern'] . "\ +" .
787
						$base_patterns['rfc3164']['process_pattern'] . "\ +" .
788
						"\(.*?\)\,\ *" .
789
						"\(.*?\)\,\ *" .
790
						"\(.*?\)\,\ *" .
791
						"\(.*?\)$";
792
			$patterns['rfc5424'] .= $base_patterns['rfc5424']['date_pattern'] . "\ " .
793
						$base_patterns['rfc5424']['host_pattern'] . "\ " .
794
						$base_patterns['rfc5424']['process_pattern'] .
795
						"\S+?\ \S+?\ \S+?\ " .
796
						"\(\S*?\)\,\ *" .
797
						"\(\S*?\)\,\ *" .
798
						"\(\S*?\)\,\ *" .
799
						"\(\S*?\)$";
800
			break;
801
		case 'unknown':
802
			$patterns['rfc3164'] .= $base_patterns['rfc3164']['date_pattern'] . "*\ +" .
803
						$base_patterns['rfc3164']['log_message_pattern'] . "$";
804
			$patterns['rfc5424'] .= $base_patterns['rfc5424']['date_pattern'] . "*\ " .
805
						$base_patterns['rfc5424']['log_message_pattern'] . "$";
806
			break;
807
		default:
808
			$patterns['rfc3164'] .= "\(.*\)$";
809
			$patterns['rfc5424'] .= "\(.*\)$";
810
	}
811

    
812
	if ($logfile_type != 'utx') {
813
		# Get a bunch of log entries.
814
		exec(system_log_get_cat() . ' ' . sort_related_log_files($logfile, true, true) . " | /usr/bin/tail -r -n {$tail}", $logarr);
815
	} else {
816
		$_gb = exec("/usr/bin/last --libxo=json", $rawdata, $rc);
817
		if ($rc == 0) {
818
			$logarr = json_decode(implode(" ", $rawdata), JSON_OBJECT_AS_ARRAY);
819
			$logarr = $logarr['last-information']['last'];
820
		}
821
	}
822

    
823
	# Remove escapes and fix up the pattern for preg_match.
824
	$patterns['rfc3164'] = '/' . str_replace(array('\(', '\)', '\[', '\]'), array('(', ')', '[', ']'), $patterns['rfc3164']) . '/';
825
	$patterns['rfc5424'] = '/' . str_replace(array('\(', '\)', '\[', '\]'), array('(', ')', '[', ']'), $patterns['rfc5424']) . '/';
826

    
827
	$filterlog = array();
828
	$counter = 0;
829

    
830
	$filterinterface = strtoupper($filterinterface);
831
	foreach ($logarr as $logent) {
832
		if ($counter >= $nentries) {
833
			break;
834
		}
835
		if ($logfile_type != 'utx') {
836
			$pattern = (substr($logent, 0, 1) == '<') ? $patterns['rfc5424'] : $patterns['rfc3164'];
837
		}
838
		switch($logfile_type) {
839
			case 'firewall':
840
				$flent = parse_firewall_log_line($logent);
841
				break;
842
			case 'system':
843
				$flent = parse_system_log_line($logent);
844
				break;
845
			case 'vpn_login':
846
				$flent = parse_vpn_login_log_line($logent);
847
				break;
848
			case 'vpn_service':
849
				$flent = parse_vpn_service_log_line($logent);
850
				break;
851
			case 'utx':
852
				$flent = parse_utx_log_line($logent);
853
				break;
854
			case 'unknown':
855
				$flent = parse_unknown_log_line($logent);
856
				break;
857
			default:
858
				$flent = array();
859
				break;
860
		}
861

    
862
		if (!$filterinterface || ($filterinterface == $flent['interface'])) {
863
			if ((($flent != "") && (!is_array($filtertext)) && (match_filter_line($flent, $filtertext))) ||
864
			    (($flent != "") && (is_array($filtertext)) && (match_filter_field($flent, $filtertext)))) {
865
				$counter++;
866
				$filterlog[] = $flent;
867
			}
868
		}
869
	}
870
	/* Since the lines are in reverse order, flip them around if needed based on the user's preference */
871
	# First get the "General Logging Options" (global) chronological order setting.  Then apply specific log override if set.
872
	$reverse = isset($config['syslog']['reverse']);
873
	$specific_log = basename($logfile, '.log') . '_settings';
874
	if (isset($config['syslog'][$specific_log]['cronorder']) && ($config['syslog'][$specific_log]['cronorder'] == 'forward')) $reverse = false;
875
	if (isset($config['syslog'][$specific_log]['cronorder']) && ($config['syslog'][$specific_log]['cronorder'] == 'reverse')) $reverse = true;
876

    
877
	return ($reverse) ? $filterlog : array_reverse($filterlog);
878
}
879

    
880
function match_filter_line($flent, $filtertext = "") {
881
	if (!$filtertext) {
882
		return true;
883
	}
884
	$filtertext = escape_filter_regex(str_replace(' ', '\s+', $filtertext));
885
	return @preg_match("/{$filtertext}/i", implode(" ", array_values($flent)));
886
}
887

    
888
function match_filter_field($flent, $fields) {
889
	foreach ($fields as $key => $field) {
890
		if ($field == "All") {
891
			continue;
892
		}
893
		if ((strpos($field, '!') === 0)) {
894
			$field = substr($field, 1);
895
			if (strtolower($key) == 'act') {
896
				if (in_arrayi($flent[$key], explode(" ", $field))) {
897
					return false;
898
				}
899
			} else {
900
				$field_regex = escape_filter_regex($field);
901
				if (@preg_match("/{$field_regex}/i", $flent[$key])) {
902
					return false;
903
				}
904
			}
905
		} else {
906
			if (strtolower($key) == 'act') {
907
				if (!in_arrayi($flent[$key], explode(" ", $field))) {
908
					return false;
909
				}
910
			} else {
911
				$field_regex = escape_filter_regex($field);
912
				if (!@preg_match("/{$field_regex}/i", $flent[$key])) {
913
					return false;
914
				}
915
			}
916
		}
917
	}
918
	return true;
919
}
920

    
921
// Case Insensitive in_array function
922
function in_arrayi($needle, $haystack) {
923
	return in_array(strtolower($needle), array_map('strtolower', $haystack));
924
}
925

    
926
function parse_vpn_login_log_line($line) {
927
	global $config, $g, $pattern;
928

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

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

    
935
	list($all, $flent['time'], $flent['host'], $flent['process'], $flent['action'], $flent['type'], $flent['ip_address'], $flent['user']) = $log_split;
936
	$flent['time'] = str_replace('T', ' ', $flent['time']);
937

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

    
949
function parse_vpn_service_log_line($line) {
950
	global $config, $g, $pattern;
951

    
952
	$flent = array();
953
	$log_split = "";
954

    
955
	if (!preg_match($pattern, $line, $log_split))
956
		return "";
957

    
958
	list($all, $flent['time'], $flent['host'], $flent['type'], $flent['pid'], $flent['message']) = $log_split;
959
	$flent['time'] = str_replace('T', ' ', $flent['time']);
960

    
961
	/* If there is time, type, and message fields, then the line should be usable/good */
962
	if (!( (trim($flent['time']) == "") && (trim($flent['type']) == "") && (trim($flent['message']) == "") )) {
963
		return $flent;
964
	} else {
965
		if ($g['debug']) {
966
			log_error(sprintf(gettext("There was a error parsing log entry: %s. Please report to mailing list or forum."), $line));
967
		}
968
		return "";
969
	}
970
}
971

    
972
function parse_utx_log_line($line) {
973
	$flent['time'] = "{$line['login-time']}";
974
	if ($line['logout-time']) {
975
		$flent['time'] .= " - {$line['logout-time']}";
976
	}
977
	$flent['host'] = $line['from'];
978
	$flent['pid'] = $line['tty'];
979
	$flent['message'] = $line['user'];
980
	if ($line['session-length']) {
981
		$flent['process'] = $line['session-length'];
982
	}
983
	return $flent;
984
}
985

    
986
function parse_unknown_log_line($line) {
987
	global $config, $g, $pattern;
988

    
989
	$flent = array();
990
	$log_split = "";
991

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

    
996
	list($all, $flent['time'], $flent['message']) = $log_split;
997
	$flent['time'] = str_replace('T', ' ', $flent['time']);
998

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

    
1010
function parse_system_log_line($line) {
1011
	global $config, $g, $pattern;
1012

    
1013
	$flent = array();
1014
	$log_split = "";
1015

    
1016
	if (!preg_match($pattern, $line, $log_split)) {
1017
		return "";
1018
	}
1019

    
1020
	list($all, $flent['time'], $flent['host'], $flent['process'], $flent['pid'], $flent['message']) = $log_split;
1021
	$flent['time'] = str_replace('T', ' ', $flent['time']);
1022

    
1023
	/* If there is time, process, and message, fields, then the line should be usable/good */
1024
	if (!((trim($flent['time']) == "") && (trim($flent['process']) == "") && (trim($flent['message']) == ""))) {
1025
		return $flent;
1026
	} else {
1027
		if ($g['debug']) {
1028
			log_error(sprintf(gettext("There was a error parsing log entry: %s. Please report to mailing list or forum."), $line));
1029
		}
1030
		return "";
1031
	}
1032
}
1033

    
1034
function parse_firewall_log_line($line) {
1035
	global $config, $g;
1036

    
1037
	$flent = array();
1038
	$log_split = "";
1039

    
1040
	if (substr($line, 0, 1) == '<') {
1041
		/* RFC 5424 */;
1042
		$pattern = "/^<[0-9]{1,3}>[0-9]*\ (\S+?)\ (\S+?)\ filterlog\ \S+?\ \S+?\ \S+?\ (.*)$/U";
1043
	} else {
1044
		/* RFC 3164 */
1045
		$pattern = "/(.*)\s(.*)\sfilterlog\[[0-9]+\]:\s(.*)$/";
1046
	}
1047

    
1048
	if (!preg_match($pattern, $line, $log_split)) {
1049
		return "";
1050
	}
1051

    
1052
	list($all, $flent['time'], $host, $rule) = $log_split;
1053
	$flent['time'] = str_replace('T', ' ', $flent['time']);
1054

    
1055
	$rule_data = explode(",", $rule);
1056
	$field = 0;
1057

    
1058
	$flent['rulenum'] = $rule_data[$field++];
1059
	$flent['subrulenum'] = $rule_data[$field++];
1060
	$flent['anchor'] = $rule_data[$field++];
1061
	$flent['tracker'] = $rule_data[$field++];
1062
	$flent['realint'] = $rule_data[$field++];
1063
	$flent['interface'] = convert_real_interface_to_friendly_descr($flent['realint']);
1064
	$flent['reason'] = $rule_data[$field++];
1065
	$flent['act'] = $rule_data[$field++];
1066
	$flent['direction'] = $rule_data[$field++];
1067
	$flent['version'] = $rule_data[$field++];
1068

    
1069
	if ($flent['version'] == '4' || $flent['version'] == '6') {
1070
		if ($flent['version'] == '4') {
1071
			$flent['tos'] = $rule_data[$field++];
1072
			$flent['ecn'] = $rule_data[$field++];
1073
			$flent['ttl'] = $rule_data[$field++];
1074
			$flent['id'] = $rule_data[$field++];
1075
			$flent['offset'] = $rule_data[$field++];
1076
			$flent['flags'] = $rule_data[$field++];
1077
			$flent['protoid'] = $rule_data[$field++];
1078
			$flent['proto'] = strtoupper($rule_data[$field++]);
1079
		} else {
1080
			$flent['class'] = $rule_data[$field++];
1081
			$flent['flowlabel'] = $rule_data[$field++];
1082
			$flent['hlim'] = $rule_data[$field++];
1083
			$flent['proto'] = $rule_data[$field++];
1084
			$flent['protoid'] = $rule_data[$field++];
1085
		}
1086

    
1087
		$flent['length'] = $rule_data[$field++];
1088
		$flent['srcip'] = $rule_data[$field++];
1089
		$flent['dstip'] = $rule_data[$field++];
1090

    
1091
		if ($flent['protoid'] == '6' || $flent['protoid'] == '17') { // TCP or UDP
1092
			$flent['srcport'] = $rule_data[$field++];
1093
			$flent['dstport'] = $rule_data[$field++];
1094

    
1095
			$flent['src'] = $flent['srcip'] . ':' . $flent['srcport'];
1096
			$flent['dst'] = $flent['dstip'] . ':' . $flent['dstport'];
1097

    
1098
			$flent['datalen'] = $rule_data[$field++];
1099
			if ($flent['protoid'] == '6') { // TCP
1100
				$flent['tcpflags'] = $rule_data[$field++];
1101
				$flent['seq'] = $rule_data[$field++];
1102
				$flent['ack'] = $rule_data[$field++];
1103
				$flent['window'] = $rule_data[$field++];
1104
				$flent['urg'] = $rule_data[$field++];
1105
				$flent['options'] = explode(";", $rule_data[$field++]);
1106
			}
1107
		} else if ($flent['protoid'] == '1' || $flent['protoid'] == '58') {	// ICMP (IPv4 & IPv6)
1108
			$flent['src'] = $flent['srcip'];
1109
			$flent['dst'] = $flent['dstip'];
1110

    
1111
			$flent['icmp_type'] = $rule_data[$field++];
1112

    
1113
			switch ($flent['icmp_type']) {
1114
				case "request":
1115
				case "reply":
1116
					$flent['icmp_id'] = $rule_data[$field++];
1117
					$flent['icmp_seq'] = $rule_data[$field++];
1118
					break;
1119
				case "unreachproto":
1120
					$flent['icmp_dstip'] = $rule_data[$field++];
1121
					$flent['icmp_protoid'] = $rule_data[$field++];
1122
					break;
1123
				case "unreachport":
1124
					$flent['icmp_dstip'] = $rule_data[$field++];
1125
					$flent['icmp_protoid'] = $rule_data[$field++];
1126
					$flent['icmp_port'] = $rule_data[$field++];
1127
					break;
1128
				case "unreach":
1129
				case "timexceed":
1130
				case "paramprob":
1131
				case "redirect":
1132
				case "maskreply":
1133
					$flent['icmp_descr'] = $rule_data[$field++];
1134
					break;
1135
				case "needfrag":
1136
					$flent['icmp_dstip'] = $rule_data[$field++];
1137
					$flent['icmp_mtu'] = $rule_data[$field++];
1138
					break;
1139
				case "tstamp":
1140
					$flent['icmp_id'] = $rule_data[$field++];
1141
					$flent['icmp_seq'] = $rule_data[$field++];
1142
					break;
1143
				case "tstampreply":
1144
					$flent['icmp_id'] = $rule_data[$field++];
1145
					$flent['icmp_seq'] = $rule_data[$field++];
1146
					$flent['icmp_otime'] = $rule_data[$field++];
1147
					$flent['icmp_rtime'] = $rule_data[$field++];
1148
					$flent['icmp_ttime'] = $rule_data[$field++];
1149
					break;
1150
				default :
1151
					$flent['icmp_descr'] = $rule_data[$field++];
1152
					break;
1153
			}
1154

    
1155
		} else if ($flent['protoid'] == '2') { // IGMP
1156
			$flent['src'] = $flent['srcip'];
1157
			$flent['dst'] = $flent['dstip'];
1158
		} else if ($flent['protoid'] == '112') { // CARP
1159
			$flent['type'] = $rule_data[$field++];
1160
			$flent['ttl'] = $rule_data[$field++];
1161
			$flent['vhid'] = $rule_data[$field++];
1162
			$flent['version'] = $rule_data[$field++];
1163
			$flent['advskew'] = $rule_data[$field++];
1164
			$flent['advbase'] = $rule_data[$field++];
1165
			$flent['src'] = $flent['srcip'];
1166
			$flent['dst'] = $flent['dstip'];
1167
		}
1168
	} else {
1169
		if ($g['debug']) {
1170
			log_error(sprintf(gettext("There was a error parsing rule number: %s. Please report to mailing list or forum."), $flent['rulenum']));
1171
		}
1172
		return "";
1173
	}
1174

    
1175
	/* If there is a src, a dst, and a time, then the line should be usable/good */
1176
	if (!((trim($flent['src']) == "") || (trim($flent['dst']) == "") || (trim($flent['time']) == ""))) {
1177
		return $flent;
1178
	} else {
1179
		if ($g['debug']) {
1180
			log_error(sprintf(gettext("There was a error parsing rule: %s. Please report to mailing list or forum."), $line));
1181
		}
1182
		return "";
1183
	}
1184
}
1185

    
1186
function get_port_with_service($port, $proto) {
1187
	if (!$port || !is_port($port)) {
1188
		return '';
1189
	}
1190

    
1191
	$service = getservbyport($port, $proto);
1192
	$portstr = "";
1193
	if ($service) {
1194
		$portstr = sprintf('<span title="' . gettext('Service %1$s/%2$s: %3$s') . '">' . htmlspecialchars($port) . '</span>', $port, $proto, $service);
1195
	} else {
1196
		$portstr = htmlspecialchars($port);
1197
	}
1198
	return ':' . $portstr;
1199
}
1200

    
1201
function find_rule_by_number($rulenum, $trackernum, $type="block") {
1202
	global $g;
1203

    
1204
	/* Passing arbitrary input to grep could be a Very Bad Thing(tm) */
1205
	if (!is_numeric($rulenum) || !is_numeric($trackernum) || !in_array($type, array('pass', 'block', 'match', 'rdr'))) {
1206
		return;
1207
	}
1208

    
1209
	if ($trackernum == "0") {
1210
		$lookup_pattern = "^@{$rulenum}\([0-9]+\)[[:space:]]{$type}[[:space:]].*[[:space:]]log[[:space:]]";
1211
	} else {
1212
		$lookup_pattern = "^@[0-9]+[[:space:]]{$type}[[:space:]].*[[:space:]]log[[:space:]].*[[:space:]]ridentifier[[:space:]]{$trackernum}";
1213
	}
1214

    
1215
	/* At the moment, miniupnpd is the only thing I know of that
1216
	   generates logging rdr rules */
1217
	unset($buffer);
1218
	if ($type == "rdr") {
1219
		$_gb = exec("/sbin/pfctl -vvPsn -a \"miniupnpd\" | /usr/bin/egrep " . escapeshellarg("^@{$rulenum}"), $buffer);
1220
	} else {
1221
		$_gb = exec("/sbin/pfctl -vvPsr | /usr/bin/egrep " . escapeshellarg($lookup_pattern), $buffer);
1222
	}
1223
	if (is_array($buffer)) {
1224
		return $buffer[0];
1225
	}
1226

    
1227
	return "";
1228
}
1229

    
1230
function buffer_rules_load() {
1231
	global $g, $buffer_rules_rdr, $buffer_rules_normal;
1232
	unset($buffer, $buffer_rules_rdr, $buffer_rules_normal);
1233
	/* Redeclare globals after unset to work around PHP */
1234
	global $buffer_rules_rdr, $buffer_rules_normal;
1235
	$buffer_rules_rdr = array();
1236
	$buffer_rules_normal = array();
1237

    
1238
	$_gb = exec("/sbin/pfctl -vvPsn -a \"miniupnpd\" | /usr/bin/grep '^@'", $buffer);
1239
	if (is_array($buffer)) {
1240
		foreach ($buffer as $line) {
1241
			list($key, $value) = explode (" ", $line, 2);
1242
			$buffer_rules_rdr[$key] = $value;
1243
		}
1244
	}
1245

    
1246
	$rules = pfSense_get_pf_rules();
1247
	if (is_array($rules)) {
1248
		foreach ($rules as $rule) {
1249
			$key = sprintf("%d", $rule['tracker']);
1250
			$buffer_rules_normal[$key] = $rule['label'];
1251
		}
1252
	}
1253
	unset($_gb, $buffer);
1254
}
1255

    
1256
function buffer_rules_clear() {
1257
	unset($GLOBALS['buffer_rules_normal']);
1258
	unset($GLOBALS['buffer_rules_rdr']);
1259
}
1260

    
1261
function find_rule_by_number_buffer($rulenum, $trackernum, $type) {
1262
	global $g, $buffer_rules_rdr, $buffer_rules_normal;
1263

    
1264
	if ($trackernum == "0") {
1265
		$lookup_key = "@{$rulenum}";
1266
	} else {
1267
		$lookup_key = $trackernum;
1268
	}
1269

    
1270
	if ($type == "rdr") {
1271
		$ruleString = $buffer_rules_rdr[$lookup_key];
1272
		//TODO: get the correct 'description' part of a RDR log line. currently just first 30 characters..
1273
		$rulename = substr($ruleString, 0, 30);
1274
	} else {
1275
		$ruleString = $buffer_rules_normal[$lookup_key];
1276
		$rulename = str_replace("USER_RULE: ", '<i class="fa fa-user"></i> ', $ruleString);
1277
	}
1278
	return "{$rulename} ({$lookup_key})";
1279
}
1280

    
1281
function find_action_image($action) {
1282
	global $g;
1283
	if ((strstr(strtolower($action), "p")) || (strtolower($action) == "rdr")) {
1284
		return "fa-check-circle-o";
1285
	} else if (strstr(strtolower($action), "r")) {
1286
		return "fa-times-circle-o";
1287
	} else {
1288
		return "fa-ban";
1289
	}
1290
}
1291

    
1292
/* AJAX specific handlers */
1293
function handle_ajax() {
1294
	global $config;
1295
	if ($_REQUEST['lastsawtime'] && $_REQUEST['logfile']) {
1296

    
1297
		$lastsawtime = getGETPOSTsettingvalue('lastsawtime', null);
1298
		$logfile = getGETPOSTsettingvalue('logfile', null);
1299
		$nentries = getGETPOSTsettingvalue('nentries', null);
1300
		$type = getGETPOSTsettingvalue('type', null);
1301
		$filter = getGETPOSTsettingvalue('filter', null);
1302
		$interfacefilter = getGETPOSTsettingvalue('interfacefilter', null);
1303

    
1304
		if (!empty(trim($filter)) || is_numeric($filter)) {
1305
			$filter = json_decode($filter, true);	# Filter Fields Array or Filter Text
1306
		}
1307

    
1308
		/* compare lastsawrule's time stamp to filter logs.
1309
		 * afterwards return the newer records so that client
1310
		 * can update AJAX interface screen.
1311
		 */
1312
		$new_rules = "";
1313

    
1314
		$filterlog = conv_log_filter($logfile, $nentries, $nentries + 100, $filter, $interfacefilter);
1315

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

    
1324
		$filterlog = ($reverse) ? array_reverse($filterlog) : $filterlog;
1325

    
1326
		foreach ($filterlog as $log_row) {
1327
			$row_time = strtotime($log_row['time']);
1328
			if ($row_time > $lastsawtime) {
1329
				if ($log_row['proto'] == "TCP") {
1330
					$log_row['proto'] .= ":{$log_row['tcpflags']}";
1331
				}
1332

    
1333
				if ($log_row['act'] == "block") {
1334
					$icon_act = "fa-times text-danger";
1335
				} else {
1336
					$icon_act = "fa-check text-success";
1337
				}
1338

    
1339
				$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>';
1340
				$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";
1341
			}
1342
		}
1343
		echo $new_rules;
1344
		exit;
1345
	}
1346
}
1347

    
1348
/* Compatibility stubs for old clog functions until packages catch up.
1349
 * Remove once packages all use the new function names. */
1350
function dump_clog_no_table($logfile, $tail, $withorig = true, $grepfor = "", $grepinvert = "") {
1351
	return dump_log($logfile, $tail, $withorig, $grepfor, $grepinvert, $format = 'notable');
1352
}
1353
function dump_log_no_table($logfile, $tail, $withorig = true, $grepfor = "", $grepinvert = "") {
1354
	return dump_log($logfile, $tail, $withorig, $grepfor, $grepinvert, $format = 'notable');
1355
}
1356
function dump_clog($logfile, $tail, $withorig = true, $grepfor = "", $grepinvert = "") {
1357
	return dump_log($logfile, $tail, $withorig, $grepfor, $grepinvert);
1358
}
1359
function return_clog($logfile, $tail, $withorig = true, $grepfor = "", $grepinvert = "", $grepreverse = false) {
1360
	return dump_log($logfile, $tail, $withorig, $grepfor, $grepinvert, $format = 'none', $grepreverse);
1361
}
1362
function return_log($logfile, $tail, $withorig = true, $grepfor = "", $grepinvert = "", $grepreverse = false) {
1363
	return dump_log($logfile, $tail, $withorig, $grepfor, $grepinvert, $format = 'none', $grepreverse);
1364
}
(49-49/62)