Work at SourceForge, help us to make it a better place! We have an immediate need for a Support Technician in our San Francisco or Denver office.

Close

script for archiving

BASE-user
grocanar
2010-04-16
2013-06-03
  • grocanar
    grocanar
    2010-04-16

    Hi

    I m wondering if someone has already a script for archiving all alerts that are more then 7 days old?
    it would be nice to speed up BASE.

     
  • kryptikET
    kryptikET
    2010-07-26

    There used to be a script called archivesnort.pl.  I searched for it and wasn't able to find it on the web anymore…here's my copy + quick instructions for debian/mysql
    1. Create dir archiveSnort where you have mysql installed (e.g. mkdir /var/lib/mysql/archiveSnort)
    2. create 2 files in directory  touch /var/lib/mysql/archiveSnort/archiveSnort.pl; touch /var/lib/mysql/archiveSnort/archiveSnort.config
    3. copy text from below into files
    4. modfiy /var/lib/mysql/archiveSnort/archiveSnort.config to reflect the appropriate values for user, passwd, db and archive db.
    5. chown mysql:mysql -R /var/lib/mysql/archiveSnort
    6. Run it using

    perl /var/lib/mysql/archiveSnort/archiveSnort.pl -c /var/lib/mysql/archiveSnort/archiveSnort.config -m 2
    

    command.

    archiveSnort.pl

      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
    #!/usr/bin/perl
    # ***************************************************************************
    # *   Copyright (C) 2007 by Dominik Strnad                                  *
    # *   dominik.strnad@unhfree.net                                            *
    # *                                                                         *
    # *   This program 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.                                   *
    # *                                                                         *
    # *   This program 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 this program; if not, write to the                         *
    # *   Free Software Foundation, Inc.,                                       *
    # *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
    # ***************************************************************************
    # This code take huge inpiration in original archivePlus.pl script by
    # Mike Griego and Paul Schmehl, University of Texas at Dallas and
    # John Bradberry, The Greentree Group.
    # Altought it was heavily overwritten, it can contains parts of original code.
    # These part are under copyright of the coresponding authors.
    # Original code unfortunatelly missed clear license conditions.
    use strict;
    use DBI;
    use Getopt::Long;
    Getopt::Long::Configure("no_ignore_case");
    use vars qw( %cfg %opt $dbh_snort $dbh_arch @event_tables @static_tables @acid_tables $sid $archivedate %control );
    # Set this value if you want to use an arbitrary date instead of N days
    # and don't forget to uncomment it :-):
    # $archivedate = qq{2003-05-06};
    @event_tables = ("data","icmphdr","iphdr", "opt","tcphdr","udphdr","signature","event");
    @static_tables = ("reference","reference_system","sensor","sig_class","sig_reference");
    @acid_tables = ("acid_event","acid_ip_cache");
    %cfg = (
            "config"        => "/etc/snort/archive_snort.cfg",
            "log"           => "/var/log/archive_snort.log",
            "flock"         => 1,
            "days"          => 7,
            "mode"          => 1,
            "sensor"        => "all",
            "pdbuser"       => undef,
            "pdbpass"       => undef,
            "pdb"           => undef,
            "pdbhost"       => undef,
            "pdbport"       => 3306,
            "adbuser"       => undef,
            "adbpass"       => undef,
            "adb"           => undef,
            "adbhost"       => undef,
            "adbport"       => 3306,
    );
    %opt = ('config' => \$cfg{"config"});
    unless ( GetOptions ( \%opt, 'config|c=s', 'log|l=s', 'days|t=i', 'mode|m=i', 'sensor|i=s',
                                'pdbuser|u=s', 'pdbpass|p=s', 'pdb|d=s', 'pdbhost|h=s', 'pdbport|s=i',
                                'adbuser|U=s', 'adbpass|P=s', 'adb|D=s', 'adbhost|H=s', 'adbport|S=i'
            ) ) {
        &usage;
    }
    if ( $cfg{"config"} and -f $cfg{"config"} ) {
        unless( open( CONFIG, $cfg{"config"} ) ) {
            die "Cannot open ".$cfg{"config"}.": $!\n";
        }
        my $line;
        while ( $line = <CONFIG> ) {
            chomp $line;
            if ( $line =~ /^#/ ) { next; }
            if ( $line =~ /^\s*(\w+)\s*\=\s*(\S+)\s*$/ ) {
                if ( exists( $cfg{$1} ) ) {
                    $cfg{$1} = $2;
                } else {
                    print "Unknown parameter: $line \n";
                    &usage;
                }
            }
        }
        close (CONFIG);
    }
    foreach my $key ( keys %opt ) {
        $cfg{$key} = $opt{$key};
    }
    unless ( $cfg{"mode"} =~ /^\d$/ ) {
        &usage;
    }
    if ( $cfg{"mode"} >= 1 and $cfg{"mode"} <= 3 ) {
        foreach my $key qw( pdbuser pdbpass pdb pdbhost pdbport ) {
            unless( exists( $cfg{$key} ) and $cfg{$key} ) {
                print "Required option $key not defined! \n";
                &usage;
            }
        }
    }
    if ( $cfg{"mode"} == 1 or $cfg{"mode"} == 2 or $cfg{"mode"} == 4 ) {
        foreach my $key qw( adbuser adbpass adb adbhost adbport ) {
            unless( exists( $cfg{$key} ) and $cfg{$key} ) {
                print "Required option $key not defined! \n";
                &usage;
            }
        }
    }   
    # put archivedate in mysql format (year-month-day)
    unless( $archivedate ) {
        # decide what archive age is (86400 is number of seconds in one day)
        unless ( $cfg{"days"} =~ /^\d+$/ ) {
            print "Option Days must be numeric!";
            &usage;
        }
        my @archivedate = localtime(time() - (86400 * $cfg{"days"}));
        # month is 0-based, so add one
        $archivedate[4] += 1;
        # year is 1900-based, so add 1900
        $archivedate[5] += 1900;
        $archivedate = "$archivedate[5]-$archivedate[4]-$archivedate[3]";
    }
    &logging("--------------- SCRIPT STARTED ---------------");
    &logging("Archive date is set to $archivedate");
    # disable the attributes for the database handles
    # to turn off error checking initially
    my %attr = ( PrintError => 0, RaiseError => 0, AutoCommit => 0 );
    # If you need to troubleshoot, uncomment the next two lines
    # This will create a trace.out file with a debug trace of
    # the script in the $tmp directory.
    # Tail should show you want went wrong
    #system("rm -f $tmp/trace.out");
    #DBI->trace (3, "$tmp/trace.out");
    # use the database type and database name for your setup
    my $snort_dsn = "DBI:mysql:".$cfg{"pdb"}.";".$cfg{"pdbhost"}.";".$cfg{"pdbport"};
    my $arch_dsn = "DBI:mysql:".$cfg{"adb"}.";".$cfg{"adbhost"}.";".$cfg{"adbport"};
    # connect to the snort database
    unless ( $dbh_snort = DBI->connect($snort_dsn, $cfg{"pdbuser"}, $cfg{"pdbpass"}, \%attr ) ) {
        &logging("Can't connect to snort database: $DBI::errstr.");
        exit 1;
    }
    # connect to the archive database
    until ( $dbh_arch = DBI->connect($arch_dsn, $cfg{"adbuser"}, $cfg{"adbpass"}, \%attr ) ) {
        &logging("Can't connect to archive database: $DBI::errstr.");
        exit 1;
    }
    $sid = &get_sensor( $cfg{"sensor"} );
    if ( not defined( $sid ) ) {
        &logging ("Unknown sensor name ".$cfg{"sensor"}."!");
        exit 1;
    }
    if ( $cfg{"mode"} == 1 or $cfg{"mode"} == 2 ) {
        &logging("Backup database ".$cfg{"pdb"}." events older than ".$cfg{"days"}." days.");
        foreach my $table ( @event_tables, @acid_tables, @static_tables ) {
            &logging("Table ".$cfg{"pdb"}.".$table backup started");
            my $time = time();
            if ( &backup_table( $table, $sid, $archivedate ) ) {
                $dbh_arch->rollback;
                &logging("Table ".$cfg{"pdb"}.".$table backup failed!");
                exit 1;
            }
            $dbh_arch->commit();
            $time = time() - $time;
            &logging("Table ".$cfg{"pdb"}.".$table backup completed in $time s");
            
        }
        &logging("Backup completed");
    }
    if ( $cfg{"mode"} == 2 or $cfg{"mode"} == 3 ) {
        &logging("Purge database ".$cfg{"pdb"}." events older than ".$cfg{"days"}." days.");
        foreach my $table ( @event_tables, @acid_tables ) {
            &logging("Table ".$cfg{"pdb"}.".$table purge started");
            my $time = time();
            if ( &delete_table( $table, $sid, $archivedate, $dbh_snort ) ) {
                $dbh_snort->rollback;
                &logging("Table ".$cfg{"pdb"}.".$table purge failed!");
                exit 1;
            }
            $time = time() - $time;
            &logging("Table ".$cfg{"pdb"}.".$table backup completed in $time s");
        }
        $dbh_snort->commit();
        &logging("Purge completed");
        &logging("Optimize database ".$cfg{"pdb"}." tables");
        foreach my $table ( @event_tables, @acid_tables ) {
        &logging("Table ".$cfg{"pdb"}.".$table optimization started");
        my $time = time();
        if ( &optimize_table( $table, $dbh_snort ) ) {
            &logging("Table ".$cfg{"pdb"}.".$table optimization failed!");
        }
        $time = time() - $time;
        &logging("Table ".$cfg{"pdb"}.".$table optimization completed in $time s");
        }
        &logging("Optimization completed");
    }
    if ( $cfg{"mode"} == 4 ) {
        &logging("Purge database ".$cfg{"adb"}." events older than ".$cfg{"days"}." days.");
        foreach my $table ( @event_tables, @acid_tables ) {
            &logging("Table ".$cfg{"adb"}.".$table purge started");
            my $time = time();
            if ( &delete_table( $table, $sid, $archivedate, $dbh_arch ) ) {
                $dbh_arch->rollback;
                &logging("Table ".$cfg{"adb"}.".$table purge failed!");
                exit 1;
            }
            $time = time() - $time;
            &logging("Table ".$cfg{"adb"}.".$table backup completed in $time s");
        }
        $dbh_arch->commit();
        &logging("Purge completed");
        &logging("Optimize database ".$cfg{"adb"}." tables");
        foreach my $table ( @event_tables, @acid_tables ) {
            &logging("Table ".$cfg{"adb"}.".$table optimization started");
        my $time = time();
        if ( &optimize_table( $table, $dbh_arch ) ) {
            &logging("Table ".$cfg{"adb"}.".$table optimization failed!");
        }
        $time = time() - $time;
        &logging("Table ".$cfg{"adb"}.".$table optimization completed in $time s");
        }
        &logging("Optimization completed");
    }
        
    $dbh_arch->disconnect();                    # disconnect from the archive database
    $dbh_snort->disconnect();                   # disconnect from the snort database
    &logging("-------- SCRIPT SUCCESFULLY TERMINATED --------");
    exit 0;
    # -------------------------------------------------------------------------
    # get sid of sensors name given to be archived
    sub get_sensor {
        my ( $sensorname ) = @_;
        my ( $sid );
        
        if ( $cfg{"sensor"} eq "all" ) {
            return 0;
        } else {
            $sid = ( $dbh_snort->selectrow_array("SELECT sid FROM sensor WHERE hostname ='$sensorname'") )[0];
            return $sid;
        }
    }
    # -------------------------------------------------------------------------
    # copy outdated records from production db into archive db
    sub backup_table {
        my ( $table, $sid, $date ) = @_;
        my ( $sql, $select, $insert, $fields, $pattern, $rows );
        
        $date = $dbh_snort->quote($date);
        
        if ( ( $table eq "event" or $table eq "acid_event" ) and $sid ) {
            $sql = "SELECT * FROM $table WHERE timestamp < $date AND sid = " . $dbh_snort->quote($sid);
        }
        elsif ( $table eq "event" or $table eq "acid_event" ) {
            $sql = "SELECT * FROM $table WHERE timestamp < $date";
        }
        elsif ( $table eq "acid_ip_cache" ) {
            $sql = "SELECT * FROM $table WHERE ipc_dns_timestamp < $date OR ipc_whois < $date OR ipc_whois_timestamp < $date";
        }
        elsif ( $table eq "signature" and $sid ) {
            $sql = "SELECT * FROM $table WHERE sig_id IN ( SELECT DISTINCT(signature) FROM event WHERE timestamp < $date AND sid = ". $dbh_snort->quote($sid) .")";
        }
        elsif ( $table eq "signature" ) {
            $sql = "SELECT * FROM $table WHERE sig_id IN ( SELECT DISTINCT(signature) FROM event WHERE timestamp < $date )";
        }
        elsif ( grep( $_ eq $table, @static_tables ) ) {
            $sql = "SELECT * FROM $table";
        }
        elsif ( $sid ) {
            $sql = "SELECT B.* FROM event AS A, $table AS B WHERE A.sid = B.sid AND A.cid = B.cid AND A.timestamp < $date AND A.sid = " . $dbh_snort->quote($sid);
        } else {
            $sql = "SELECT B.* FROM event AS A, $table AS B WHERE A.sid = B.sid AND A.cid = B.cid AND A.timestamp < $date";
        }
        
        unless( $select = $dbh_snort->prepare($sql) ) {
            &logging("Can't prepare SQL statement: SELECT * FROM $table " . $dbh_snort->errstr() );
            return 1;
        }
        unless( $select->execute() ) {
            &logging("Can't execute SQL statement: SELECT * FROM $table " . $dbh_snort->errstr() );
            return 1;   
        }
        
        $fields = $select->{NUM_OF_FIELDS};
        $pattern = "?," x $fields;
        chop($pattern);
        unless ( $pattern ) {
            &logging("Error in number of fields in table $table, does table exists or isn't too large?");
            return 1;
        }
        
        $sql = "REPLACE INTO $table VALUES($pattern)";
        unless( $insert = $dbh_arch->prepare($sql) ) {
            &logging("Can't prepare SQL statement: INSERT INTO $table " . $dbh_arch->errstr() );
            return 1;
        }
        
        unless ( $rows = $insert->execute_for_fetch( sub{ $select->fetchrow_arrayref } ) ) {
            &logging("Error when inserting into table $table " . $dbh_arch->errstr() );
            return 1;
        }
        &logging("Backuped $rows rows for table $table");
        $select->finish();
        $insert->finish();
        
        return 0;
    }
        
    # -------------------------------------------------------------------------
    # Delete outdated events from given table
    sub delete_table {
        my ( $table, $sid, $date, $dbh ) = @_;
        my ( $sql, $rows );
        
        $date = $dbh_snort->quote($date);
        
        if ( ( $table eq "event" or $table eq "acid_event" ) and $sid ) {
            $sql = "DELETE FROM $table WHERE timestamp < $date AND sid = " . $dbh_snort->quote($sid);
        }
        elsif ( $table eq "event" or $table eq "acid_event" ) {
            $sql = "DELETE FROM $table WHERE timestamp < $date";
        }
        elsif ( $table eq "acid_ip_cache" ) {
            $sql = "DELETE FROM $table WHERE ipc_dns_timestamp < $date OR ipc_whois < $date OR ipc_whois_timestamp < $date";
        }
        elsif ( $table eq "signature" ) {
            return 0;
        }
        elsif ( grep( $_ eq $table, @static_tables ) ) {
            return 0;
        }
        elsif ( $sid ) {
            $sql = "DELETE FROM B USING event AS A, $table AS B WHERE A.sid = B.sid AND A.cid = B.cid AND A.timestamp < $date AND A.sid = " . $dbh_snort->quote($sid);
        } else {
            $sql = "DELETE FROM B USING event AS A, $table AS B WHERE A.sid = B.sid AND A.cid = B.cid AND A.timestamp < $date";
        }
        $rows = $dbh->do($sql);
        if ( not defined( $rows ) ) {
            &logging("Error when deleting from table $table " . $dbh->errstr() );
            return 1;
        }
        &logging("Purged $rows rows for table $table");
        
        return 0;
    }
    sub optimize_table {
        my ( $table, $dbh ) = @_;
        my ( $sql );
        $sql = "optimize table $table";
        unless ( $dbh->do($sql) ) {
            &logging("Error when optimizing table $table " . $dbh->errstr() );
            return 1;
        }
        return 0;
    }
    # -------------------------------------------------------------------------
    # print script usage
    sub usage {
    print<<USAGE;
    Usage:  $0 [OPTIONS]
    '+' indicates a required option!
    -c FILE               Read options from FILE
    -d N days             Events older than N days will be archived [default is $cfg{"days"} days]
    -m MODE               Mode of operation. Can be one of following:
       1                  Archive events older than N days from production to archive db [default]
       2                  Archive events older than N days from production to archive db + delete them from production db
       3                  Delete events older than N days from production db
       4                  Delete events older than N days from archive db
    -i SENSOR             hostname of sensors to backup/delete [default is all]
    -u user      +        Production db user
    -p pass      +        Production db user pass
    -d db name   +        Production db name
    -h hostname  +        Production db IP host
    -s db port            Production db service port [default 3306]
    -U user      +        Archive db user
    -P pass      +        Archive db user pass
    -D db name   +        Archive db name
    -H hostname  +        Archive db IP host
    -S db port            Archive db service port [default 3306]
    USAGE
    exit 0;
    }
    # -------------------------------------------------------------------------
    # logging
    sub logging {
        my ( $message ) = @_;
        my ( $time, $i );
        if ( not open(LOG, ">>".$cfg{"log"}) ) {
            die "Cannot open log file ".$cfg{"log"};
        }
        $time = localtime(time);
        if ( $cfg{"flock"} ) { flock(LOG, 2); }
        print LOG "$time  \t $message \r\n";
        close(LOG);
    }
    

    archivesnort.config

    # Copyright (C) 2004 Paul L. Schmehl
    #
    # This program 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.
    #
    # This program 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 this program; if not, write to the Free Software
    # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
    # Configuration file for ACID archive utility
    # Archive events older than N days:
    days = 10
    # Production ACID db:
    pdbuser = <username>
    pdbpass = <password> 
    pdb = snort
    pdbhost = localhost
    pdbport = 3306
    # Archive db:
    adbuser = <username>
    adbpass = <password> 
    adb = snort_archive
    adbhost = localhost
    adbport = 3306
    ~