Log.pm 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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. =head3 configuring retention
  32. The audit log is quite likely to have very limited retention.
  33. This is configured in the max_log_file and num_logs parameter of /etc/auditd/audit.conf
  34. You will only have max_log_file * num_logs MB of events stored, so plan according to how much you need to watch.
  35. Your specific use case should be observed, and tuned accordingly.
  36. For example, the average audit log line is ~200 bytes, so you can get maybe 40k entries per log at max_log_file=8.
  37. Each file action is (worst case) 5 lines in the log, resulting in maybe 8k file modifications per 8MB logfile.
  38. As such, stashing results or watching very tightly around blocks of functionality is highly recommended.
  39. Especially in situations such as public servers which are likely to get a large amount of SSH bounces recorded in the log by default.
  40. =cut
  41. sub new {
  42. my ($class, $path, @returning) = @_;
  43. $path = '/var/log/audit/audit.log' unless $path;
  44. die "Cannot access $path" unless -f $path;
  45. return bless({ path => $path, returning => \@returning}, $class);
  46. }
  47. =head1 METHODS
  48. =head2 search(key => constraint) = ARRAY[HashRef{}]
  49. Searches the log for lines where the value corresponding to the provided key matches the constraint, which is expected to be a quoted regex.
  50. If no constraints are provided, all matching rows will be returned.
  51. Example:
  52. my $rows = $parser->search( type => qr/path/i, nametype=qr/delete|create|normal/i );
  53. The above effectively will get you a list of all file modifications/creations/deletions in watched directories.
  54. Adds in a 'line' parameter to rows returned in case you want to know which line in the log it's on.
  55. Also adds a 'timestamp' parameter, since this is a parsed parameter.
  56. =head3 Speeding it up: by event
  57. Auditd logs are also structured in blocks separated between SYSCALL lines, which are normally filtered by 'key', which corresponds to rule name.
  58. We can speed up processing by ignoring events of the incorrect key.
  59. Example:
  60. my $rows = $parser->search( type => qr/path/i, nametype=qr/delete|create|normal/i, key => qr/backup_watch/i );
  61. The above will ignore events from all rules save those from the "backup_watch" rule.
  62. =head3 Speeding it up: by timeframe
  63. Auditd log rules also print a timestamp, which means we need a numeric comparison.
  64. Pass in 'older' and 'newer', and we can filter out things appropriately.
  65. Example:
  66. # Get all records that are from the last 24 hours
  67. my $rows = $parser->search( type => qr/path/i, nametype=qr/delete|create|normal/i, newer => ( time - 86400 ) );
  68. =head3 Getting full paths with CWDs
  69. PATH records don't actually store the full path to what is acted upon unless the process acting upon it used an absolute path.
  70. Thankfully, SYSCALL records are are always followed by a CWD record. As such we add the 'cwd' field to all subsequent records.
  71. As such, you can build full paths like so:
  72. my $parser = Audit::Log->new(undef, 'name', 'cwd');
  73. my $rows = $parser->search( type => qr/path/i, nametype=qr/delete|create|normal/i );
  74. my @full_paths = map { "$_->{cwd}/$_->{name}" } @$rows;
  75. =head3 Filtering by command
  76. 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.
  77. Example of getting all the commands run which triggered audit events:
  78. my $parser = Audit::Log->new(undef, 'exe')
  79. my $rows = $parser->search();
  80. =cut
  81. sub search {
  82. my ($self,%options) = @_;
  83. my $ret = [];
  84. my $in_block = 1;
  85. my $line = -1;
  86. my ($cwd, $exe, $comm) = ('','','');
  87. open(my $fh, '<', $self->{path});
  88. LINE: while (<$fh>) {
  89. next if index( $_, 'SYSCALL') < 0 && !$in_block;
  90. # I am trying to cheat here to snag the timestamp.
  91. my $msg_start = index($_, 'msg=audit(') + 10;
  92. my $msg_end = index($_, ':');
  93. my $timestamp = substr($_, $msg_start, $msg_end - $msg_start);
  94. next if $options{older} && $timestamp > $options{older};
  95. next if $options{newer} && $timestamp < $options{newer};
  96. # Snag CWDs
  97. if ( index( $_, 'type=CWD') == 0) {
  98. my $cwd_start = index($_, 'cwd="') + 5;
  99. my $cwd_end = index($_, "\n") - 1;
  100. $cwd = substr($_, $cwd_start, $cwd_end - $cwd_start);
  101. $line++;
  102. next;
  103. }
  104. # Replace GROUP SEPARATOR usage with simple spaces
  105. s/[\x1D]/ /g;
  106. my %parsed = map {
  107. my @out = split(/=/, $_);
  108. shift @out, join('=',@out)
  109. } grep { $_ } map {
  110. my $subj = $_;
  111. $subj =~ s/"//g;
  112. chomp $subj;
  113. $subj
  114. } split(/ /,$_);
  115. $line++;
  116. $parsed{line} = $line;
  117. $parsed{timestamp} = $timestamp;
  118. $parsed{cwd} = $cwd;
  119. $parsed{exe} //= $exe;
  120. $parsed{comm} //= $comm;
  121. if (exists $options{key} && $parsed{type} eq 'SYSCALL') {
  122. $in_block = $parsed{key} =~ $options{key};
  123. $exe = $parsed{exe};
  124. $comm = $parsed{comm};
  125. $cwd = '';
  126. next unless $in_block;
  127. }
  128. # Check constraints BEFORE filtering returned values, this is a WHERE clause
  129. CONSTRAINT: foreach my $constraint (keys(%options)) {
  130. next CONSTRAINT if !exists $parsed{$constraint};
  131. next LINE if $parsed{$constraint} !~ $options{$constraint};
  132. }
  133. # Filter fields for RETURNING clause
  134. if (@{$self->{returning}}) {
  135. foreach my $field (keys(%parsed)) {
  136. delete $parsed{$field} unless grep { $field eq $_ } @{$self->{returning}};
  137. }
  138. }
  139. push(@$ret,\%parsed);
  140. }
  141. close($fh);
  142. return $ret;
  143. }
  144. 1;