# Security concerns with locking files

I'm writing a perl script which reads logs from a file and looks for matches from another file before sending the matches off by email. The problem is, I'm dealing with files which could be changed (a log written to them by syslog) at any time. I discovered that files can be locked in perl, however I'm not sure if it is 100% secure yet. Here is the pertinent snippet:

    # Check for valid email
unless ($mailto =~ EMAIL_REGEX) { die "Please supply a valid email" } # Build a rule from a key and an email # Write it to LOGMAN_CONF my$key_and_email = $keyword.":".$mailto."\n";
open (RULES, ">>", LOGMAN_CONF)
or die "Cannot open logman configuration file ".LOGMAN_CONF;
flock(RULES, LOCK_EX) or die "Can't lock ".LOGMAN_CONF;
print RULES $key_and_email; close RULES; # Check if CRONTAB_LOC needs a send entry open (CRON, "<", CRONTAB_LOC) or die "Cannot open crontab file ".CRONTAB_LOC; flock(CRON, LOCK_SH) or die "Can't lock ".CRONTAB_LOC; my @cronLines = <CRON>; close CRON; my$match = 0;
foreach my $line (@cronLines) { if ($line eq CRON_ENTRY) {
$match = 1; } } unless ($match == 1) {
open (CRON, ">>", CRONTAB_LOC)
or die "Cannot open crontab file ".CRONTAB_LOC;
flock(CRON, LOCK_EX) or die "Can't lock ".CRONTAB_LOC;
print CRON CRON_ENTRY;
close CRON;
}


Feel free to critique my style or structure, as this is my first contact with Perl.

NB: There are a couple of constants used above which I haven't shown where they are defined. I could add them if anyone needs, but they are for the most part location to files.

Locking is advisory which mean unless syslog is also doing flock() before write (which is doubtful) your locking scheme will have no effect. Some operating systems like AIX do have manditory/enforced locking mechanisms but I don't believe they're standard at the filesystem level across any UNIX system.

• Is there a way of knowing for sure if syslog flock()'s? I checked the man page and there was nothing that would indicate that it did or didn't. – n0pe Aug 18 '11 at 21:20
• Test it. Write a perl app the flocks() the file and just waits forever. If you see new log lines appear then syslog doesn't use flock(). – bot403 Aug 18 '11 at 21:44
• I'm on OpenSuse and they don't use syslog for logging. So I'll have to try this tomorrow at work. – n0pe Aug 18 '11 at 22:01