File: logcheck

package info (click to toggle)
logcheck 1.2.54
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 1,372 kB
  • ctags: 54
  • sloc: sh: 872; python: 158; perl: 138; makefile: 136
file content (791 lines) | stat: -rwxr-xr-x 21,409 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
#!/bin/bash
#
# Copyright (C) 2004-2006 Debian Logcheck Team 
#                         <logcheck-devel@alioth.lists.debian.org>
# Copyright (C) 2002,2003 Jonathan Middleton <jjm@ixtab.org.uk>
# Copyright (C) 1999-2002 Rene Mayrhofer <rmayr@debian.org>
# Copyright (C) 1996-1997 Craig Rowland <crowland@psionic.com>

# This file is part of Logcheck

# Logcheck is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# Logcheck is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with Logcheck; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

# $Id: logcheck,v 1.142 2006/07/06 10:16:42 ttroxell Exp $

if [ $UID == 0 ]; then
    echo "logcheck should not be run as root. Use su to invoke logcheck:"
    echo "su -s /bin/bash -c \"/usr/sbin/logcheck${@:+ $@}\" logcheck"
    echo "Or use sudo: sudo -u logcheck logcheck${@:+ $@}."
    # you may want to uncomment that hack to let logcheck invoke itself.
    # su -s /bin/bash -c "$0 $*" logcheck
    exit 1
fi

if [ ! -f /usr/bin/lockfile-create -o \
     ! -f /usr/bin/lockfile-remove -o \
     ! -f /usr/bin/lockfile-touch ]; then
    echo "fatal: lockfile-progs is a prerequisite for logcheck, and was not found."
    exit 1
fi

# Set the umask
umask 077

# Set the flag variables
SYSTEM=0
SECURITY=0
ATTACK=0

# Set the getopts string
GETOPTS="c:dhH:l:L:m:opr:RsS:tTuvw"

# Get the details for the email message
DATE="$(date +'%Y-%m-%d %H:%M')"
VERSION="1.2.45"

# Set the default report level
REPORTLEVEL="server"

# default to sent mails to local root
SENDMAILTO="root"

# Set the default subject lines
ATTACKSUBJECT="Security Alerts"
SECURITYSUBJECT="Security Events"
EVENTSSUBJECT="System Events"
ADDTAG="no"

# Set the default paths
RULEDIR="/etc/logcheck"
CONFFILE="/etc/logcheck/logcheck.conf"
STATEDIR="/var/lib/logcheck"
LOGFILES_LIST="/etc/logcheck/logcheck.logfiles"
LOGFILE_FALLBACK="/var/log/syslog"
LOGTAIL="/usr/sbin/logtail"
CAT="/bin/cat"
SYSLOG_SUMMARY="/usr/bin/syslog-summary"

# Set the options defaults
INTRO=1
LOGCHECKDEBUG=0
MAILOUT=0
NOCLEANUP=0
REBOOT=0
FQDN=0
SORTUNIQ=0
SUPPORT_CRACKING_IGNORE=0
SYSLOGSUMMARY=0
LOCKDIR=/var/lock/logcheck
LOCKFILE="$LOCKDIR/logcheck"

# Carry out the clean up tasks
cleanup() {

    if [ -n "$LOCK" ]; then
        debug "cleanup: Killing lockfile-touch - $LOCK"
	kill $LOCK && unset LOCK
    fi

    if [ -f "$LOCKFILE.lock" ]; then
        debug "cleanup: Removing lockfile: $LOCKFILE.lock"
	lockfile-remove $LOCKFILE
    fi

    if [ -d $TMPDIR ]; then
        # Remove the tmp directory
        if [ $NOCLEANUP -eq 0 ];then 
    	    cd /var/lib/logcheck
    	    debug "cleanup: Removing - $TMPDIR" 
    	    rm -r $TMPDIR
        else
    	    debug "cleanup: Not removing - $TMPDIR"
        fi
    fi
}

# Log debug output to standard error
debug() {
	if [ $LOGCHECKDEBUG -eq 1 ]; then
		echo "D: [$(date +%s)] $1" >&2 
	fi
}

# Add warning
warn () {
	message=$1
	debug "Warning - $message"

	if [ -d $TMPDIR ]; then
		echo "$message" >> $TMPDIR/warnings \
		  || error "Could not append to $TMPDIR/warnings."
	fi
	echo
	return 0
}

# Mail error message to sysadmin
error() {
    message=$1

    if [ "$2" = "noclean" ]; then
	debug "error: Not removing lockfile"
    else
        if [ -n "$LOCK" ]; then
	    debug "error: Killing lockfile-touch - $LOCK"
	    kill $LOCK && unset LOCK
	fi

       if [ -f "$LOCKFILE.lock" ]; then
           debug "error: Removing lockfile: $LOCKFILE.lock"
           lockfile-remove $LOCKFILE
       fi
	
    fi

    debug "Error: $message"

    if [ $MAILOUT -eq 0 ]; then
	{
	    cat<<EOF
Warning: If you are seeing this message, your log files may not have been
checked!

Details:
$message

${TMPDIR:+Check temporary directory: $TMPDIR
}
Also verify that the logcheck user can read all files referenced in
/etc/logcheck/logcheck.logfiles!

$(export)
EOF
	} | mail -s "Logcheck: $HOSTNAME $DATE exiting due to errors" \
	    "$SENDMAILTO"
    
    elif [ $MAILOUT -eq 1 ]; then
          {
	      echo "Error: $message."
	  }
    fi
    exit 1
}

# Add an identification line at the beginning of the sent mail
setintro() {
    if [ -f /etc/logcheck/header.txt -a -r /etc/logcheck/header.txt ] ; then
       $CAT /etc/logcheck/header.txt >> $TMPDIR/report \
           || error "Could not append header to $TMPDIR/report."
    fi
}


# Add a footer to the report.
setfooter() {
    if [ -f /etc/logcheck/footer.txt -a -r /etc/logcheck/footer.txt ] ; then
       $CAT /etc/logcheck/footer.txt >> $TMPDIR/report \
           || error "Could not append footer to $TMPDIR/report."
    fi
}


# Clean a directory (or single file) to a cleaned tmp version
# takes two args: directory and cleaned file
cleanrules() {
    dir=$1
    cleaned=$2

    if [ -d $dir ]; then 
        if [ ! -d $cleaned ]; then
	    mkdir $cleaned \
	        || error "Could not make dir $cleaned for cleaned rulefiles."
	fi
	for rulefile in $(run-parts --list $dir); do
	    rulefile=$(basename $rulefile)
	    if [ -f ${dir}/${rulefile} ]; then
		debug "cleanrules: ${dir}/${rulefile}"
		if [ -r ${dir}/${rulefile} ]; then
			# pipe to cat on greps to get usable exit status
			egrep --text -v '^[[:space:]]*$|^#' $dir/$rulefile | cat \
		    		>> $cleaned/$rulefile \
		    	|| error "Couldn't append to $cleaned/$rulefile."
		else
			error "Couldn't read $dir/$rulefile"
		fi
	    fi
	done
    elif [ -f $dir ]; then
	error "cleanrules: '$dir' is a file, not a directory"
    elif [ -z $dir ]; then
	error "cleanrules: called without argument"
    fi
}

# Add any events to the report
report() {
    if [ -s $TMPDIR/checked ]; then
	printheader "$*" >> $TMPDIR/report \
	    || error "Could not append to report."
	if [ $SYSLOGSUMMARY -eq 1 ] && [ -x $SYSLOG_SUMMARY ]; then
	    debug "report: running syslog-summary - $*"
	    $SYSLOG_SUMMARY $TMPDIR/checked | \
		egrep -v "^Summarizing " | cat >> $TMPDIR/report \
		    || error "Could not append to report."
	else
	    if [ $SYSLOGSUMMARY -eq 1 ] && [ ! -x $SYSLOG_SUMMARY ]; then
	    	debug "report : WARNING : can't exec $SYSLOG_SUMMARY. Running without summary"
	    fi
	    debug "report: cat'ing - $*"
	    cat $TMPDIR/checked >> $TMPDIR/report \
	        || error "Could not append to report."
	fi
	echo >> $TMPDIR/report \
	    || error "Could not append to report."
	return 0
    else
	return 1
    fi
}

# Add eventual section titles to the report
printheader() {
    char="="
    header="$1"
    number="$(echo $header | wc -c)"
    num=1
    line=""

    while [ "$num" -lt "$number" ]; do
        line="${line}${char}"
        if [ "$char" = "=" ]; then
            char="-"
        else
            char="="
        fi
        num=$(($num + 1))
    done
    echo "$header"
    echo "$line"
}

# Mail the report
sendreport() {
    if [ $REBOOT -eq 1 ]; then
	subject="Reboot: $HOSTNAME $DATE $*"
    else
	subject="$HOSTNAME $DATE $*"
    fi
    if [ $ADDTAG = "yes" ]; then
        subject="[logcheck] $subject"
    fi

    if [ $MAILOUT -eq 1 ]; then
	debug "Sending report to STDOUT"
	cat $TMPDIR/report
	debug "Sent report to STDOUT"
    else
	debug "Sending report: '$subject' to $SENDMAILTO"
	cat $TMPDIR/report | mail -s "$subject" "$SENDMAILTO"
    fi
}

# Clean the report to level for type
greplogoutput() {
    raise="$1"
    sectionstring="$2"
    ignore="$3"
    ignorehigher="$4"

    RETURN=1

    for grepfile in $(ls -1 $raise); do
	debug "greplogoutput: $grepfile"

	# Raise entries that match
	egrep --text -f $raise/$grepfile $TMPDIR/logoutput-sorted | cat \
	    > $TMPDIR/checked \
	    || error "Could not output to $TMPDIR/checked."

	# apply different ignore rules
	if [ -s $TMPDIR/checked ]; then
	    debug "greplogoutput: Entries in checked"
	    
	    if [ -n "$ignore" -a -f "$ignore/$(basename $grepfile)" ]; then
		cleanchecked "$ignore/$(basename $grepfile)"
	    fi

	    # quick and dirty fix for ignoring logcheck-foo files 
	    # in the case logcheck itself has no raised entry
	    if [ -n "$ignore" -a -f "$ignore/logcheck-$(basename $grepfile)" ]; then
		cleanchecked "$ignore/logcheck-$(basename $grepfile)"
	    fi
	    
	    # If it's the logcheck file, we do something special
	    if [ "$(basename $grepfile)" = "logcheck" ]; then 

		# Now ignore all entries from the ignore dir
		# old logcheck versions only ignored logcheck-<package> files
		if [ -n "$ignore" ]; then
		    debug "Applying Logcheck override files"
		    for file in $(ls -1 $ignore/) ; do
		        debug "clean logcheck-<package>: $file"
			cleanchecked "$ignore/$file"
		    done
		else
		    debug "No Logcheck override files" 
		fi
 
		debug "Cleaning logcheck"
		# Remove any entries already reported
		for file in $(ls $raise/ | grep -v '^logcheck') ; do
		    debug "Cleaning logcheck: $file"
		    cleanchecked "$raise/$file"
		done
	    fi

	    if [ -n "$ignorehigher" ]; then 
		if [ -d $ignorehigher -a -s $TMPDIR/checked ]; then
		    cleanchecked "$ignorehigher"
		fi
	    fi

	    # Apply local rules before we report
	    if [ -n "$ignore" ]; then
	        if [ -f $ignore/local -a -s $TMPDIR/checked ]; then
		    cleanchecked "$ignore/local"
	        fi

	        # Now apply any local-* files
	        for file in $(ls -1 $ignore/ | grep '^local-') ; do
	    	    cleanchecked "$ignore/$file"
	        done
	    fi

	    if [ "$(basename $grepfile)" = "logcheck" ]; then
		report "${sectionstring}" && RETURN=0
	    else
		report "${sectionstring} for $(basename $grepfile)" \
		    && RETURN=0
	    fi
	fi
    done
    debug "greplogoutput: returning $RETURN"
    return $RETURN
}

# Process a logfile snippet with egrep.
cleanchecked() {
    clean=$1

    if [ -f $clean ]; then 
	debug "cleanchecked - file: $clean"
        egrep --text -v -f $clean $TMPDIR/checked | cat >> $TMPDIR/checked.1  \
	    || error "Could not output to $TMPDIR/checked.1."
	mv $TMPDIR/checked.1 $TMPDIR/checked \
	    || error "Could not move $TMPDIR/checked.1 to $TMPDIR/checked"
    elif [ -d $clean ]; then
	debug "cleanchecked - dir - $clean"
	for file in $(ls -1 $clean/); do
	debug "cleanchecked - dir - $clean/$file"
	    egrep --text -v -f "$clean/$file" $TMPDIR/checked | cat \
		>> $TMPDIR/checked.1 \
		    || error "Could not output to TMPDIR/checked.1."
	    mv $TMPDIR/checked.1 $TMPDIR/checked \
	        || error "Could not move $TMPDIR/checked.1 to $TMPDIR/checked"
	done
    else
	error "cleanchecked: Not a file or a directory $clean"
    fi
}

# Get the yet unseen part of one logfile.
logoutput() {
    file=$1

    # There are some problems with this section.
    debug "logoutput called with file: $file"
    if [ -f "$file" ]; then
	offsetfile="$STATEDIR/offset$(echo $file | tr / .)"
	if [ -s "$offsetfile" -a -r "$offsetfile" ]; then
	    if [[ $(wc -c < "$file") -lt $(tail -n 1  "$offsetfile") ]]; then
	        # assume the log is rotated by savelog(8)
		# syslog-ng leaves old files here
		if [ -e "$file.0" -a "$file.0" -nt "$file.1.gz" ]; then
		    debug "Running logtail on rotated: $file.0"
		    $LOGTAIL -f "$file.0" -o "$offsetfile" $LOGTAIL_OPTS > \
			$TMPDIR/logoutput/$(basename "$file") 2>&1 \
			|| error "Could not run logtail or save output"
		    rm -f "$offsetfile" \
		        || error "Could not remove $offsetfile"
		# assume the log is rotated by logrotate(8)
		# should also probably check if file is still fresh
		elif [ -e "$file.1" ]; then
		    debug "Running logtail on rotated: $file.1"
		    $LOGTAIL -f "$file.1" -o "$offsetfile" $LOGTAIL_OPTS > \
			$TMPDIR/logoutput/$(basename "$file") 2>&1 \
			|| error "Could not run logtail or save output"
		    rm -f "$offsetfile" \
		        || error "Could not remove $offsetfile"
		fi
	    fi
	fi
	debug "Running logtail: $file"
	$LOGTAIL -f "$file" -o "$offsetfile" $LOGTAIL_OPTS \
	    >> $TMPDIR/logoutput/$(basename "$file") 2>&1 \
	    || error "Could not run logtail or save output"
    else
	echo "E: File could not be read: $file" >> $TMPDIR/errors \
	    || error "Could not output to $TMPDIR/errors."
    fi
}

# Show all the cli options to our users.
usage() {
    debug "usage: Printing usage and exiting"
    cat<<EOF
usage: logcheck [-c CFG] [-d] [-h] [-H HOST] [-l LOG] [-L CFG] [-m MAIL] [-o] 
                [-r DIR] [-s|-p|-w] [-R] [-S DIR] [-t] [-T] [-u]
 -c CFG       = override default configuration file
 -d           = debug mode
 -h           = print this usage information and exit
 -H HOST      = use this hostname in the subject of any generated mail
 -l LOG       = check the specified logfile
 -L CFG       = override default logfiles list
 -m MAIL      = send the report to the specified recipient
 -o           = send the report to stdout, no mail will be sent
 -p           = use the "paranoid" runlevel
 -r DIR       = override default rules directory
 -R           = adds "Reboot:" to email subject
 -s           = use the "server" runlevel
 -S DIR       = override default state directory
 -t           = testing mode, don't update the logfile offsets
 -T           = do not remove the TMPDIR 
 -u           = enable syslog-summary
 -v           = print version
 -w           = use the "workstation" runlevel
EOF
}

# Check the commandline options for a change to the config file option
while getopts $GETOPTS opt; do
    case "$opt" in
	c)
	    debug "Setting CONFFILE to $OPTARG"
	    CONFFILE="$OPTARG"
            if [ ! -r $CONFFILE ]; then
                 error "Config file $CONFFILE unreadable or does not exists"
            fi
	    ;;
	d)
	    LOGCHECKDEBUG=1
	    debug "Turning debug mode on"
	    ;;
	h)
	    usage
	    exit 0
	    ;;
	T)
	    debug "Setting NOCLEANUP to 1"
	    NOCLEANUP=1
	    ;;
	v)
	    echo "logcheck $VERSION"
	    exit 0
	    ;;
	\?)
	    usage
	    exit 1
	    ;;
    esac
done

# Now reset $OPTIND to 1 
OPTIND=1

debug "Sourcing - $CONFFILE"

# Now source the config file - before things that should not be changed
if [ -r $CONFFILE ]; then
	. $CONFFILE
elif [ -f $CONFFILE ]; then
	error  "Config file $CONFFILE could not be read"
fi

# Setup the compatibility for the old style of setting $INTRO
# And handle it being set to ""
if [ -z "$INTRO" ]; then
	INTRO=1
else
    if [ "$INTRO" = "no" ]; then
	INTRO=0
    elif [ "$INTRO" = "yes" ]; then
	INTRO=1
    fi
fi

# Use sort -u or -k 1,3 -s 
if [ $SORTUNIQ -eq 1 ];then
    SORT="sort -u"
else
    SORT="sort -k 1,3 -s"
fi

# Hostname either fully qualified or not.
if [ $FQDN -eq 1 ]; then
        HOSTNAME="$(hostname --fqdn)" > /dev/null 2>&1
else
        HOSTNAME="$(hostname --short)" > /dev/null 2>&1
fi
		
# Now check for the other options
while getopts $GETOPTS opt; do
    case "$opt" in
    	H)
	   debug "Setting HOSTNAME to $OPTARG"
	   HOSTNAME="$OPTARG"
	   ;;
	l)
	    debug "Setting LOGFILE to $OPTARG"
	    LOGFILE="$OPTARG"
	    ;;
	L)
	    debug "Setting LOGFILES_LIST to $OPTARG"
	    LOGFILES_LIST="$OPTARG"
	    ;;
	m)
	    debug "Setting SENDMAILTO to $OPTARG"
	    SENDMAILTO="$OPTARG"
	    ;;
	o)
	    debug "Setting MAILOUT to 1"
	    MAILOUT="1"
	    ;;
	p)
	    debug "Setting REPORTLEVEL to paranoid"
	    REPORTLEVEL="paranoid"
	    ;;
	r)
	    debug "Setting RULEDIR to $OPTARG"
	    RULEDIR="$OPTARG"
	    ;;
	R)
	    debug "Setting REBOOT to 1"
	    REBOOT=1
	    ;;
	s)
	    debug "Setting REPORTLEVEL to server"
	    REPORTLEVEL="server"
	    ;;
	S)
	    debug "Setting STATEDIR to $OPTARG"
	    STATEDIR="$OPTARG"
	    ;;
	u)
	    debug "Setting SYSLOGSUMMARY to 1"
	    SYSLOGSUMMARY="1"
	    ;;
	t)
	    debug "Setting LOGTAIL_OPTS to -t"
	    LOGTAIL_OPTS=' -t'
	    ;;
	w)
	    debug "Setting REPORTLEVEL to workstation"
	    REPORTLEVEL="workstation"
	    ;;
	\?)
	    usage
	    exit 1
	    ;;
    esac
done
debug "Finished getopts $GETOPTS"
shift `expr $OPTIND - 1`

if [ $REPORTLEVEL = "workstation" ]; then
    REPORTLEVELS="workstation server paranoid"
elif [ $REPORTLEVEL = "server" ]; then
    REPORTLEVELS="server paranoid"
elif [ $REPORTLEVEL = "paranoid" ]; then
    REPORTLEVELS="paranoid"
else
    error "REPORTLEVEL is set to an unknown value" "noclean"
fi

trap 'cleanup' 0

debug "Trying to get lockfile: $LOCKFILE.lock"
if [ ! -d $LOCKDIR ]; then 
	mkdir -m 0755 $LOCKDIR
fi
lockfile-create --retry 1 $LOCKFILE > /dev/null 2>&1


if [ $? -eq 1 ]; then 
    trap 0
    error "Failed to get lockfile: $LOCKFILE.lock" "noclean"
else 
    debug "Running lockfile-touch $LOCKFILE.lock"
    lockfile-touch $LOCKFILE &
    LOCK="$!"
fi

# Create the secure temporary directory or exit
TMPDIR=$(mktemp -d -p /tmp logcheck.XXXXXX) \
    || TMPDIR=$(mktemp -d -p /var/tmp logcheck.XXXXXX) \
    || error "Could not create temporary directory"

# Now clean the rulefiles in the directories
cleanrules "$RULEDIR/cracking.d" $TMPDIR/cracking
cleanrules "$RULEDIR/violations.d" $TMPDIR/violations
cleanrules "$RULEDIR/violations.ignore.d" $TMPDIR/violations-ignore

# Now clean the ignore rulefiles for the report levels
for level in $REPORTLEVELS; do 
    cleanrules "$RULEDIR/ignore.d.$level" $TMPDIR/ignore
done

# The following cracking.ignore directory will only be used if
# $SUPPORT_CRACKING_IGNORE is set to 1 in the configuration file.
# This is *only* for local admin use.
if [ $SUPPORT_CRACKING_IGNORE -eq 1 ]; then
    cleanrules "$RULEDIR/cracking.ignore.d" $TMPDIR/cracking-ignore
fi

# Get the list of log files from config file
# Handle log rotation correctly, idea taken from Wiktor Niesiobedzki.
mkdir $TMPDIR/logoutput \
    || error "Could not mkdir for log files"
if [ ! $LOGFILE ] && [ -r $LOGFILES_LIST ]; then
    for file in $(egrep --text -v "(^#|^[[:space:]]*$)" $LOGFILES_LIST); do
	logoutput "$file"
    done 
elif [ $LOGFILE ]; then
    if [ -f $LOGFILE ] && [ -r $LOGFILE ]; then
        logoutput "$LOGFILE"
    else
    	error "$LOGFILE don't exist or we do not have permissions to read it"
    fi
elif [ -r $LOGFILE_FALLBACK ]; then
        logoutput "$LOGFILE_FALLBACK"
else
    error "Gave up no Logfile exist or we do not have permissions to read it"
fi

# First sort the logs to remove duplicate lines (from different logfiles with
# the same lines) and reduce CPU and memory usage afterwards.
debug "Sorting logs"
$SORT $TMPDIR/logoutput/* | sed -e 's/[[:space:]]\+$//' | cat  \
    > $TMPDIR/logoutput-sorted \
        || error "Could not output to $TMPDIR/logoutput-sorted."
 

# See if the tmp file exists and actually has data to check,
# if it doesn't we should erase it and exit as our job is done.
if [ ! -s $TMPDIR/logoutput-sorted -a ! -f $TMPDIR/errors ]; then
    debug "Nothing to report"
    exit 0
elif [ ! -s $TMPDIR/logoutput-sorted -a -f $TMPDIR/errors ]; then
    error "$(cat $TMPDIR/errors)"
fi

if [ $INTRO -eq 1 ]; then
    debug "Setting the Intro"
    setintro
else
    debug "Not setting the Intro"
fi

if [ -f $TMPDIR/errors ]; then
    { 
	cat<<EOF

$(cat $TMPDIR/errors)

EOF
    } >> $TMPDIR/report \
    || error "Could not output to $TMPDIR/report."
fi

# Check for blatant cracking attempts
if [ -d $TMPDIR/cracking ]; then
    if [ $SUPPORT_CRACKING_IGNORE -eq 1 ]; then
	debug "Checking for security alerts and using cracking-ignore"
	if [ -d $TMPDIR/cracking-ignore ]; then
	    greplogoutput $TMPDIR/cracking "$ATTACKSUBJECT" \
		$TMPDIR/cracking-ignore && ATTACK="1"
	fi
    else
	debug "Checking for security alerts"
	greplogoutput $TMPDIR/cracking "$ATTACKSUBJECT" \
	    && ATTACK="1"
    fi
fi

# Check for security events
if [ -d $TMPDIR/violations ]; then
    debug "Checking for security events"
    rm -f $TMPDIR/checked 

    if [ $ATTACK -eq 1 ]; then
	greplogoutput $TMPDIR/violations "$SECURITYSUBJECT" \
	    $TMPDIR/violations-ignore $TMPDIR/cracking && SECURITY="1"
    else
	greplogoutput $TMPDIR/violations "$SECURITYSUBJECT" \
	    $TMPDIR/violations-ignore && SECURITY="1"
    fi
fi

# Do reverse grep on patterns we want to ignore
if [ -d $TMPDIR/ignore ]; then
    debug "Checking for system events"
    cp $TMPDIR/logoutput-sorted $TMPDIR/checked \
    || error "Could not copy $TMPDIR/logoutput-sorted to $TMPDIR/checked"
    cleanchecked $TMPDIR/ignore

    if [ -s $TMPDIR/checked ]; then
	debug "Removing alerts from system events"
	cleanchecked $TMPDIR/cracking
    fi
    if [ -s $TMPDIR/checked ]; then 	
	debug "Removing violations from system events"
	cleanchecked $TMPDIR/violations
    fi
    report "$EVENTSSUBJECT" && SYSTEM="1"
fi

# Add warnings to report
if [ -f $TMPDIR/warnings ]; then
	  printheader "Logcheck Warnings" >> $TMPDIR/report \
	  || error "Cannot append warnings to report."
	cat $TMPDIR/warnings >> $TMPDIR/report && echo >> $TMPDIR/report \
	  || error "Cannot append warnings to report."
fi

# Include the footer if present.
if [ $INTRO -eq 1 ]; then
    debug "Setting the footer text"
    setfooter
else
    debug "Not setting the footer text"
fi

# If there are results, mail them to sysadmin
if [ $ATTACK -eq 1 ]; then
    sendreport "$ATTACKSUBJECT"
elif [ $SECURITY -eq 1 ]; then
    sendreport "$SECURITYSUBJECT"
elif [ $SYSTEM -eq 1 ]; then
    sendreport "$EVENTSSUBJECT"
fi