Log.pm 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. package Audit::Log;
  2. use strict;
  3. use warnings;
  4. use 5.006;
  5. use v5.12.0; # Before 5.006, v5.10.0 would not be understood.
  6. # ABSTRACT: auditd log parser with no external dependencies, using no perl features past 5.12
  7. =head1 WHY
  8. I had to do reporting for non-incremental backups.
  9. I needed something faster than GNU find, and which took less memory as well.
  10. I didn't want to stat 1M+ files.
  11. Just reads a log and keeps the bare minimum useful information.
  12. You can use auditd for a number of other interesting purposes, which this should support as well.
  13. =head1 SYNOPSIS
  14. my $parser = Audit::Log->new();
  15. my $rows = $parser->search(
  16. type => qr/path/i,
  17. nametype => qr/delete|create|normal/i,
  18. name => qr/somefile.txt/i,
  19. );
  20. =head1 CONSTRUCTOR
  21. =head2 new(STRING path, ARRAY returning) = Audit::Log
  22. Opens the provided audit log path when searching, or
  23. /var/log/audit/audit.log
  24. if none is provided.
  25. Also can filter returned keys by the provided array to not allocate unnecesarily in low mem situations.
  26. =head3 using with ausearch
  27. It's common to have the audit log be quite verbose, and log-rotated.
  28. To get around that you can dump pieces of the audit log as appropriate with ausearch.
  29. Here's an example of dumping keyed events for the last day, which you could then load into new().
  30. ausearch --raw --key backupwatch -ts `date --date yesterday '+%x'` > yesterdays-audit.log
  31. Even then the audit log is quite likely to only have a few days of retention.
  32. Be sure to stash results appropriately.
  33. =cut
  34. sub new {
  35. my ($class, $path, @returning) = @_;
  36. $path = '/var/log/audit/audit.log' unless $path;
  37. die "Cannot access $path" unless -f $path;
  38. return bless({ path => $path, returning => \@returning}, $class);
  39. }
  40. =head1 METHODS
  41. =head2 search(key => constraint) = ARRAY[HashRef{}]
  42. Searches the log for lines where the value corresponding to the provided key matches the constraint, which is expected to be a quoted regex.
  43. If no constraints are provided, all matching rows will be returned.
  44. Example:
  45. my $rows = $parser->search( type => qr/path/i, nametype=qr/delete|create|normal/i );
  46. The above effectively will get you a list of all file modifications/creations/deletions in watched directories.
  47. Adds in a 'line' parameter to rows returned in case you want to know which line in the log it's on.
  48. Also adds a 'timestamp' parameter, since this is a parsed parameter.
  49. =head3 Speeding it up: by event
  50. Auditd logs are also structured in blocks separated between SYSCALL lines, which are normally filtered by 'key', which corresponds to rule name.
  51. We can speed up processing by ignoring events of the incorrect key.
  52. Example:
  53. my $rows = $parser->search( type => qr/path/i, nametype=qr/delete|create|normal/i, key => qr/backup_watch/i );
  54. The above will ignore events from all rules save those from the "backup_watch" rule.
  55. =head3 Speeding it up: by timeframe
  56. Auditd log rules also print a timestamp, which means we need a numeric comparison.
  57. Pass in 'older' and 'newer', and we can filter out things appropriately.
  58. Example:
  59. # Get all records that are from the last 24 hours
  60. my $rows = $parser->search( type => qr/path/i, nametype=qr/delete|create|normal/i, newer => ( time - 86400 ) );
  61. =head3 Getting full paths with CWDs
  62. PATH records don't actually store the full path to what is acted upon unless the process acting upon it used an absolute path.
  63. Thankfully, SYSCALL records are are always followed by a CWD record. As such we add the 'cwd' field to all subsequent records.
  64. As such, you can build full paths like so:
  65. my $parser = Audit::Log->new(undef, 'name', 'cwd');
  66. my $rows = $parser->search( type => qr/path/i, nametype=qr/delete|create|normal/i );
  67. my @full_paths = map { "$_->{cwd}/$_->{name}" } @$rows;
  68. =head3 Filtering by command
  69. SYSCALL records store the command which executed the call. This is exposed as part of the parse for each child record, such as PATH or DAEMON_* records.
  70. Example of getting all the commands run which triggered audit events:
  71. my $parser = Audit::Log->new(undef, 'exe')
  72. my $rows = $parser->search();
  73. =cut
  74. sub search {
  75. my ($self,%options) = @_;
  76. my $ret = [];
  77. my $in_block = 1;
  78. my $line = -1;
  79. my ($cwd, $exe, $comm) = ('','','');
  80. open(my $fh, '<', $self->{path});
  81. LINE: while (<$fh>) {
  82. next if index( $_, 'SYSCALL') < 0 && !$in_block;
  83. # I am trying to cheat here to snag the timestamp.
  84. my $msg_start = index($_, 'msg=audit(') + 10;
  85. my $msg_end = index($_, ':');
  86. my $timestamp = substr($_, $msg_start, $msg_end - $msg_start);
  87. next if $options{older} && $timestamp > $options{older};
  88. next if $options{newer} && $timestamp < $options{newer};
  89. # Snag CWDs
  90. if ( index( $_, 'type=CWD') == 0) {
  91. my $cwd_start = index($_, 'cwd="') + 5;
  92. my $cwd_end = index($_, "\n") - 1;
  93. $cwd = substr($_, $cwd_start, $cwd_end - $cwd_start);
  94. $line++;
  95. next;
  96. }
  97. # Replace GROUP SEPARATOR usage with simple spaces
  98. s/[\x1D]/ /g;
  99. my %parsed = map {
  100. my @out = split(/=/, $_);
  101. shift @out, join('=',@out)
  102. } grep { $_ } map {
  103. my $subj = $_;
  104. $subj =~ s/"//g;
  105. chomp $subj;
  106. $subj
  107. } split(/ /,$_);
  108. $line++;
  109. $parsed{line} = $line;
  110. $parsed{timestamp} = $timestamp;
  111. $parsed{cwd} = $cwd;
  112. $parsed{exe} //= $exe;
  113. $parsed{comm} //= $comm;
  114. if (exists $options{key} && $parsed{type} eq 'SYSCALL') {
  115. $in_block = $parsed{key} =~ $options{key};
  116. $exe = $parsed{exe};
  117. $comm = $parsed{comm};
  118. $cwd = '';
  119. next unless $in_block;
  120. }
  121. # Check constraints BEFORE filtering returned values, this is a WHERE clause
  122. CONSTRAINT: foreach my $constraint (keys(%options)) {
  123. next CONSTRAINT if !exists $parsed{$constraint};
  124. next LINE if $parsed{$constraint} !~ $options{$constraint};
  125. }
  126. # Filter fields for RETURNING clause
  127. if (@{$self->{returning}}) {
  128. foreach my $field (keys(%parsed)) {
  129. delete $parsed{$field} unless grep { $field eq $_ } @{$self->{returning}};
  130. }
  131. }
  132. push(@$ret,\%parsed);
  133. }
  134. close($fh);
  135. return $ret;
  136. }
  137. 1;