Project

General

Profile

Download (48.9 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-2024 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 (config_path_enabled('syslog')) {
57
		if (array_get_path($syslogcfg, 'remoteserver')) {
58
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server(array_get_path($syslogcfg, 'remoteserver')) . "\n";
59
		}
60
		if (array_get_path($syslogcfg, 'remoteserver2')) {
61
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server(array_get_path($syslogcfg, 'remoteserver2')) . "\n";
62
		}
63
		if (array_get_path($syslogcfg, 'remoteserver3')) {
64
			$remote_servers .= "{$facility}" . str_repeat("\t", $padding) . "@" . system_syslogd_fixup_server(array_get_path($syslogcfg, 'remoteserver3')) . "\n";
65
		}
66
	}
67
	return $remote_servers;
68
}
69

    
70
function system_syslogd_get_all_logfilenames($add_extension = false) {
71
	global $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
	foreach (config_get_path('installedpackages/package', []) as $key => $package) {
83
		if (!empty(config_get_path("installedpackages/package/{$key}/logging", [])) &&
84
		    !empty(config_get_path("installedpackages/package/{$key}/logging/logfilename"))) {
85
			$all_syslog_files[] = config_get_path("installedpackages/package/{$key}/logging/logfilename");
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
	/* Break the filename up into components by '.', it could be in one
113
	 * Of the following formats:
114
	 * Compressed:   /var/log/<name>.log.<number>.<compressed extension>
115
	 * Uncompressed: /var/log/<name>.log.<number>
116
	 *
117
	 * See: https://redmine.pfsense.org/issues/11639
118
	 */
119
	$aparts = explode('.', $a);
120
	/* If the last part is not a number, it's a compressed log extension,
121
	 * pop it off. */
122
	if (!is_numeric($aparts[count($aparts)-1])) {
123
		array_pop($aparts);
124
	}
125

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

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

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

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

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

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

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

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

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

    
193
	$syslogcfg = config_get_path('syslog', []);
194

    
195
	if (is_platform_booting()) {
196
		echo gettext("Starting syslog...");
197
	}
198

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

    
206
EOD;
207

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

    
215
	$syslogd_extra = "";
216
	$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');
217
	$syslogconf = "# Automatically generated, do not edit!\n";
218

    
219
	foreach (config_get_path('installedpackages/package', []) as $key => $package) {
220
		$pkg_log_facility = config_get_path("installedpackages/package/{$key}/logging/facilityname");
221
		$pkg_log_filename = basename(config_get_path("installedpackages/package/{$key}/logging/logfilename"));
222

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

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

    
244
	$syslogconf .= "!radvd\n";
245
	$radvdloglevel = ((config_path_enabled('system', 'radvddebug')) ? '*' : 'err');
246
	if (!config_path_enabled('syslog', 'disablelocallogging')) {
247
		$syslogconf .= "*.{$radvdloglevel}								{$g['varlog_path']}/routing.log\n";
248
	}
249
	if (config_path_enabled('syslog', 'routing')) {
250
		$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "!radvd.{$radvdloglevel}");
251
	}
252

    
253
	$syslogconf .= "!routed,zebra,ospfd,ospf6d,bgpd,watchfrr,miniupnpd,igmpproxy\n";
254
	if (!config_path_enabled('syslog', 'disablelocallogging')) {
255
		$syslogconf .= "*.*									{$g['varlog_path']}/routing.log\n";
256
	}
257
	if (config_path_enabled('syslog', 'routing')) {
258
		$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
259
	}
260

    
261
	$syslogconf .= "!ntp,ntpd,ntpdate\n";
262
	if (!config_path_enabled('syslog', 'disablelocallogging')) {
263
		$syslogconf .= "*.*									{$g['varlog_path']}/ntpd.log\n";
264
	}
265
	if (config_path_enabled('syslog', 'ntpd')) {
266
		$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
267
	}
268

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

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

    
285
	$syslogconf .= "!l2tps\n";
286
	if (!config_path_enabled('syslog', 'disablelocallogging')) {
287
		$syslogconf .= "*.*									{$g['varlog_path']}/l2tps.log\n";
288
	}
289
	if (config_path_enabled('syslog', 'vpn')) {
290
		$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
291
	}
292

    
293
	$syslogconf .= "!charon,ipsec_starter\n";
294
	if (!config_path_enabled('syslog', 'disablelocallogging')) {
295
		$syslogconf .= "*.*									{$g['varlog_path']}/ipsec.log\n";
296
	}
297
	if (config_path_enabled('syslog', 'vpn')) {
298
		$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
299
	}
300

    
301
	$syslogconf .= "!openvpn\n";
302
	if (!config_path_enabled('syslog', 'disablelocallogging')) {
303
		$syslogconf .= "*.*									{$g['varlog_path']}/openvpn.log\n";
304
	}
305
	if (config_path_enabled('syslog', 'vpn')) {
306
		$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
307
	}
308

    
309
	$syslogconf .= "!dpinger\n";
310
	if (!config_path_enabled('syslog', 'disablelocallogging')) {
311
		$syslogconf .= "*.*									{$g['varlog_path']}/gateways.log\n";
312
	}
313
	if (config_path_enabled('syslog', 'dpinger')) {
314
		$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
315
	}
316

    
317
	$syslogconf .= "!dnsmasq,named,filterdns,unbound\n";
318
	if (!config_path_enabled('syslog', 'disablelocallogging')) {
319
		$syslogconf .= "*.*									{$g['varlog_path']}/resolver.log\n";
320
	}
321
	if (config_path_enabled('syslog', 'resolver')) {
322
		$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
323
	}
324

    
325
	$syslogconf .= "!dhcpd,dhcrelay,dhclient,dhcp6c,dhcpleases,dhcpleases6,kea-dhcp4,kea-dhcp6\n";
326
	if (!config_path_enabled('syslog', 'disablelocallogging')) {
327
		$syslogconf .= "*.*									{$g['varlog_path']}/dhcpd.log\n";
328
	}
329
	if (config_path_enabled('syslog', 'dhcp')) {
330
		$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
331
	}
332

    
333
	$syslogconf .= "!hostapd\n";
334
	if (!config_path_enabled('syslog', 'disablelocallogging')) {
335
		$syslogconf .= "*.* 								{$g['varlog_path']}/wireless.log\n";
336
	}
337
	if (config_path_enabled('syslog', 'hostapd')) {
338
		$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
339
	}
340

    
341
	$syslogconf .= "!filterlog\n";
342
	if (!config_path_enabled('syslog', 'disablelocallogging')) {
343
		$syslogconf .= "*.* 								{$g['varlog_path']}/filter.log\n";
344
	}
345
	if (config_path_enabled('syslog', 'filter')) {
346
		$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
347
	}
348

    
349
	$syslogconf .= "!logportalauth\n";
350
	if (!config_path_enabled('syslog', 'disablelocallogging')) {
351
		$syslogconf .= "*.* 								{$g['varlog_path']}/portalauth.log\n";
352
	}
353
	if (config_path_enabled('syslog', 'portalauth')) {
354
		$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
355
	}
356

    
357
	$syslogconf .= "!-{$facilitylist}\n";
358
	if (!config_path_enabled('syslog', 'disablelocallogging')) {
359
		$syslogconf .= <<<EOD
360
local3.*							{$g['varlog_path']}/vpn.log
361
local5.*							{$g['varlog_path']}/nginx.log
362
*.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
363
*.emerg								*
364

    
365
EOD;
366
	}
367
	if (config_path_enabled('syslog', 'vpn')) {
368
		$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "local3.*");
369
	}
370
	if (config_path_enabled('syslog', 'system')) {
371
		$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");
372
	}
373
	if (config_path_enabled('syslog', 'logall')) {
374
		// Make everything mean everything, including facilities excluded above.
375
		$syslogconf .= "!*\n";
376
		$syslogconf .= system_syslogd_get_remote_servers($syslogcfg, "*.*");
377
	}
378

    
379
	/* write syslog config to pfSense.conf */
380
	if (!@file_put_contents("{$g['varetc_path']}/syslog.d/pfSense.conf", $syslogconf)) {
381
		printf(gettext("Error: cannot open syslog config file in system_syslogd_start().%s"), "\n");
382
		unset($syslogconf);
383
		return 1;
384
	}
385
	unset($syslogconf);
386

    
387
	$sourceip = config_get_path('syslog/sourceip');
388
	if (config_path_enabled('syslog') &&
389
	    !empty($sourceip)) {
390
		if (config_get_path('syslog/ipproto') == "ipv6") {
391
			$ifaddr = is_ipaddr($sourceip) ? $sourceip : get_interface_ipv6($sourceip);
392
			if (!is_ipaddr($ifaddr)) {
393
				$ifaddr = get_interface_ip($sourceip);
394
			}
395
		} else {
396
			$ifaddr = is_ipaddr($sourceip) ? $sourceip : get_interface_ip($sourceip);
397
			if (!is_ipaddr($ifaddr)) {
398
				$ifaddr = get_interface_ipv6($sourceip);
399
			}
400
		}
401
		$sourceip = is_ipaddr($ifaddr) ? "-b {$ifaddr}" : '';
402
	} else {
403
		$sourceip = '';
404
	}
405
	$syslogd_extra = "-f {$g['etc_path']}/syslog.conf {$sourceip}";
406

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

    
409
	foreach (config_get_path('installedpackages/package', []) as $key => $package) {
410
		$pkg_log_socket = config_get_path("installedpackages/package/{$key}/logging/logsocket");
411
		if (!empty($pkg_log_socket) &&
412
		    !in_array($pkg_log_socket, $log_sockets)) {
413
			$log_sockets[] = $package['logging']['logsocket'];
414
		}
415
	}
416

    
417
	$syslogd_format = empty(config_get_path('syslog/format')) ? '' : '-O ' . escapeshellarg(config_get_path('syslog/format'));
418

    
419
	$syslogd_sockets = "";
420
	foreach ($log_sockets as $log_socket) {
421
		// Ensure that the log directory exists
422
		$logpath = dirname($log_socket);
423
		safe_mkdir($logpath);
424
		$syslogd_sockets .= " -l {$log_socket}";
425
	}
426

    
427
	/* Setup log rotation */
428
	system_log_rotation_setup();
429

    
430
	/* If HUP was requested, but syslogd is not running, restart it instead. */
431
	if ($sighup && !isvalidpid("{$g['varrun_path']}/syslog.pid")) {
432
		$sighup = false;
433
	}
434

    
435
	if (!$sighup) {
436
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
437
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "TERM");
438
			usleep(100000); // syslogd often doesn't respond to a TERM quickly enough for the starting of syslogd below to be successful
439
		}
440

    
441
		if (isvalidpid("{$g['varrun_path']}/syslog.pid")) {
442
			// if it still hasn't responded to the TERM, KILL it.
443
			sigkillbypid("{$g['varrun_path']}/syslog.pid", "KILL");
444
			usleep(100000);
445
		}
446

    
447
		$retval = mwexec_bg("/usr/sbin/syslogd {$syslogd_format} -s -c -c {$syslogd_sockets} -P {$g['varrun_path']}/syslog.pid {$syslogd_extra}");
448
	} else {
449
		$retval = sigkillbypid("{$g['varrun_path']}/syslog.pid", "HUP");
450
	}
451

    
452
	if (!config_path_enabled('syslog', 'disablelocallogging')) {
453
		system_sshguard_start();
454
	}
455

    
456
	if (is_platform_booting()) {
457
		echo gettext("done.") . "\n";
458
	}
459

    
460
	return $retval;
461
}
462

    
463
function system_sshguard_start() {
464
	$sshguard_whitelist = array();
465
	if (!empty(config_get_path('system/sshguard_whitelist'))) {
466
		$sshguard_whitelist = explode(' ',
467
		    config_get_path('system/sshguard_whitelist'));
468
	}
469

    
470
	$sshguard_config = array();
471
	$sshguard_config[] = 'FILES="' . g_get('varlog_path') . '/auth.log"' . "\n";
472
	$sshguard_config[] = 'BACKEND="/usr/local/libexec/sshg-fw-pf"' . "\n";
473
	if (!empty(config_get_path('system/sshguard_threshold'))) {
474
		$sshguard_config[] = 'THRESHOLD=' .
475
		    config_get_path('system/sshguard_threshold') . "\n";
476
	}
477
	if (!empty(config_get_path('system/sshguard_blocktime'))) {
478
		$sshguard_config[] = 'BLOCK_TIME=' .
479
		    config_get_path('system/sshguard_blocktime') . "\n";
480
	}
481
	if (!empty(config_get_path('system/sshguard_detection_time'))) {
482
		$sshguard_config[] = 'DETECTION_TIME=' .
483
		    config_get_path('system/sshguard_detection_time') . "\n";
484
	}
485
	if (!empty($sshguard_whitelist)) {
486
		@file_put_contents("/usr/local/etc/sshguard.whitelist",
487
		    implode(PHP_EOL, $sshguard_whitelist));
488
		$sshguard_config[] =
489
		    'WHITELIST_FILE=/usr/local/etc/sshguard.whitelist' . "\n";
490
	} else {
491
		unlink_if_exists("/usr/local/etc/sshguard.whitelist");
492
	}
493
	file_put_contents("/usr/local/etc/sshguard.conf", $sshguard_config);
494

    
495
	mwexec_bg('/usr/sbin/daemon -R 60 -P /var/run/daemon_sshguard.pid -t sshguard /usr/local/sbin/sshguard -i /var/run/sshguard.pid');
496
}
497

    
498
function system_sshguard_stop() {
499
	mwexec_bg('pkill -f "' . str_replace('/', '\\/', g_get('varlog_path')) . '\\/auth\.log|[[:<:]](sshguard|sshg-parser|sshg-fw-pf|sshg-blocker)[[:>:]]"');
500
}
501

    
502
function system_log_get_compression() {
503
	global $g, $system_log_compression_types;
504
	$compressiontype = config_get_path('syslog/logcompressiontype');
505
	if (empty($compressiontype) ||
506
	    !array_key_exists($compressiontype, $system_log_compression_types)) {
507
		if (file_exists("{$g['conf_path']}/syslog_default_uncompressed")) {
508
			/* Disable log compression by default when flag file is present. */
509
			$compressiontype = 'none';
510
		} else {
511
			/* Default is bzip2 */
512
			$compressiontype = 'bzip2';
513
		}
514
	}
515
	return $compressiontype;
516
}
517

    
518
function system_log_get_cat() {
519
	global $system_log_compression_types;
520
	return $system_log_compression_types[system_log_get_compression()]['cat'];
521
}
522

    
523
/* Setup newsyslog log rotation */
524
function system_log_rotation_setup() {
525
	global $g, $system_log_files, $system_log_compression_types;
526
	$syslogcfg = config_get_path('syslog', []);
527

    
528
	$mainnewsyslogconf = <<<EOD
529
# Automatically generated, do not edit!
530
# Place configuration files in {$g['varetc_path']}/newsyslog.conf.d
531
<include> {$g['varetc_path']}/newsyslog.conf.d/*
532
# /* Manually added files with non-conflicting names will not be automatically removed */
533

    
534
EOD;
535

    
536
	file_put_contents("{$g['etc_path']}/newsyslog.conf", $mainnewsyslogconf);
537
	safe_mkdir("{$g['varetc_path']}/newsyslog.conf.d");
538

    
539
	$log_size = config_get_path('syslog/logfilesize', g_get('default_log_size'));
540
	$log_size = ($log_size < (2**32)/2) ? $log_size : g_get('default_log_size');
541
	$log_size = (int)$log_size/1024;
542

    
543
	$rotatecount = config_get_path('syslog/rotatecount', 7);
544
	$rotatecount = is_numericint($rotatecount) ? $rotatecount : 7;
545

    
546
	$compression_flag = $system_log_compression_types[system_log_get_compression()]['flag'];
547

    
548
	$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');
549
	$newsyslogconf = <<<EOD
550
/var/log/userlog		root:wheel	600	3	{$log_size}	*	B
551
/var/log/utx.log		root:wheel	644	3	{$log_size}	*	B
552

    
553
EOD;
554

    
555
	foreach (config_get_path('installedpackages/package', []) as $key => $package) {
556
		if (!empty(config_get_path("installedpackages/package/{$key}/logging", [])) &&
557
		    !empty(config_get_path("installedpackages/package/{$key}/logging/logfilename"))) {
558
			$pkg_log_filename = config_get_path("installedpackages/package/{$key}/logging/logfilename");
559
			$pkg_log_owner = config_get_path("installedpackages/package/{$key}/logging/logowner", 'root:wheel');
560
			$pkg_log_mode = config_get_path("installedpackages/package/{$key}/logging/logmode", '600');
561
			$pkg_rotate_count = (int) config_get_path("installedpackages/package/{$key}/logging/rotatecount", $rotatecount);
562
			$pkg_log_size = (int) config_get_path("installedpackages/package/{$key}/logging/logfilesize", 0);
563
			$pkg_log_size = ($pkg_log_size > 0) ? $pkg_log_size / 1024 : $log_size;
564
			$pkg_rotate_time = config_get_path("installedpackages/package/{$key}/logging/rotatetime", '*');
565
			$pkg_extra_flags = config_get_path("installedpackages/package/{$key}/logging/rotateflags", '');
566
			$pkg_pidcmd = config_get_path("installedpackages/package/{$key}/logging/pidcmd", '');
567
			$pkg_signal = config_get_path("installedpackages/package/{$key}/logging/signal", '');
568

    
569
			$pkgnewsyslogconf = "# Automatically generated for package {$package['name']}. Do not edit.\n";
570
			$pkgnewsyslogconf .= system_log_rotation_make_line("{$g['varlog_path']}/{$pkg_log_filename}",
571
										$pkg_log_owner,
572
										$pkg_log_mode,
573
										$pkg_rotate_count,
574
										$pkg_log_size,
575
										$pkg_rotate_time,
576
										"{$compression_flag}C{$pkg_extra_flags}",
577
										$pkg_pidcmd,
578
										$pkg_signal);
579
			@file_put_contents("{$g['varetc_path']}/newsyslog.conf.d/" . basename($pkg_log_filename) . ".conf", $pkgnewsyslogconf);
580
		}
581
	}
582

    
583
	foreach($system_log_files as $logfile) {
584
		$local_log_size = (int) config_get_path("syslog/" . basename($logfile, '.log') . "_settings/logfilesize", 0);
585
		$local_log_size = ($local_log_size > 0) ? $local_log_size / 1024 : $log_size;
586
		$local_rotate_count = (int) config_get_path("syslog/" . basename($logfile, '.log') . "_settings/rotatecount", $rotatecount);
587

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

    
591
	if (!@file_put_contents("{$g['varetc_path']}/newsyslog.conf.d/pfSense.conf", $newsyslogconf)) {
592
		printf(gettext("Error: cannot open syslog config file in system_log_rotation_setup().%s"), "\n");
593
	}
594
	unset($newsyslogconf);
595
}
596

    
597
function system_log_rotation_make_line($filename, $owner = 'root:wheel', $mode='644', $count=7, $size=1000, $time='*', $flags='C', $pidcmd = '', $signal = '') {
598
	/* TODO: Fix default size, flags, etc. */
599
	$nslline = $filename;
600
	$nslline .= "		{$owner}";
601
	$nslline .= "	{$mode}";
602
	$nslline .= "	{$count}";
603
	$nslline .= "	{$size}";
604
	$nslline .= "	{$time}";
605
	$nslline .= "	{$flags}";
606
	if (!empty($pidcmd)) {
607
		$nslline .= "	{$pidcmd}";
608
	}
609
	if (!empty($signal)) {
610
		$nslline .= "	{$signal}";
611
	}
612
	$nslline .= "\n";
613
	return $nslline;
614
}
615

    
616
function dump_log($logfile, $tail, $withorig = true, $grepfor = "", $grepinvert = "", $format = 'table', $grepreverse = false) {
617
	global $g;
618
	$sor = (config_path_enabled('syslog', 'reverse') || $grepreverse) ? "-r" : "";
619
	$specific_log = basename($logfile, '.log') . '_settings';
620
	$cronorder = config_get_path("syslog/{$specific_log}/cronorder");
621
	if (($cronorder == 'forward') && !$grepreverse) {
622
		$sor = "";
623
	}
624
	if (($cronorder == 'reverse') ||  $grepreverse) {
625
		$sor = "-r";
626
	}
627
	$logarr = array();
628
	$grepline = "  ";
629
	if (is_array($grepfor)) {
630
		$invert = '';
631
		if ((strpos($grepfor[0], '!') === 0)) {
632
			$grepfor[0] = substr($grepfor[0], 1);
633
			$invert = '-v';
634
		}
635
		/* Ensure the user-supplied filter is sane */
636
		$filtertext = cleanup_regex_pattern(implode("|", $grepfor));
637
		if (!empty($filtertext)) {
638
			$grepline .= " | /usr/bin/egrep {$invert} -- " . escapeshellarg($filtertext);
639
		}
640
	}
641
	if (is_array($grepinvert)) {
642
		/* Ensure the user-supplied filter is sane */
643
		$filtertext = cleanup_regex_pattern(implode("|", $grepinvert));
644
		if (!empty($filtertext)) {
645
			$grepline .= " | /usr/bin/egrep -v -- " . escapeshellarg($filtertext);
646
		}
647
	}
648
	if (is_dir($logfile)) {
649
		$logarr = array(sprintf(gettext("File %s is a directory."), $logfile));
650
	} elseif (file_exists($logfile) && filesize($logfile) == 0) {
651
		$logarr = array(gettext("Log file started."));
652
	} else {
653
		exec(system_log_get_cat() . ' ' . sort_related_log_files($logfile, true, true) . "{$grepline} | /usr/bin/tail {$sor} -n " . escapeshellarg($tail), $logarr);
654
	}
655

    
656
	if ($format == 'none') {
657
		return($logarr);
658
	}
659

    
660
	$rows = 0;
661
	foreach ($logarr as $logent) {
662
		$rows++;
663
		$entry_date_time = "";
664

    
665
		/* Determine log entry content */
666
		$splitlogent = preg_split("/\s+/", $logent, 10);
667
		if (strpos($splitlogent[0], '>') === false) {
668
			/* RFC 3164 Format */
669
			$syslogformat = 'rfc3164';
670
		} else {
671
			/* RFC 5424 Format */
672
			$syslogformat = 'rfc5424';
673
		}
674

    
675
		if ($format == 'raw') {
676
			$entry_text = $logent;
677
		} elseif ($withorig) {
678
			if ($syslogformat == 'rfc3164') {
679
				$entry_date_time = htmlspecialchars(join(" ", array_slice($splitlogent, 0, 3)));
680
				$entry_text = ($splitlogent[3] == config_get_path('system/hostname')) ? "" : $splitlogent[3] . " ";
681
				$entry_text .= implode(' ', array_slice($splitlogent, 4));
682
			} else {
683
				$entry_date_time = htmlspecialchars($splitlogent[1]);
684
				$entry_text = ($splitlogent[2] == config_get_path('system/hostname') . '.' . config_get_path('system/domain')) ? '' : $splitlogent[2] . ' ';
685
				$entry_text .= implode(' ', array_slice($splitlogent, 3));
686
			}
687
		} else {
688
			$entry_text = implode(' ', array_slice($splitlogent, ($syslogformat == 'rfc3164') ? 5 : 9));
689
		}
690
		$entry_text = htmlspecialchars($entry_text);
691

    
692
		/* Output content in desired format. */
693
		switch ($format) {
694
			case 'notable':
695
				echo implode(' ', array($entry_date_time, $entry_text)) . "\n";
696
				break;
697
			case 'raw':
698
				$span = 'colspan="2"';
699
			case 'table':
700
			default:
701
				echo "<tr>\n";
702
				if (!empty($entry_date_time)) {
703
					echo "	<td class=\"text-nowrap\">{$entry_date_time}</td>\n";
704
				}
705
				echo "	<td {$span} style=\"word-wrap:break-word; word-break:break-all; white-space:normal\">{$entry_text}</td>\n";
706
				echo "</tr>\n";
707
				break;
708
		}
709
	}
710

    
711
	return($rows);
712
}
713

    
714
/* format filter logs */
715
function conv_log_filter($logfile, $nentries, $tail = 500, $filtertext = "", $filterinterface = null) {
716
	global $g, $pattern;
717

    
718
	/* Make sure this is a number before using it in a system call */
719
	if (!(is_numeric($tail))) {
720
		return;
721
	}
722

    
723
	/* Safety belt to ensure we get enough lines for filtering without overloading the parsing code */
724
	if ($filtertext) {
725
		$tail = 10000;
726
	}
727

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

    
731
	$logtypecheck = preg_replace('/\.log$/', '', basename($logfile));
732
	if (in_array($logtypecheck, array('system', 'gateways', 'routing', 'resolver', 'wireless', 'nginx', 'dmesg.boot', 'portalauth', 'dhcpd', 'ipsec', 'ppp', 'openvpn', 'ntpd', 'userlog', 'auth'))) {
733
		$logfile_type = "system";
734
	} elseif (in_array($logtypecheck, array('filter'))) {
735
		$logfile_type = "firewall";
736
	} elseif (in_array($logtypecheck, array('vpn'))) {
737
		$logfile_type = "vpn_login";
738
	} elseif (in_array($logtypecheck, array('poes', 'l2tps'))) {
739
		$logfile_type = "vpn_service";
740
	} elseif (in_array($logtypecheck, array('utx'))) {
741
		$logfile_type = "utx";
742
	} else {
743
		$logfile_type = "unknown";
744
	}
745

    
746
# Common Regular Expression Patterns
747
	$base_patterns = array(
748
		'rfc3164' => array('start_pattern' => "^"),
749
		'rfc5424' => array('start_pattern' => "^<[0-9]{1,3}>[0-9]*\ "),
750
	);
751

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

    
757
	/* hostname only, might not be present */
758
	$base_patterns['rfc3164']['host_pattern'] = "\(.*?\)";
759
	/* FQDN, always present */
760
	$base_patterns['rfc5424']['host_pattern'] = "\(\S+?\)";
761

    
762
	/* name[pid]:, pid may not be present */
763
	$base_patterns['rfc3164']['process_pattern'] = "\(.*?\)\(?::\ +\)?";
764
	/* name alone, nothing special */
765
	$base_patterns['rfc5424']['process_pattern'] = "\(\S+?\)\ ";
766

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

    
772
	/* match anything from here on */
773
	$base_patterns['rfc3164']['log_message_pattern'] = "\(.*\)";
774
	$base_patterns['rfc5424']['log_message_pattern'] = "\(.*\)";
775

    
776
	$patterns = array(
777
		'rfc3164' => $base_patterns['rfc3164']['start_pattern'],
778
		'rfc5424' => $base_patterns['rfc5424']['start_pattern'],
779
	);
780

    
781
	# Construct RegEx for specific log file type.
782
	switch ($logfile_type) {
783
		case 'firewall':
784
			$patterns['rfc3164'] = "filterlog\[[0-9]+\]:";
785
			$patterns['rfc5424'] = "filterlog";
786
			break;
787
		case 'system':
788
		case 'vpn_service':
789
			$patterns['rfc3164'] .= $base_patterns['rfc3164']['date_pattern'] . "\ +" .
790
						$base_patterns['rfc3164']['host_pattern'] . "\ +" .
791
						$base_patterns['rfc3164']['process_pattern'] .
792
						$base_patterns['rfc3164']['pid_pattern'] . "\ +" .
793
						$base_patterns['rfc3164']['log_message_pattern'] . "$";
794
			$patterns['rfc5424'] .= $base_patterns['rfc5424']['date_pattern'] . "\ " .
795
						$base_patterns['rfc5424']['host_pattern'] . "\ " .
796
						$base_patterns['rfc5424']['process_pattern'] .
797
						$base_patterns['rfc5424']['pid_pattern'] . "\ " .
798
						$base_patterns['rfc5424']['log_message_pattern'] . "$";
799
			break;
800
		case 'vpn_login':
801
			$action_pattern = "\(.*?\)";
802
			$type_pattern = "\(.*?\)";
803
			$ip_address_pattern = "\(.*?\)";
804
			$user_pattern = "\(.*?\)";
805
			$patterns['rfc3164'] .= $base_patterns['rfc3164']['date_pattern'] . "\ +" .
806
						$base_patterns['rfc3164']['host_pattern'] . "\ +" .
807
						$base_patterns['rfc3164']['process_pattern'] . "\ +" .
808
						"\(.*?\)\,\ *" .
809
						"\(.*?\)\,\ *" .
810
						"\(.*?\)\,\ *" .
811
						"\(.*?\)$";
812
			$patterns['rfc5424'] .= $base_patterns['rfc5424']['date_pattern'] . "\ " .
813
						$base_patterns['rfc5424']['host_pattern'] . "\ " .
814
						$base_patterns['rfc5424']['process_pattern'] .
815
						"\S+?\ \S+?\ \S+?\ " .
816
						"\(\S*?\)\,\ *" .
817
						"\(\S*?\)\,\ *" .
818
						"\(\S*?\)\,\ *" .
819
						"\(\S*?\)$";
820
			break;
821
		case 'unknown':
822
			$patterns['rfc3164'] .= $base_patterns['rfc3164']['date_pattern'] . "*\ +" .
823
						$base_patterns['rfc3164']['log_message_pattern'] . "$";
824
			$patterns['rfc5424'] .= $base_patterns['rfc5424']['date_pattern'] . "*\ " .
825
						$base_patterns['rfc5424']['log_message_pattern'] . "$";
826
			break;
827
		default:
828
			$patterns['rfc3164'] .= "\(.*\)$";
829
			$patterns['rfc5424'] .= "\(.*\)$";
830
	}
831

    
832
	if ($logfile_type != 'utx') {
833
		# Get a bunch of log entries.
834
		exec(system_log_get_cat() . ' ' . sort_related_log_files($logfile, true, true) . " | /usr/bin/tail -r -n {$tail}", $logarr);
835
	} else {
836
		$_gb = exec("/usr/bin/last --libxo=json", $rawdata, $rc);
837
		if ($rc == 0) {
838
			$logarr = json_decode(implode(" ", $rawdata), JSON_OBJECT_AS_ARRAY);
839
			$logarr = $logarr['last-information']['last'];
840
		}
841
	}
842

    
843
	# Remove escapes and fix up the pattern for preg_match.
844
	$patterns['rfc3164'] = '/' . str_replace(array('\(', '\)', '\[', '\]'), array('(', ')', '[', ']'), $patterns['rfc3164']) . '/';
845
	$patterns['rfc5424'] = '/' . str_replace(array('\(', '\)', '\[', '\]'), array('(', ')', '[', ']'), $patterns['rfc5424']) . '/';
846

    
847
	$filterlog = array();
848
	$counter = 0;
849

    
850
	$filterinterface = strtoupper($filterinterface);
851
	foreach ($logarr as $logent) {
852
		if ($counter >= $nentries) {
853
			break;
854
		}
855
		if ($logfile_type != 'utx') {
856
			$pattern = (substr($logent, 0, 1) == '<') ? $patterns['rfc5424'] : $patterns['rfc3164'];
857
		}
858
		switch($logfile_type) {
859
			case 'firewall':
860
				$flent = parse_firewall_log_line($logent);
861
				break;
862
			case 'system':
863
				$flent = parse_system_log_line($logent);
864
				break;
865
			case 'vpn_login':
866
				$flent = parse_vpn_login_log_line($logent);
867
				break;
868
			case 'vpn_service':
869
				$flent = parse_vpn_service_log_line($logent);
870
				break;
871
			case 'utx':
872
				$flent = parse_utx_log_line($logent);
873
				break;
874
			case 'unknown':
875
				$flent = parse_unknown_log_line($logent);
876
				break;
877
			default:
878
				$flent = array();
879
				break;
880
		}
881

    
882
		if (!$filterinterface || ($filterinterface == $flent['interface'])) {
883
			if ((($flent != "") && (!is_array($filtertext)) && (match_filter_line($flent, $filtertext))) ||
884
			    (($flent != "") && (is_array($filtertext)) && (match_filter_field($flent, $filtertext)))) {
885
				$counter++;
886
				$filterlog[] = $flent;
887
			}
888
		}
889
	}
890
	/* Since the lines are in reverse order, flip them around if needed based on the user's preference */
891
	# First get the "General Logging Options" (global) chronological order setting.  Then apply specific log override if set.
892
	$reverse = config_path_enabled('syslog','reverse');
893
	$specific_log = basename($logfile, '.log') . '_settings';
894
	$cronorder = config_get_path("syslog/{$specific_log}/cronorder");
895
	if ($cronorder == 'forward') {
896
		$reverse = false;
897
	}
898
	if ($cronorder == 'reverse') {
899
		$reverse = true;
900
	}
901

    
902
	return ($reverse) ? $filterlog : array_reverse($filterlog);
903
}
904

    
905
function match_filter_line($flent, $filtertext = "") {
906
	if (!$filtertext) {
907
		return true;
908
	}
909
	$filtertext = escape_filter_regex(str_replace(' ', '\s+', $filtertext));
910
	return @preg_match("/{$filtertext}/i", implode(" ", array_values($flent)));
911
}
912

    
913
function match_filter_field($flent, $fields) {
914
	foreach ($fields as $key => $field) {
915
		if ($field == "All") {
916
			continue;
917
		}
918
		if ((strpos($field, '!') === 0)) {
919
			$field = substr($field, 1);
920
			if (strtolower($key) == 'act') {
921
				if (in_arrayi($flent[$key], explode(" ", $field))) {
922
					return false;
923
				}
924
			} else {
925
				$field_regex = escape_filter_regex($field);
926
				if (@preg_match("/{$field_regex}/i", $flent[$key])) {
927
					return false;
928
				}
929
			}
930
		} else {
931
			if (strtolower($key) == 'act') {
932
				if (!in_arrayi($flent[$key], explode(" ", $field))) {
933
					return false;
934
				}
935
			} else {
936
				$field_regex = escape_filter_regex($field);
937
				if (!@preg_match("/{$field_regex}/i", $flent[$key])) {
938
					return false;
939
				}
940
			}
941
		}
942
	}
943
	return true;
944
}
945

    
946
// Case Insensitive in_array function
947
function in_arrayi($needle, $haystack) {
948
	return in_array(strtolower($needle), array_map('strtolower', $haystack));
949
}
950

    
951
function parse_vpn_login_log_line($line) {
952
	global $g, $pattern;
953

    
954
	$flent = array();
955
	$log_split = "";
956

    
957
	if (!preg_match($pattern, $line, $log_split))
958
		return "";
959

    
960
	list($all, $flent['time'], $flent['host'], $flent['process'], $flent['action'], $flent['type'], $flent['ip_address'], $flent['user']) = $log_split;
961
	$flent['time'] = str_replace('T', ' ', $flent['time']);
962

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

    
974
function parse_vpn_service_log_line($line) {
975
	global $g, $pattern;
976

    
977
	$flent = array();
978
	$log_split = "";
979

    
980
	if (!preg_match($pattern, $line, $log_split))
981
		return "";
982

    
983
	list($all, $flent['time'], $flent['host'], $flent['type'], $flent['pid'], $flent['message']) = $log_split;
984
	$flent['time'] = str_replace('T', ' ', $flent['time']);
985

    
986
	/* If there is time, type, and message fields, then the line should be usable/good */
987
	if (!( (trim($flent['time']) == "") && (trim($flent['type']) == "") && (trim($flent['message']) == "") )) {
988
		return $flent;
989
	} else {
990
		if (g_get('debug')) {
991
			log_error(sprintf(gettext("There was a error parsing log entry: %s. Please report to mailing list or forum."), $line));
992
		}
993
		return "";
994
	}
995
}
996

    
997
function parse_utx_log_line($line) {
998
	$flent['time'] = "{$line['login-time']}";
999
	if ($line['logout-time']) {
1000
		$flent['time'] .= " - {$line['logout-time']}";
1001
	}
1002
	$flent['host'] = $line['from'];
1003
	$flent['pid'] = $line['tty'];
1004
	$flent['message'] = $line['user'];
1005
	if ($line['session-length']) {
1006
		$flent['process'] = $line['session-length'];
1007
	}
1008
	return $flent;
1009
}
1010

    
1011
function parse_unknown_log_line($line) {
1012
	global $g, $pattern;
1013

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

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

    
1021
	list($all, $flent['time'], $flent['message']) = $log_split;
1022
	$flent['time'] = str_replace('T', ' ', $flent['time']);
1023

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

    
1035
function parse_system_log_line($line) {
1036
	global $g, $pattern;
1037

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

    
1041
	if (!preg_match($pattern, $line, $log_split)) {
1042
		return "";
1043
	}
1044

    
1045
	list($all, $flent['time'], $flent['host'], $flent['process'], $flent['pid'], $flent['message']) = $log_split;
1046
	$flent['time'] = str_replace('T', ' ', $flent['time']);
1047

    
1048
	/* If there is time, process, and message, fields, then the line should be usable/good */
1049
	if (!((trim($flent['time']) == "") && (trim($flent['process']) == "") && (trim($flent['message']) == ""))) {
1050
		return $flent;
1051
	} else {
1052
		if (g_get('debug')) {
1053
			log_error(sprintf(gettext("There was a error parsing log entry: %s. Please report to mailing list or forum."), $line));
1054
		}
1055
		return "";
1056
	}
1057
}
1058

    
1059
function parse_firewall_log_line($line) {
1060
	global $g;
1061

    
1062
	$flent = array();
1063
	$log_split = "";
1064

    
1065
	if (substr($line, 0, 1) == '<') {
1066
		/* RFC 5424 */;
1067
		$pattern = "/^<[0-9]{1,3}>[0-9]*\ (\S+?)\ (\S+?)\ filterlog\ \S+?\ \S+?\ \S+?\ (.*)$/U";
1068
	} else {
1069
		/* RFC 3164 */
1070
		$pattern = "/(.*)\s(.*)\sfilterlog\[[0-9]+\]:\s(.*)$/";
1071
	}
1072

    
1073
	if (!preg_match($pattern, $line, $log_split)) {
1074
		return "";
1075
	}
1076

    
1077
	list($all, $flent['time'], $host, $rule) = $log_split;
1078
	$flent['time'] = str_replace('T', ' ', $flent['time']);
1079

    
1080
	$rule_data = array_filter(explode(",", $rule));
1081
	$field = 0;
1082

    
1083
	$flent['rulenum'] = $rule_data[$field++];
1084
	$flent['subrulenum'] = $rule_data[$field++];
1085
	$flent['anchor'] = $rule_data[$field++];
1086
	$flent['tracker'] = $rule_data[$field++];
1087
	$flent['realint'] = $rule_data[$field++];
1088
	$flent['interface'] = convert_real_interface_to_friendly_descr($flent['realint']);
1089
	$flent['reason'] = $rule_data[$field++];
1090
	$flent['act'] = $rule_data[$field++];
1091
	$flent['direction'] = $rule_data[$field++];
1092
	$flent['version'] = $rule_data[$field++];
1093

    
1094
	if ($flent['version'] == '4' || $flent['version'] == '6') {
1095
		if ($flent['version'] == '4') {
1096
			$flent['tos'] = $rule_data[$field++];
1097
			$flent['ecn'] = $rule_data[$field++];
1098
			$flent['ttl'] = $rule_data[$field++];
1099
			$flent['id'] = $rule_data[$field++];
1100
			$flent['offset'] = $rule_data[$field++];
1101
			$flent['flags'] = $rule_data[$field++];
1102
			$flent['protoid'] = $rule_data[$field++];
1103
			$flent['proto'] = strtoupper($rule_data[$field++]);
1104
		} else {
1105
			$flent['class'] = $rule_data[$field++];
1106
			$flent['flowlabel'] = $rule_data[$field++];
1107
			$flent['hlim'] = $rule_data[$field++];
1108
			$flent['proto'] = $rule_data[$field++];
1109
			$flent['protoid'] = $rule_data[$field++];
1110
		}
1111

    
1112
		$flent['length'] = $rule_data[$field++];
1113
		$flent['srcip'] = $rule_data[$field++];
1114
		$flent['dstip'] = $rule_data[$field++];
1115

    
1116
		switch($flent['protoid']) {
1117
			case '6':
1118
			case '17': // TCP or UDP
1119
			case '132': // SCTP
1120
				$flent['srcport'] = $rule_data[$field++];
1121
				$flent['dstport'] = $rule_data[$field++];
1122

    
1123
				$flent['src'] = $flent['srcip'] . ':' . $flent['srcport'];
1124
				$flent['dst'] = $flent['dstip'] . ':' . $flent['dstport'];
1125

    
1126
				$flent['datalen'] = $rule_data[$field++];
1127
				if ($flent['protoid'] == '6') { // TCP
1128
					$flent['tcpflags'] = $rule_data[$field++];
1129
					$flent['seq'] = $rule_data[$field++];
1130
					$flent['ack'] = $rule_data[$field++];
1131
					$flent['window'] = $rule_data[$field++];
1132
					$flent['urg'] = $rule_data[$field++];
1133
					$flent['options'] = explode(";", $rule_data[$field++]);
1134
				}
1135
				break;
1136
			case '1':
1137
			case '58': // ICMP (IPv4 & IPv6)
1138
				$flent['src'] = $flent['srcip'];
1139
				$flent['dst'] = $flent['dstip'];
1140

    
1141
				$flent['icmp_type'] = $rule_data[$field++];
1142

    
1143
				switch ($flent['icmp_type']) {
1144
					case "request":
1145
					case "reply":
1146
						$flent['icmp_id'] = $rule_data[$field++];
1147
						$flent['icmp_seq'] = $rule_data[$field++];
1148
						break;
1149
					case "unreachproto":
1150
						$flent['icmp_dstip'] = $rule_data[$field++];
1151
						$flent['icmp_protoid'] = $rule_data[$field++];
1152
						break;
1153
					case "unreachport":
1154
						$flent['icmp_dstip'] = $rule_data[$field++];
1155
						$flent['icmp_protoid'] = $rule_data[$field++];
1156
						$flent['icmp_port'] = $rule_data[$field++];
1157
						break;
1158
					case "unreach":
1159
					case "timexceed":
1160
					case "paramprob":
1161
					case "redirect":
1162
					case "maskreply":
1163
						$flent['icmp_descr'] = $rule_data[$field++];
1164
						break;
1165
					case "needfrag":
1166
						$flent['icmp_dstip'] = $rule_data[$field++];
1167
						$flent['icmp_mtu'] = $rule_data[$field++];
1168
						break;
1169
					case "tstamp":
1170
						$flent['icmp_id'] = $rule_data[$field++];
1171
						$flent['icmp_seq'] = $rule_data[$field++];
1172
						break;
1173
					case "tstampreply":
1174
						$flent['icmp_id'] = $rule_data[$field++];
1175
						$flent['icmp_seq'] = $rule_data[$field++];
1176
						$flent['icmp_otime'] = $rule_data[$field++];
1177
						$flent['icmp_rtime'] = $rule_data[$field++];
1178
						$flent['icmp_ttime'] = $rule_data[$field++];
1179
						break;
1180
					default :
1181
						$flent['icmp_descr'] = $rule_data[$field++];
1182
						break;
1183
				}
1184
				break;
1185
			case '112': // CARP
1186
				$flent['type'] = $rule_data[$field++];
1187
				$flent['ttl'] = $rule_data[$field++];
1188
				$flent['vhid'] = $rule_data[$field++];
1189
				$flent['version'] = $rule_data[$field++];
1190
				$flent['advskew'] = $rule_data[$field++];
1191
				$flent['advbase'] = $rule_data[$field++];
1192
				$flent['src'] = $flent['srcip'];
1193
				$flent['dst'] = $flent['dstip'];
1194
				break;
1195
			default:
1196
				$flent['src'] = $flent['srcip'];
1197
				$flent['dst'] = $flent['dstip'];
1198
				break;
1199
		}
1200
	} else {
1201
		if (g_get('debug')) {
1202
			log_error(sprintf(gettext("There was a error parsing rule number: %s. Please report to mailing list or forum."), $flent['rulenum']));
1203
		}
1204
		return "";
1205
	}
1206

    
1207
	/* If there is a src, a dst, and a time, then the line should be usable/good */
1208
	if (!((trim($flent['src']) == "") || (trim($flent['dst']) == "") || (trim($flent['time']) == ""))) {
1209
		return $flent;
1210
	} else {
1211
		if (g_get('debug')) {
1212
			log_error(sprintf(gettext("There was a error parsing rule: %s. Please report to mailing list or forum."), $line));
1213
		}
1214
		return "";
1215
	}
1216
}
1217

    
1218
function get_port_with_service($port, $proto) {
1219
	if (!$port || !is_port($port)) {
1220
		return '';
1221
	}
1222

    
1223
	$service = getservbyport($port, $proto);
1224
	$portstr = "";
1225
	if ($service) {
1226
		$portstr = sprintf('<span title="' . gettext('Service %1$s/%2$s: %3$s') . '">' . htmlspecialchars($port) . '</span>', $port, $proto, $service);
1227
	} else {
1228
		$portstr = htmlspecialchars($port);
1229
	}
1230
	return ':' . $portstr;
1231
}
1232

    
1233
function find_rule_by_number($rulenum, $trackernum, $type="block") {
1234
	global $g;
1235

    
1236
	/* Passing arbitrary input to grep could be a Very Bad Thing(tm) */
1237
	if (!is_numeric($rulenum) || !is_numeric($trackernum) || !in_array($type, array('pass', 'block', 'match', 'rdr'))) {
1238
		return;
1239
	}
1240

    
1241
	if ($trackernum == "0") {
1242
		$lookup_pattern = "^@{$rulenum}\([0-9]+\)[[:space:]]{$type}[[:space:]].*[[:space:]]log[[:space:]]";
1243
	} else {
1244
		$lookup_pattern = "^@[0-9]+[[:space:]]{$type}[[:space:]].*[[:space:]]log[[:space:]].*[[:space:]]ridentifier[[:space:]]{$trackernum}";
1245
	}
1246

    
1247
	/* At the moment, miniupnpd is the only thing I know of that
1248
	   generates logging rdr rules */
1249
	unset($buffer);
1250
	if ($type == "rdr") {
1251
		$_gb = exec("/sbin/pfctl -vvPsn -a \"miniupnpd\" | /usr/bin/egrep " . escapeshellarg("^@{$rulenum}"), $buffer);
1252
	} else {
1253
		$_gb = exec("/sbin/pfctl -vvPsr | /usr/bin/egrep " . escapeshellarg($lookup_pattern), $buffer);
1254
	}
1255
	if (is_array($buffer)) {
1256
		return $buffer[0];
1257
	}
1258

    
1259
	return "";
1260
}
1261

    
1262
function buffer_rules_load() {
1263
	global $g, $buffer_rules_rdr, $buffer_rules_normal;
1264
	unset($buffer, $buffer_rules_rdr, $buffer_rules_normal);
1265
	/* Redeclare globals after unset to work around PHP */
1266
	global $buffer_rules_rdr, $buffer_rules_normal;
1267
	$buffer_rules_rdr = array();
1268
	$buffer_rules_normal = array();
1269

    
1270
	$_gb = exec("/sbin/pfctl -vvPsn -a \"miniupnpd\" | /usr/bin/grep '^@'", $buffer);
1271
	if (is_array($buffer)) {
1272
		foreach ($buffer as $line) {
1273
			list($key, $value) = explode (" ", $line, 2);
1274
			$buffer_rules_rdr[$key] = $value;
1275
		}
1276
	}
1277

    
1278
	$rules = pfSense_get_pf_rules();
1279
	if (is_array($rules)) {
1280
		foreach ($rules as $rule) {
1281
			$key = sprintf("%d", $rule['tracker']);
1282
			$buffer_rules_normal[$key] = is_array($rule['labels']) ? array_shift($rule['labels']) : $rule['labels'];
1283
		}
1284
	}
1285
	unset($_gb, $buffer);
1286
}
1287

    
1288
function buffer_rules_clear() {
1289
	unset($GLOBALS['buffer_rules_normal']);
1290
	unset($GLOBALS['buffer_rules_rdr']);
1291
}
1292

    
1293
function find_rule_by_number_buffer($rulenum, $trackernum, $type) {
1294
	global $g, $buffer_rules_rdr, $buffer_rules_normal;
1295

    
1296
	if ($trackernum == "0") {
1297
		$lookup_key = "@{$rulenum}";
1298
	} else {
1299
		$lookup_key = $trackernum;
1300
	}
1301

    
1302
	if ($type == "rdr") {
1303
		$ruleString = $buffer_rules_rdr[$lookup_key];
1304
		//TODO: get the correct 'description' part of a RDR log line. currently just first 30 characters..
1305
		$rulename = substr($ruleString, 0, 30);
1306
	} else {
1307
		$ruleString = $buffer_rules_normal[$lookup_key];
1308
		$rulename = str_replace("USER_RULE: ", '<i class="fa-solid fa-user"></i> ', $ruleString);
1309
	}
1310
	return "{$rulename} ({$lookup_key})";
1311
}
1312

    
1313
function find_action_image($action) {
1314
	global $g;
1315
	if ((strstr(strtolower($action), "p")) || (strtolower($action) == "rdr")) {
1316
		return "fa-regular fa-circle-check";
1317
	} else if (strstr(strtolower($action), "r")) {
1318
		return "fa-regular fa-circle-xmark";
1319
	} else {
1320
		return "fa-solid fa-ban";
1321
	}
1322
}
1323

    
1324
/* AJAX specific handlers */
1325
function handle_ajax() {
1326
	if ($_REQUEST['lastsawtime'] && $_REQUEST['logfile']) {
1327

    
1328
		$lastsawtime = getGETPOSTsettingvalue('lastsawtime', null);
1329
		$logfile = getGETPOSTsettingvalue('logfile', null);
1330
		$nentries = getGETPOSTsettingvalue('nentries', null);
1331
		$type = getGETPOSTsettingvalue('type', null);
1332
		$filter = getGETPOSTsettingvalue('filter', null);
1333
		$interfacefilter = getGETPOSTsettingvalue('interfacefilter', null);
1334

    
1335
		if (!empty(trim($filter)) || is_numeric($filter)) {
1336
			$filter = json_decode($filter, true);	# Filter Fields Array or Filter Text
1337
		}
1338

    
1339
		/* compare lastsawrule's time stamp to filter logs.
1340
		 * afterwards return the newer records so that client
1341
		 * can update AJAX interface screen.
1342
		 */
1343
		$new_rules = "";
1344

    
1345
		$filterlog = conv_log_filter($logfile, $nentries, $nentries + 100, $filter, $interfacefilter);
1346

    
1347
		/* We need this to always be in forward order for the AJAX update to work properly */
1348
		/* Since the lines are in reverse order, flip them around if needed based on the user's preference */
1349
		# First get the "General Logging Options" (global) chronological order setting.  Then apply specific log override if set.
1350
		$reverse = config_path_enabled('syslog', 'reverse');
1351
		$specific_log = basename($logfile, '.log') . '_settings';
1352
		$cronorder = config_get_path("syslog/{$specific_log}/cronorder");
1353
		if ($cronorder == 'forward') {
1354
			$reverse = false;
1355
		}
1356
		if ($cronorder == 'reverse') {
1357
			$reverse = true;
1358
		}
1359

    
1360
		$filterlog = ($reverse) ? array_reverse($filterlog) : $filterlog;
1361

    
1362
		foreach ($filterlog as $log_row) {
1363
			$row_time = strtotime($log_row['time']);
1364
			if ($row_time > $lastsawtime) {
1365
				if ($log_row['proto'] == "TCP") {
1366
					$log_row['proto'] .= ":{$log_row['tcpflags']}";
1367
				}
1368

    
1369
				if ($log_row['act'] == "block") {
1370
					$icon_act = "fa-solid fa-times text-danger";
1371
				} else {
1372
					$icon_act = "fa-solid fa-check text-success";
1373
				}
1374

    
1375
				$btn = '<i class="' . $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>';
1376
				$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";
1377
			}
1378
		}
1379
		echo $new_rules;
1380
		exit;
1381
	}
1382
}
1383

    
1384
/* Compatibility stubs for old clog functions until packages catch up.
1385
 * Remove once packages all use the new function names. */
1386
function dump_clog_no_table($logfile, $tail, $withorig = true, $grepfor = "", $grepinvert = "") {
1387
	return dump_log($logfile, $tail, $withorig, $grepfor, $grepinvert, $format = 'notable');
1388
}
1389
function dump_log_no_table($logfile, $tail, $withorig = true, $grepfor = "", $grepinvert = "") {
1390
	return dump_log($logfile, $tail, $withorig, $grepfor, $grepinvert, $format = 'notable');
1391
}
1392
function dump_clog($logfile, $tail, $withorig = true, $grepfor = "", $grepinvert = "") {
1393
	return dump_log($logfile, $tail, $withorig, $grepfor, $grepinvert);
1394
}
1395
function return_clog($logfile, $tail, $withorig = true, $grepfor = "", $grepinvert = "", $grepreverse = false) {
1396
	return dump_log($logfile, $tail, $withorig, $grepfor, $grepinvert, $format = 'none', $grepreverse);
1397
}
1398
function return_log($logfile, $tail, $withorig = true, $grepfor = "", $grepinvert = "", $grepreverse = false) {
1399
	return dump_log($logfile, $tail, $withorig, $grepfor, $grepinvert, $format = 'none', $grepreverse);
1400
}
(49-49/61)