From: Dinko Korunic Date: Thu, 15 Aug 2013 17:33:08 +0000 (+0200) Subject: Imported Upstream version 2.7 X-Git-Tag: upstream/2.7^0 X-Git-Url: http://ftp.carnet.hr/carnet-debian/scm?a=commitdiff_plain;h=6ef2f786c6c8ead94841b5f93baf9f43421f08c8;p=ossec-hids.git Imported Upstream version 2.7 --- diff --git a/.hg_archival.txt b/.hg_archival.txt index acdd63e..203a47d 100644 --- a/.hg_archival.txt +++ b/.hg_archival.txt @@ -1,5 +1,5 @@ repo: b55c69ab0638427c3307fb169a767b950530ce4a -node: 5afbec313087627a125241c880b8a03f819f714f +node: 10cc358d57a8cf57eb9c97c411cc2a118a3c14ac branch: default -latesttag: v2.5.0-beta1 -latesttagdistance: 21 +latesttag: 2.7-beta2 +latesttagdistance: 15 diff --git a/.hgignore b/.hgignore index 3605c11..1394769 100644 --- a/.hgignore +++ b/.hgignore @@ -5,6 +5,7 @@ syntax: glob *.o *.a *.dSYM +*.orig .hgignore # Auto generated build files @@ -44,6 +45,8 @@ src/client-agent/ossec-agentd src/logcollector/ossec-logcollector src/monitord/ossec-monitord src/monitord/ossec-reportd +src/os_auth/agent-auth +src/os_auth/ossec-authd src/os_csyslogd/ossec-csyslogd src/os_dbd/ossec-dbd src/os_execd/ossec-execd diff --git a/.hgtags b/.hgtags index f3a3aa6..bea110e 100644 --- a/.hgtags +++ b/.hgtags @@ -4,3 +4,8 @@ 7550abc82f5402592a646615f02fd698686de7bd OSSEC_HIDS_0_4 946d14c2b5ba7c21cd6eefe5f56f136df93f28a6 v1_1_0 8b7a8120903fe0e18fcd9a29897919669c46adfc v2.5.0-beta1 +6f9682e3e1492532e48455e6ca65ca27151f1931 AgentConfigProfile-beta +7f7d3ed19f558c985931a9b2734a6d5fabc42ab3 MultpileProfileWithOverwriting +3c4f446bab8d58b93c99e14276ec599319e61401 v2.6.0 Final plus enhancements +c1d1982737cb58bbffc9721f82c0532323f36bba v2.7-beta1 +39c20dca5873f178beb31168e79dcf654139e578 2.7-beta2 diff --git a/BUGS b/BUGS old mode 100755 new mode 100644 index 9cfc42a..bd4b5ac --- a/BUGS +++ b/BUGS @@ -1,5 +1,5 @@ -OSSEC v2.5.1 -Copyright (C) 2010 Trend Micro Inc. +OSSEC v2.7 +Copyright (C) 2012 Trend Micro Inc. ** Reporting bugs ** @@ -17,4 +17,4 @@ the following information: If you prefer to contact us privately or if it is a security -issue, send an e-mail to contact@ossec.net. +issue, send an e-mail to OSSEC Project ( ossecproject@gmail.com ). diff --git a/CONFIG b/CONFIG old mode 100755 new mode 100644 index 69a2c0a..68a7025 --- a/CONFIG +++ b/CONFIG @@ -1,5 +1,5 @@ -OSSEC v2.5.1 -Copyright (C) 2010 Trend Micro Inc. +OSSEC v2.7 +Copyright (C) 2012 Trend Micro Inc. = Information about OSSEC = @@ -16,4 +16,4 @@ See INSTALL Just follow the steps from the install.sh script. More information at -http://www.ossec.net/en/manual.html +http://www.ossec.net/doc/manual/index.html diff --git a/CONTRIBUTORS b/CONTRIBUTORS old mode 100755 new mode 100644 index 3f20e2a..a42fcbc --- a/CONTRIBUTORS +++ b/CONTRIBUTORS @@ -1,5 +1,5 @@ -# @(#) $Id$ -# +OSSEC v2.7 +Copyright (C) 2012 Trend Micro Inc. Many thanks to everyone who contributed and helped with the ossec project. Below is the list of all the people @@ -9,10 +9,21 @@ who helped us since our first release (0.1). -Development - Daniel B. Cid - Jeremy Rossi - - Stephen Kreusch + - Michael Starks + - Dan Parriott - Meir Michanie - Slava Semushin - Ahmet Ozturk + - Scott R. Shinn + - George Kargiotakis + - Jason Stelzer + - Xavier Mertens + - Stjepan Gros + - Brad Lhotsky + - cmlara + - Christian Gottsche (cgzones) + - Dominic + - JB Cheng -Testing/Patches and other contributions. @@ -26,6 +37,7 @@ who helped us since our first release (0.1). - Andre Alexandre Gaio - Liliane A. Cid - Marcus Maciel - + - Stephen Kreusch - Kayvan A. Sylvan - Dianzhi Wang - Meir Michanie @@ -36,13 +48,26 @@ who helped us since our first release (0.1). - Jorge Augusto Senger - ossec2mysql (contrib) - David J. Bianco - Ivan Lotina - - Michael Starks - Robert Millan [ackstorm] - Martin West - Rafael Capovilla + - Florian Crouzqat + - Danny Fullerton + - Jeremy Hanmer + - Pepe Sanz + - Kat Fitzgerald + - Regis Houssin + - carlopmart + - Ash Kumar -Translations + + -Dutch: + - Martijn de Boer - martijn ( at ) oceanius.com + + -Serbian: + - Maja Michanie - majam ( at ) riunx.com -Portuguese: - Daniel Barcellos diff --git a/INSTALL b/INSTALL old mode 100755 new mode 100644 index ffbb4f8..c44d292 --- a/INSTALL +++ b/INSTALL @@ -1,5 +1,5 @@ -OSSEC v2.5.1 -Copyright (C) 2009 Trend Micro Inc. +OSSEC v2.7 +Copyright (C) 2012 Trend Micro Inc. = Information about OSSEC = diff --git a/LICENSE b/LICENSE old mode 100755 new mode 100644 index b20bf9c..2652963 --- a/LICENSE +++ b/LICENSE @@ -1,10 +1,21 @@ - Copyright (C) 2010 Trend Micro Inc. All rights reserved. + Copyright (C) 2012 Trend Micro Inc. All rights reserved. OSSEC HIDS is a free software; you can redistribute it and/or modify it under the terms of the GNU General Public License (version 2) as published by the FSF - Free Software Foundation. + In addition, certain source files in this program permit linking with the + OpenSSL library (http://www.openssl.org), which otherwise wouldn't be allowed + under the GPL. For purposes of identifying OpenSSL, most source files giving + this permission limit it to versions of OpenSSL having a license identical to + that listed in this file (see section "OpenSSL LICENSE" below). It is not + necessary for the copyright years to match between this file and the OpenSSL + version in question. However, note that because this file is an extension of + the license statements of these source files, this file may not be changed + except with permission from all copyright holders of source files in this + program which reference this file. + Note that this license applies to the source code, as well as decoders, rules and any other data file included with OSSEC (unless otherwise specified). @@ -29,10 +40,23 @@ modules. Our interpretation refers only to OSSEC - we don't speak for any other GPL products. + * As a special exception, the copyright holders give + * permission to link the code of portions of this program with the + * OpenSSL library under certain conditions as described in each + * individual source file, and distribute linked combinations + * including the two. + * You must obey the GNU General Public License in all respects + * for all of the code used other than OpenSSL. If you modify + * file(s) with this exception, you may extend this exception to your + * version of the file(s), but you are not obligated to do so. If you + * do not wish to do so, delete this exception statement from your + * version. If you delete this exception statement from all source + * files in the program, then also delete it here. + OSSEC HIDS 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 Version 3 below for more details. + See the GNU General Public License Version 2 below for more details. ----------------------------------------------------------------------------- @@ -317,3 +341,134 @@ POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS + +------------------------------------------------------------------------------- + +OpenSSL License +--------------- + + LICENSE ISSUES + ============== + + The OpenSSL toolkit stays under a dual license, i.e. both the conditions of + the OpenSSL License and the original SSLeay license apply to the toolkit. + See below for the actual license texts. Actually both licenses are BSD-style + Open Source licenses. In case of any license issues related to OpenSSL + please contact openssl-core@openssl.org. + + OpenSSL License + --------------- + +/* ==================================================================== + * Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + + Original SSLeay License + ----------------------- + +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ diff --git a/README b/README old mode 100755 new mode 100644 index 2d643ec..1071710 --- a/README +++ b/README @@ -1,5 +1,5 @@ -OSSEC v2.5.1 -Copyright (C) 2010 Trend Micro Inc. +OSSEC v2.7 +Copyright (C) 2012 Trend Micro Inc. = Information about OSSEC = diff --git a/active-response/firewall-drop.sh b/active-response/firewall-drop.sh index 65b1dbd..f0e634b 100755 --- a/active-response/firewall-drop.sh +++ b/active-response/firewall-drop.sh @@ -6,12 +6,15 @@ # Expect: srcip # Author: Ahmet Ozturk (ipfilter and IPSec) # Author: Daniel B. Cid (iptables) -# Last modified: Feb 14, 2006 +# Author: cgzones +# Last modified: Oct 04, 2012 UNAME=`uname` ECHO="/bin/echo" GREP="/bin/grep" -IPTABLES="/sbin/iptables" +IPTABLES="" +IP4TABLES="/sbin/iptables" +IP6TABLES="/sbin/ip6tables" IPFILTER="/sbin/ipf" if [ "X$UNAME" = "XSunOS" ]; then IPFILTER="/usr/sbin/ipf" @@ -27,11 +30,18 @@ ACTION=$1 USER=$2 IP=$3 + LOCAL=`dirname $0`; cd $LOCAL cd ../ PWD=`pwd` -echo "`date` $0 $1 $2 $3 $4 $5" >> ${PWD}/../logs/active-responses.log +filename=$(basename "$0") + +LOCK="${PWD}/fw-drop" +LOCK_PID="${LOCK}/pid" +LOG_FILE="${PWD}/../logs/active-responses.log" + +echo "`date` $0 $1 $2 $3 $4 $5" >> ${LOG_FILE} # Checking for an IP @@ -40,6 +50,84 @@ if [ "x${IP}" = "x" ]; then exit 1; fi +case "${IP}" in + *:* ) IPTABLES=$IP6TABLES;; + *.* ) IPTABLES=$IP4TABLES;; + * ) echo "`date` Unable to run active response (invalid IP: '${IP}')." >> ${LOG_FILE} && exit 1;; +esac + +# This number should be more than enough (even if a hundred +# instances of this script is ran together). If you have +# a really loaded env, you can increase it to 75 or 100. +MAX_ITERATION="50" + +# Lock function +lock() +{ + i=0; + # Providing a lock. + while [ 1 ]; do + mkdir ${LOCK} > /dev/null 2>&1 + MSL=$? + if [ "${MSL}" = "0" ]; then + # Lock aquired (setting the pid) + echo "$$" > ${LOCK_PID} + return; + fi + + # Getting currently/saved PID locking the file + C_PID=`cat ${LOCK_PID} 2>/dev/null` + if [ "x" = "x${S_PID}" ]; then + S_PID=${C_PID} + fi + + # Breaking out of the loop after X attempts + if [ "x${C_PID}" = "x${S_PID}" ]; then + i=`expr $i + 1`; + fi + + # Sleep 1 after 10/25 interactions + if [ "$i" = "10" -o "$i" = "25" ]; then + sleep 1; + fi + + i=`expr $i + 1`; + + # So i increments 2 by 2 if the pid does not change. + # If the pid keeps changing, we will increments one + # by one and fail after MAX_ITERACTION + + if [ "$i" = "${MAX_ITERATION}" ]; then + kill="false" + for pid in `pgrep -f "${filename}"`; do + if [ "x${pid}" = "x${C_PID}" ]; then + # Unlocking and exiting + kill -9 ${C_PID} + echo "`date` Killed process ${C_PID} holding lock." >> ${LOG_FILE} + kill="true" + unlock; + i=0; + S_PID=""; + break; + fi + done + + if [ "x${kill}" = "xfalse" ]; then + echo "`date` Unable kill process ${C_PID} holding lock." >> ${LOG_FILE} + # Unlocking and exiting + unlock; + exit 1; + fi + fi + done +} + +# Unlock function +unlock() +{ + rm -rf ${LOCK} +} + # Blocking IP @@ -61,17 +149,17 @@ if [ "X${UNAME}" = "XLinux" ]; then fi # Checking if iptables is present - ls ${IPTABLES} >> /dev/null 2>&1 - if [ $? != 0 ]; then + if [ ! -x ${IPTABLES} ]; then IPTABLES="/usr"${IPTABLES} - ls ${IPTABLES} >> /dev/null 2>&1 - if [ $? != 0 ]; then - exit 0; + if [ ! -x ${IPTABLES} ]; then + echo "$0: can not find iptables" + exit 0; fi fi # Executing and exiting COUNT=0; + lock; while [ 1 ]; do echo ".." ${IPTABLES} ${ARG1} @@ -80,7 +168,7 @@ if [ "X${UNAME}" = "XLinux" ]; then break; else COUNT=`expr $COUNT + 1`; - echo "`date` Unable to run (iptables returning != $RES): $COUNT - $0 $1 $2 $3 $4 $5" >> ${PWD}/../logs/active-responses.log + echo "`date` Unable to run (iptables returning != $RES): $COUNT - $0 $1 $2 $3 $4 $5" >> ${LOG_FILE} sleep $COUNT; if [ $COUNT -gt 4 ]; then @@ -96,7 +184,7 @@ if [ "X${UNAME}" = "XLinux" ]; then break; else COUNT=`expr $COUNT + 1`; - echo "`date` Unable to run (iptables returning != $RES): $COUNT - $0 $1 $2 $3 $4 $5" >> ${PWD}/../logs/active-responses.log + echo "`date` Unable to run (iptables returning != $RES): $COUNT - $0 $1 $2 $3 $4 $5" >> ${LOG_FILE} sleep $COUNT; if [ $COUNT -gt 4 ]; then @@ -104,6 +192,7 @@ if [ "X${UNAME}" = "XLinux" ]; then fi fi done + unlock; exit 0; diff --git a/contrib/active-list.pl b/contrib/active-list.pl new file mode 100644 index 0000000..57b6290 --- /dev/null +++ b/contrib/active-list.pl @@ -0,0 +1,100 @@ +#!/usr/bin/perl +# +# OSSEC active-response script to store a suspicious IP address in a MySQL table. +# +# Available actions are: +# 'add' - Create a new record in the MySQL DB +# 'delete' - Remove a existing record +# +# History +# ------- +# 2010/10/24 xavir@rootshell.be Created +# + +use strict; +use warnings; +use DBI; + +# ----------------------- +# DB access configuration +# ----------------------- +my $db_name = 'ossec_active_lists'; +my $db_user = 'suspicious'; +my $db_pass = 'xxxxxxxxxx'; + +my ($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWeek, $dayOfYear, $daylightSavings) = localtime(); +my $theTime = sprintf("%d-%02d-%02d %02d:%02d:%02d", + $yearOffset+1900, $month+1, $dayOfMonth, $hour, $minute, $second); + +my $nArgs = $#ARGV + 1; +if ($nArgs != 5) { + print STDERR "Usage: active-list.pl \n"; + exit 1; +} + +my $action = $ARGV[0]; +my $ipAddr = $ARGV[2]; +my $alertId = $ARGV[3]; +my $ruleId = $ARGV[4]; + +if ($action ne "add" && $action ne "delete") { + WriteLog("Invalid action: $action\n"); + exit 1; +} + +if ($ipAddr =~ m/^(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)/) { + if ($1 > 255 || $2 > 255 || $3 > 255 || $4 > 255) { + WriteLog("Invalid IP address: $ipAddr\n"); + exit 1; + } +} +else { + WriteLog("Invalid IP address: $ipAddr\n"); +} + +WriteLog("active-list.pl $action $ipAddr $alertId $ruleId\n"); + +my $dbh = DBI->connect('DBI:mysql:' . $db_name, $db_user, $db_pass) || \ + die "Could not connect to database: $DBI::errstr"; + +if ( $action eq "add" ) { + my $sth = $dbh->prepare('SELECT ip FROM ip_addresses WHERE ip = "' . $ipAddr . '"'); + $sth->execute(); + my $result = $sth->fetchrow_hashref(); + if (!$result->{ip}) { + $sth = $dbh->prepare('INSERT INTO ip_addresses VALUES ("' . $ipAddr . '","'. $theTime . '",' . $alertId . ',' . $ruleId . ',"Added by suspicious-ip Perl Script")'); + if (!$sth->execute) { + WriteLog("Cannot insert new IP address: $DBI::errstr\n"); + } + } + else { + $sth = $dbh->prepare('UPDATE ip_addresses SET timestamp = "' . $theTime . '", alertid = ' . $alertId . ', ruleid = ' . $ruleId . ' WHERE ip = "' . $ipAddr . '"'); + if (!$sth->execute) { + WriteLog("Cannot update IP address: $DBI::errstr\n"); + } + } +} +else { + my $sth = $dbh->prepare('DELETE FROM ip_addresses WHERE ip = "' . $ipAddr . '"'); + if (!$sth->execute) { + WriteLog("Cannot remove IP address: $DBI::errstr\n"); + } +} + +$dbh->disconnect; +exit 0; + +sub WriteLog +{ + if ( $_[0] eq "" ) { return; } + + my $pwd = `pwd`; + chomp($pwd); + my $date = `date`; + chomp($date); + + open(LOGH, ">>" . $pwd . "/../active-responses.log") || die "Cannot open log file."; + print LOGH $date . " " . $_[0]; + close(LOGH); + return; +} diff --git a/contrib/logtesting/1/log b/contrib/logtesting/1/log new file mode 100644 index 0000000..eb7e201 --- /dev/null +++ b/contrib/logtesting/1/log @@ -0,0 +1 @@ +Nov 2 13:24:34 melancia pam: gdm-password[1600]: pam_unix(gdm-password:session): session closed for user dcid11 diff --git a/contrib/logtesting/1/res b/contrib/logtesting/1/res new file mode 100644 index 0000000..a62202e --- /dev/null +++ b/contrib/logtesting/1/res @@ -0,0 +1,8 @@ +**Phase 1: Completed pre-decoding. + full event: 'Nov 2 13:24:34 melancia pam: gdm-password[1600]: pam_unix(gdm-password:session): session closed for user dcid11' + hostname: 'melancia' + program_name: 'pam' + log: 'gdm-password[1600]: pam_unix(gdm-password:session): session closed for user dcid11' + +**Phase 2: Completed decoding. + No decoder matched. diff --git a/contrib/logtesting/10/log b/contrib/logtesting/10/log new file mode 100644 index 0000000..74ad821 --- /dev/null +++ b/contrib/logtesting/10/log @@ -0,0 +1 @@ +Feb 15 16:08:14 triumph PAM-securetty[741]: Couldn't open /etc/securetty diff --git a/contrib/logtesting/10/res b/contrib/logtesting/10/res new file mode 100644 index 0000000..d8aa869 --- /dev/null +++ b/contrib/logtesting/10/res @@ -0,0 +1,16 @@ +**Phase 1: Completed pre-decoding. + full event: 'Feb 15 16:08:14 triumph PAM-securetty[741]: Couldn't open /etc/securetty' + hostname: 'triumph' + program_name: 'PAM-securetty' + log: 'Couldn't open /etc/securetty' + +**Phase 2: Completed decoding. + No decoder matched. + +**Phase 3: Completed filtering (rules). + Rule id: '1001' + Level: '2' + Description: 'File missing. Root access unrestricted.' +**Alert to be generated. + + diff --git a/contrib/logtesting/11/log b/contrib/logtesting/11/log new file mode 100644 index 0000000..34594c7 --- /dev/null +++ b/contrib/logtesting/11/log @@ -0,0 +1 @@ +Sep 11 01:40:59 bogus.com su: ericx to root on /dev/ttyu0 diff --git a/contrib/logtesting/11/res b/contrib/logtesting/11/res new file mode 100644 index 0000000..a132a0f --- /dev/null +++ b/contrib/logtesting/11/res @@ -0,0 +1,18 @@ +**Phase 1: Completed pre-decoding. + full event: 'Sep 11 01:40:59 bogus.com su: ericx to root on /dev/ttyu0' + hostname: 'bogus.com' + program_name: 'su' + log: 'ericx to root on /dev/ttyu0' + +**Phase 2: Completed decoding. + decoder: 'su' + srcuser: 'ericx' + dstuser: 'root' + +**Phase 3: Completed filtering (rules). + Rule id: '5303' + Level: '3' + Description: 'User successfully changed UID to root.' +**Alert to be generated. + + diff --git a/contrib/logtesting/12/log b/contrib/logtesting/12/log new file mode 100644 index 0000000..e1baedb --- /dev/null +++ b/contrib/logtesting/12/log @@ -0,0 +1 @@ +May 4 11:17:42 niban su(pam_unix)[2298]: authentication failure; logname= uid=1342 euid=0 tty= ruser=dcid rhost= user=root diff --git a/contrib/logtesting/12/res b/contrib/logtesting/12/res new file mode 100644 index 0000000..81143bf --- /dev/null +++ b/contrib/logtesting/12/res @@ -0,0 +1,16 @@ +**Phase 1: Completed pre-decoding. + full event: 'May 4 11:17:42 niban su(pam_unix)[2298]: authentication failure; logname= uid=1342 euid=0 tty= ruser=dcid rhost= user=root' + hostname: 'melancia' + program_name: '(null)' + log: 'May 4 11:17:42 niban su(pam_unix)[2298]: authentication failure; logname= uid=1342 euid=0 tty= ruser=dcid rhost= user=root' + +**Phase 2: Completed decoding. + No decoder matched. + +**Phase 3: Completed filtering (rules). + Rule id: '2501' + Level: '5' + Description: 'User authentication failure.' +**Alert to be generated. + + diff --git a/contrib/logtesting/13/log b/contrib/logtesting/13/log new file mode 100644 index 0000000..a9bffd1 --- /dev/null +++ b/contrib/logtesting/13/log @@ -0,0 +1 @@ +May 4 11:18:52 niban su(pam_unix)[2307]: authentication failure; logname= uid=1342 euid=0 tty= ruser=dcid rhost= user=test diff --git a/contrib/logtesting/13/res b/contrib/logtesting/13/res new file mode 100644 index 0000000..83f79a0 --- /dev/null +++ b/contrib/logtesting/13/res @@ -0,0 +1,16 @@ +**Phase 1: Completed pre-decoding. + full event: 'May 4 11:18:52 niban su(pam_unix)[2307]: authentication failure; logname= uid=1342 euid=0 tty= ruser=dcid rhost= user=test' + hostname: 'melancia' + program_name: '(null)' + log: 'May 4 11:18:52 niban su(pam_unix)[2307]: authentication failure; logname= uid=1342 euid=0 tty= ruser=dcid rhost= user=test' + +**Phase 2: Completed decoding. + No decoder matched. + +**Phase 3: Completed filtering (rules). + Rule id: '2501' + Level: '5' + Description: 'User authentication failure.' +**Alert to be generated. + + diff --git a/contrib/logtesting/14/log b/contrib/logtesting/14/log new file mode 100644 index 0000000..86d4c56 --- /dev/null +++ b/contrib/logtesting/14/log @@ -0,0 +1 @@ +Jun 8 09:01:01 niban su(pam_unix)[1313]: session opened for user root by (uid=1342) diff --git a/contrib/logtesting/14/res b/contrib/logtesting/14/res new file mode 100644 index 0000000..d6fcaae --- /dev/null +++ b/contrib/logtesting/14/res @@ -0,0 +1,8 @@ +**Phase 1: Completed pre-decoding. + full event: 'Jun 8 09:01:01 niban su(pam_unix)[1313]: session opened for user root by (uid=1342)' + hostname: 'melancia' + program_name: '(null)' + log: 'Jun 8 09:01:01 niban su(pam_unix)[1313]: session opened for user root by (uid=1342)' + +**Phase 2: Completed decoding. + No decoder matched. diff --git a/contrib/logtesting/15/log b/contrib/logtesting/15/log new file mode 100644 index 0000000..60cc1e1 --- /dev/null +++ b/contrib/logtesting/15/log @@ -0,0 +1 @@ +Jun 9 13:32:14 niban su(pam_unix)[1338]: session opened for user root by (uid=1342) diff --git a/contrib/logtesting/15/res b/contrib/logtesting/15/res new file mode 100644 index 0000000..5dcfd9f --- /dev/null +++ b/contrib/logtesting/15/res @@ -0,0 +1,8 @@ +**Phase 1: Completed pre-decoding. + full event: 'Jun 9 13:32:14 niban su(pam_unix)[1338]: session opened for user root by (uid=1342)' + hostname: 'melancia' + program_name: '(null)' + log: 'Jun 9 13:32:14 niban su(pam_unix)[1338]: session opened for user root by (uid=1342)' + +**Phase 2: Completed decoding. + No decoder matched. diff --git a/contrib/logtesting/16/log b/contrib/logtesting/16/log new file mode 100644 index 0000000..305dc61 --- /dev/null +++ b/contrib/logtesting/16/log @@ -0,0 +1 @@ +Jul 5 00:30:21 lili su[2190]: + pts/4 dcid-root diff --git a/contrib/logtesting/16/res b/contrib/logtesting/16/res new file mode 100644 index 0000000..6388ef2 --- /dev/null +++ b/contrib/logtesting/16/res @@ -0,0 +1,8 @@ +**Phase 1: Completed pre-decoding. + full event: 'Jul 5 00:30:21 lili su[2190]: + pts/4 dcid-root' + hostname: 'melancia' + program_name: '(null)' + log: 'Jul 5 00:30:21 lili su[2190]: + pts/4 dcid-root' + +**Phase 2: Completed decoding. + No decoder matched. diff --git a/contrib/logtesting/17/log b/contrib/logtesting/17/log new file mode 100644 index 0000000..b9f0336 --- /dev/null +++ b/contrib/logtesting/17/log @@ -0,0 +1 @@ +Jul 5 12:13:15 lili su[2614]: Authentication failed for root diff --git a/contrib/logtesting/17/res b/contrib/logtesting/17/res new file mode 100644 index 0000000..5d2368e --- /dev/null +++ b/contrib/logtesting/17/res @@ -0,0 +1,16 @@ +**Phase 1: Completed pre-decoding. + full event: 'Jul 5 12:13:15 lili su[2614]: Authentication failed for root' + hostname: 'melancia' + program_name: '(null)' + log: 'Jul 5 12:13:15 lili su[2614]: Authentication failed for root' + +**Phase 2: Completed decoding. + No decoder matched. + +**Phase 3: Completed filtering (rules). + Rule id: '2501' + Level: '5' + Description: 'User authentication failure.' +**Alert to be generated. + + diff --git a/contrib/logtesting/18/log b/contrib/logtesting/18/log new file mode 100644 index 0000000..721b97b --- /dev/null +++ b/contrib/logtesting/18/log @@ -0,0 +1 @@ +Jul 5 12:13:15 lili su[2614]: - pts/6 dcid-root diff --git a/contrib/logtesting/18/res b/contrib/logtesting/18/res new file mode 100644 index 0000000..1dd1cf8 --- /dev/null +++ b/contrib/logtesting/18/res @@ -0,0 +1,8 @@ +**Phase 1: Completed pre-decoding. + full event: 'Jul 5 12:13:15 lili su[2614]: - pts/6 dcid-root' + hostname: 'melancia' + program_name: '(null)' + log: 'Jul 5 12:13:15 lili su[2614]: - pts/6 dcid-root' + +**Phase 2: Completed decoding. + No decoder matched. diff --git a/contrib/logtesting/19/log b/contrib/logtesting/19/log new file mode 100644 index 0000000..a0843f8 --- /dev/null +++ b/contrib/logtesting/19/log @@ -0,0 +1 @@ +May 21 10:24:54 niban useradd[6070]: new group: name=test, gid=5006 diff --git a/contrib/logtesting/19/res b/contrib/logtesting/19/res new file mode 100644 index 0000000..64a4ab6 --- /dev/null +++ b/contrib/logtesting/19/res @@ -0,0 +1,16 @@ +**Phase 1: Completed pre-decoding. + full event: 'May 21 10:24:54 niban useradd[6070]: new group: name=test, gid=5006' + hostname: 'niban' + program_name: 'useradd' + log: 'new group: name=test, gid=5006' + +**Phase 2: Completed decoding. + No decoder matched. + +**Phase 3: Completed filtering (rules). + Rule id: '5901' + Level: '8' + Description: 'New group added to the system' +**Alert to be generated. + + diff --git a/contrib/logtesting/2/log b/contrib/logtesting/2/log new file mode 100644 index 0000000..6059c8f --- /dev/null +++ b/contrib/logtesting/2/log @@ -0,0 +1 @@ +Nov 1 14:54:03 melancia runuser: pam_unix(runuser:session): session opened for user root by (uid=0) diff --git a/contrib/logtesting/2/res b/contrib/logtesting/2/res new file mode 100644 index 0000000..ed00e95 --- /dev/null +++ b/contrib/logtesting/2/res @@ -0,0 +1,16 @@ +**Phase 1: Completed pre-decoding. + full event: 'Nov 1 14:54:03 melancia runuser: pam_unix(runuser:session): session opened for user root by (uid=0)' + hostname: 'melancia' + program_name: 'runuser' + log: 'pam_unix(runuser:session): session opened for user root by (uid=0)' + +**Phase 2: Completed decoding. + decoder: 'pam' + +**Phase 3: Completed filtering (rules). + Rule id: '5501' + Level: '3' + Description: 'Login session opened.' +**Alert to be generated. + + diff --git a/contrib/logtesting/20/log b/contrib/logtesting/20/log new file mode 100644 index 0000000..7cb06f5 --- /dev/null +++ b/contrib/logtesting/20/log @@ -0,0 +1 @@ +May 28 10:48:29 niban useradd[32421]: new group: name=logr, gid=12000 diff --git a/contrib/logtesting/20/res b/contrib/logtesting/20/res new file mode 100644 index 0000000..b0b4458 --- /dev/null +++ b/contrib/logtesting/20/res @@ -0,0 +1,16 @@ +**Phase 1: Completed pre-decoding. + full event: 'May 28 10:48:29 niban useradd[32421]: new group: name=logr, gid=12000' + hostname: 'niban' + program_name: 'useradd' + log: 'new group: name=logr, gid=12000' + +**Phase 2: Completed decoding. + No decoder matched. + +**Phase 3: Completed filtering (rules). + Rule id: '5901' + Level: '8' + Description: 'New group added to the system' +**Alert to be generated. + + diff --git a/contrib/logtesting/21/log b/contrib/logtesting/21/log new file mode 100644 index 0000000..5842364 --- /dev/null +++ b/contrib/logtesting/21/log @@ -0,0 +1 @@ +Jun 16 09:53:44 niban useradd[5721]: new group: name=test2, gid=12001 diff --git a/contrib/logtesting/21/res b/contrib/logtesting/21/res new file mode 100644 index 0000000..74dd5bb --- /dev/null +++ b/contrib/logtesting/21/res @@ -0,0 +1,16 @@ +**Phase 1: Completed pre-decoding. + full event: 'Jun 16 09:53:44 niban useradd[5721]: new group: name=test2, gid=12001' + hostname: 'niban' + program_name: 'useradd' + log: 'new group: name=test2, gid=12001' + +**Phase 2: Completed decoding. + No decoder matched. + +**Phase 3: Completed filtering (rules). + Rule id: '5901' + Level: '8' + Description: 'New group added to the system' +**Alert to be generated. + + diff --git a/contrib/logtesting/22/log b/contrib/logtesting/22/log new file mode 100644 index 0000000..d769abb --- /dev/null +++ b/contrib/logtesting/22/log @@ -0,0 +1 @@ +Aug 4 15:11:23 niban groupadd[26459]: new group: name=osaudit, gid=12002 diff --git a/contrib/logtesting/22/res b/contrib/logtesting/22/res new file mode 100644 index 0000000..1f3de22 --- /dev/null +++ b/contrib/logtesting/22/res @@ -0,0 +1,8 @@ +**Phase 1: Completed pre-decoding. + full event: 'Aug 4 15:11:23 niban groupadd[26459]: new group: name=osaudit, gid=12002' + hostname: 'melancia' + program_name: '(null)' + log: 'Aug 4 15:11:23 niban groupadd[26459]: new group: name=osaudit, gid=12002' + +**Phase 2: Completed decoding. + No decoder matched. diff --git a/contrib/logtesting/23/log b/contrib/logtesting/23/log new file mode 100644 index 0000000..bab3655 --- /dev/null +++ b/contrib/logtesting/23/log @@ -0,0 +1 @@ +Aug 4 15:14:14 niban groupadd[26477]: new group: name=osaudit, gid=12002 diff --git a/contrib/logtesting/23/res b/contrib/logtesting/23/res new file mode 100644 index 0000000..2829a5f --- /dev/null +++ b/contrib/logtesting/23/res @@ -0,0 +1,8 @@ +**Phase 1: Completed pre-decoding. + full event: 'Aug 4 15:14:14 niban groupadd[26477]: new group: name=osaudit, gid=12002' + hostname: 'melancia' + program_name: '(null)' + log: 'Aug 4 15:14:14 niban groupadd[26477]: new group: name=osaudit, gid=12002' + +**Phase 2: Completed decoding. + No decoder matched. diff --git a/contrib/logtesting/24/log b/contrib/logtesting/24/log new file mode 100644 index 0000000..d52ac7a --- /dev/null +++ b/contrib/logtesting/24/log @@ -0,0 +1 @@ +Apr 5 16:19:49 niban adduser[16188]: new user: name=port4, uid=12006, gid=0, home=/home/port4, shell=/bin/bash diff --git a/contrib/logtesting/24/res b/contrib/logtesting/24/res new file mode 100644 index 0000000..0e45275 --- /dev/null +++ b/contrib/logtesting/24/res @@ -0,0 +1,8 @@ +**Phase 1: Completed pre-decoding. + full event: 'Apr 5 16:19:49 niban adduser[16188]: new user: name=port4, uid=12006, gid=0, home=/home/port4, shell=/bin/bash' + hostname: 'melancia' + program_name: '(null)' + log: 'Apr 5 16:19:49 niban adduser[16188]: new user: name=port4, uid=12006, gid=0, home=/home/port4, shell=/bin/bash' + +**Phase 2: Completed decoding. + No decoder matched. diff --git a/contrib/logtesting/25/log b/contrib/logtesting/25/log new file mode 100644 index 0000000..6871b31 --- /dev/null +++ b/contrib/logtesting/25/log @@ -0,0 +1 @@ +Feb 1 14:39:16 nogan sudo: test2 : 3 incorrect password attempts ; TTY=pts/4 ; PWD=/home/test2 ; USER=root ; COMMAND=/bin/ls diff --git a/contrib/logtesting/25/res b/contrib/logtesting/25/res new file mode 100644 index 0000000..6c61ac8 --- /dev/null +++ b/contrib/logtesting/25/res @@ -0,0 +1,8 @@ +**Phase 1: Completed pre-decoding. + full event: 'Feb 1 14:39:16 nogan sudo: test2 : 3 incorrect password attempts ; TTY=pts/4 ; PWD=/home/test2 ; USER=root ; COMMAND=/bin/ls' + hostname: 'melancia' + program_name: '(null)' + log: 'Feb 1 14:39:16 nogan sudo: test2 : 3 incorrect password attempts ; TTY=pts/4 ; PWD=/home/test2 ; USER=root ; COMMAND=/bin/ls' + +**Phase 2: Completed decoding. + No decoder matched. diff --git a/contrib/logtesting/26/log b/contrib/logtesting/26/log new file mode 100644 index 0000000..328e46f --- /dev/null +++ b/contrib/logtesting/26/log @@ -0,0 +1 @@ +Jan 28 20:36:33 enigma sudo: dcid : 3 incorrect password attempts ; TTY=ttyp0 ; PWD=/home/dcid ; USER=root ; COMMAND=/bin/ls diff --git a/contrib/logtesting/26/res b/contrib/logtesting/26/res new file mode 100644 index 0000000..d05a62d --- /dev/null +++ b/contrib/logtesting/26/res @@ -0,0 +1,16 @@ +**Phase 1: Completed pre-decoding. + full event: 'Jan 28 20:36:33 enigma sudo: dcid : 3 incorrect password attempts ; TTY=ttyp0 ; PWD=/home/dcid ; USER=root ; COMMAND=/bin/ls' + hostname: 'enigma' + program_name: 'sudo' + log: 'dcid : 3 incorrect password attempts ; TTY=ttyp0 ; PWD=/home/dcid ; USER=root ; COMMAND=/bin/ls' + +**Phase 2: Completed decoding. + decoder: 'sudo' + +**Phase 3: Completed filtering (rules). + Rule id: '5401' + Level: '10' + Description: 'Three failed attempts to run sudo' +**Alert to be generated. + + diff --git a/contrib/logtesting/27/log b/contrib/logtesting/27/log new file mode 100644 index 0000000..b156e56 --- /dev/null +++ b/contrib/logtesting/27/log @@ -0,0 +1 @@ +May 26 19:40:25 enigma sudo: dcid : 3 incorrect password attempts ; TTY=ttyp0 ; PWD=/var/www/htdocs ; USER=root ; COMMAND=/bin/ls diff --git a/contrib/logtesting/27/res b/contrib/logtesting/27/res new file mode 100644 index 0000000..5bf1a5f --- /dev/null +++ b/contrib/logtesting/27/res @@ -0,0 +1,16 @@ +**Phase 1: Completed pre-decoding. + full event: 'May 26 19:40:25 enigma sudo: dcid : 3 incorrect password attempts ; TTY=ttyp0 ; PWD=/var/www/htdocs ; USER=root ; COMMAND=/bin/ls' + hostname: 'enigma' + program_name: 'sudo' + log: 'dcid : 3 incorrect password attempts ; TTY=ttyp0 ; PWD=/var/www/htdocs ; USER=root ; COMMAND=/bin/ls' + +**Phase 2: Completed decoding. + decoder: 'sudo' + +**Phase 3: Completed filtering (rules). + Rule id: '5401' + Level: '10' + Description: 'Three failed attempts to run sudo' +**Alert to be generated. + + diff --git a/contrib/logtesting/28/log b/contrib/logtesting/28/log new file mode 100644 index 0000000..b0dea84 --- /dev/null +++ b/contrib/logtesting/28/log @@ -0,0 +1 @@ +Feb 4 10:43:02 niban sudo: dcid : TTY=pts/4 ; PWD=/home/dcid ; USER=root ; COMMAND=/bin/ls diff --git a/contrib/logtesting/28/res b/contrib/logtesting/28/res new file mode 100644 index 0000000..a5a97d8 --- /dev/null +++ b/contrib/logtesting/28/res @@ -0,0 +1,8 @@ +**Phase 1: Completed pre-decoding. + full event: 'Feb 4 10:43:02 niban sudo: dcid : TTY=pts/4 ; PWD=/home/dcid ; USER=root ; COMMAND=/bin/ls' + hostname: 'melancia' + program_name: '(null)' + log: 'Feb 4 10:43:02 niban sudo: dcid : TTY=pts/4 ; PWD=/home/dcid ; USER=root ; COMMAND=/bin/ls' + +**Phase 2: Completed decoding. + No decoder matched. diff --git a/contrib/logtesting/29/log b/contrib/logtesting/29/log new file mode 100644 index 0000000..03a69c9 --- /dev/null +++ b/contrib/logtesting/29/log @@ -0,0 +1 @@ +Feb 4 10:44:00 niban sudo: dcid : TTY=pts/4 ; PWD=/home/dcid ; USER=root ; COMMAND=/bin/chmod 777 /home/dcid/test1 diff --git a/contrib/logtesting/29/res b/contrib/logtesting/29/res new file mode 100644 index 0000000..8d55df2 --- /dev/null +++ b/contrib/logtesting/29/res @@ -0,0 +1,8 @@ +**Phase 1: Completed pre-decoding. + full event: 'Feb 4 10:44:00 niban sudo: dcid : TTY=pts/4 ; PWD=/home/dcid ; USER=root ; COMMAND=/bin/chmod 777 /home/dcid/test1' + hostname: 'melancia' + program_name: '(null)' + log: 'Feb 4 10:44:00 niban sudo: dcid : TTY=pts/4 ; PWD=/home/dcid ; USER=root ; COMMAND=/bin/chmod 777 /home/dcid/test1' + +**Phase 2: Completed decoding. + No decoder matched. diff --git a/contrib/logtesting/3/log b/contrib/logtesting/3/log new file mode 100644 index 0000000..60a16a2 --- /dev/null +++ b/contrib/logtesting/3/log @@ -0,0 +1 @@ +Nov 11 22:46:29 localhost vsftpd: pam_unix(vsftpd:auth): authentication failure; logname= uid=0 euid=0 tty= ruser= rhost=1.2.3.4 diff --git a/contrib/logtesting/3/res b/contrib/logtesting/3/res new file mode 100644 index 0000000..5586f89 --- /dev/null +++ b/contrib/logtesting/3/res @@ -0,0 +1,17 @@ +**Phase 1: Completed pre-decoding. + full event: 'Nov 11 22:46:29 localhost vsftpd: pam_unix(vsftpd:auth): authentication failure; logname= uid=0 euid=0 tty= ruser= rhost=1.2.3.4' + hostname: 'localhost' + program_name: 'vsftpd' + log: 'pam_unix(vsftpd:auth): authentication failure; logname= uid=0 euid=0 tty= ruser= rhost=1.2.3.4' + +**Phase 2: Completed decoding. + decoder: 'pam' + srcip: '1.2.3.4' + +**Phase 3: Completed filtering (rules). + Rule id: '5503' + Level: '5' + Description: 'User login failed.' +**Alert to be generated. + + diff --git a/contrib/logtesting/30/log b/contrib/logtesting/30/log new file mode 100644 index 0000000..eeb35ef --- /dev/null +++ b/contrib/logtesting/30/log @@ -0,0 +1 @@ +Feb 4 10:46:37 niban sudo: dcid : TTY=pts/26 ; PWD=/home/dcid/dev/pr/osaudit/osaudit-0.1/src ; USER=root ; COMMAND=/bin/cp -pr ../bin/logreader ../bin/logremote ../bin/logremote-client /var/osaudit/bin diff --git a/contrib/logtesting/30/res b/contrib/logtesting/30/res new file mode 100644 index 0000000..87eec28 --- /dev/null +++ b/contrib/logtesting/30/res @@ -0,0 +1,8 @@ +**Phase 1: Completed pre-decoding. + full event: 'Feb 4 10:46:37 niban sudo: dcid : TTY=pts/26 ; PWD=/home/dcid/dev/pr/osaudit/osaudit-0.1/src ; USER=root ; COMMAND=/bin/cp -pr ../bin/logreader ../bin/logremote ../bin/logremote-client /var/osaudit/bin' + hostname: 'melancia' + program_name: '(null)' + log: 'Feb 4 10:46:37 niban sudo: dcid : TTY=pts/26 ; PWD=/home/dcid/dev/pr/osaudit/osaudit-0.1/src ; USER=root ; COMMAND=/bin/cp -pr ../bin/logreader ../bin/logremote ../bin/logremote-client /var/osaudit/bin' + +**Phase 2: Completed decoding. + No decoder matched. diff --git a/contrib/logtesting/31/log b/contrib/logtesting/31/log new file mode 100644 index 0000000..e5eb9d1 --- /dev/null +++ b/contrib/logtesting/31/log @@ -0,0 +1 @@ +May 26 19:40:41 enigma sudo: dcid : TTY=ttyp0 ; PWD=/var/www/htdocs ; USER=root ; COMMAND=/usr/bin/tail /var/log/secure diff --git a/contrib/logtesting/31/res b/contrib/logtesting/31/res new file mode 100644 index 0000000..597abea --- /dev/null +++ b/contrib/logtesting/31/res @@ -0,0 +1,16 @@ +**Phase 1: Completed pre-decoding. + full event: 'May 26 19:40:41 enigma sudo: dcid : TTY=ttyp0 ; PWD=/var/www/htdocs ; USER=root ; COMMAND=/usr/bin/tail /var/log/secure' + hostname: 'enigma' + program_name: 'sudo' + log: 'dcid : TTY=ttyp0 ; PWD=/var/www/htdocs ; USER=root ; COMMAND=/usr/bin/tail /var/log/secure' + +**Phase 2: Completed decoding. + decoder: 'sudo' + +**Phase 3: Completed filtering (rules). + Rule id: '5403' + Level: '4' + Description: 'First time user executed sudo.' +**Alert to be generated. + + diff --git a/contrib/logtesting/32/log b/contrib/logtesting/32/log new file mode 100644 index 0000000..83041fb --- /dev/null +++ b/contrib/logtesting/32/log @@ -0,0 +1 @@ +May 26 20:16:17 lili sudo: dcid : TTY=pts/1 ; PWD=/home/dcid ; USER=root ; COMMAND=/usr/bin/vi /etc/sudoers diff --git a/contrib/logtesting/32/res b/contrib/logtesting/32/res new file mode 100644 index 0000000..4ce5102 --- /dev/null +++ b/contrib/logtesting/32/res @@ -0,0 +1,16 @@ +**Phase 1: Completed pre-decoding. + full event: 'May 26 20:16:17 lili sudo: dcid : TTY=pts/1 ; PWD=/home/dcid ; USER=root ; COMMAND=/usr/bin/vi /etc/sudoers' + hostname: 'lili' + program_name: 'sudo' + log: 'dcid : TTY=pts/1 ; PWD=/home/dcid ; USER=root ; COMMAND=/usr/bin/vi /etc/sudoers' + +**Phase 2: Completed decoding. + decoder: 'sudo' + +**Phase 3: Completed filtering (rules). + Rule id: '5403' + Level: '4' + Description: 'First time user executed sudo.' +**Alert to be generated. + + diff --git a/contrib/logtesting/33/log b/contrib/logtesting/33/log new file mode 100644 index 0000000..ee9b225 --- /dev/null +++ b/contrib/logtesting/33/log @@ -0,0 +1 @@ +Oct 26 18:07:45 ccs rpc.statd[189]: gethostbyname error for ^X÷ÿ¿^X÷ÿ¿^Z÷ÿ¿^Z÷ÿ¿%8x%8x%8x%8x%8x%8x%8x%8x%8x%62716x%hn%51859x%hn220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220 diff --git a/contrib/logtesting/33/res b/contrib/logtesting/33/res new file mode 100644 index 0000000..69d8c5a --- /dev/null +++ b/contrib/logtesting/33/res @@ -0,0 +1,16 @@ +**Phase 1: Completed pre-decoding. + full event: 'Oct 26 18:07:45 ccs rpc.statd[189]: gethostbyname error for ^X÷ÿ¿^X÷ÿ¿^Z÷ÿ¿^Z÷ÿ¿%8x%8x%8x%8x%8x%8x%8x%8x%8x%62716x%hn%51859x%hn220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220' + hostname: 'ccs' + program_name: 'rpc.statd' + log: 'gethostbyname error for ^X÷ÿ¿^X÷ÿ¿^Z÷ÿ¿^Z÷ÿ¿%8x%8x%8x%8x%8x%8x%8x%8x%8x%62716x%hn%51859x%hn220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220220' + +**Phase 2: Completed decoding. + No decoder matched. + +**Phase 3: Completed filtering (rules). + Rule id: '1002' + Level: '2' + Description: 'Unknown problem somewhere in the system.' +**Alert to be generated. + + diff --git a/contrib/logtesting/34/log b/contrib/logtesting/34/log new file mode 100644 index 0000000..691ce2a --- /dev/null +++ b/contrib/logtesting/34/log @@ -0,0 +1 @@ +May 17 01:01:19 server ftpd[746]: ANONYMOUS FTP LOGIN FROM emaca.here.com diff --git a/contrib/logtesting/34/res b/contrib/logtesting/34/res new file mode 100644 index 0000000..16f671f --- /dev/null +++ b/contrib/logtesting/34/res @@ -0,0 +1,16 @@ +**Phase 1: Completed pre-decoding. + full event: 'May 17 01:01:19 server ftpd[746]: ANONYMOUS FTP LOGIN FROM emaca.here.com' + hostname: 'server' + program_name: 'ftpd' + log: 'ANONYMOUS FTP LOGIN FROM emaca.here.com' + +**Phase 2: Completed decoding. + decoder: 'ftpd' + +**Phase 3: Completed filtering (rules). + Rule id: '11106' + Level: '3' + Description: 'Remote host connected to FTP server.' +**Alert to be generated. + + diff --git a/contrib/logtesting/35/log b/contrib/logtesting/35/log new file mode 100644 index 0000000..6e81c7e --- /dev/null +++ b/contrib/logtesting/35/log @@ -0,0 +1 @@ +May 16 22:46:08 victim-host inetd[600]: /usr/lib/fs/cachefs/cachefsd: Segmentation Fault - core dumped diff --git a/contrib/logtesting/35/res b/contrib/logtesting/35/res new file mode 100644 index 0000000..290e8e1 --- /dev/null +++ b/contrib/logtesting/35/res @@ -0,0 +1,17 @@ +**Phase 1: Completed pre-decoding. + full event: 'May 16 22:46:08 victim-host inetd[600]: /usr/lib/fs/cachefs/cachefsd: Segmentation Fault - core dumped' + hostname: 'victim-host' + program_name: 'inetd' + log: '/usr/lib/fs/cachefs/cachefsd: Segmentation Fault - core dumped' + +**Phase 2: Completed decoding. + No decoder matched. + +**Phase 3: Completed filtering (rules). + Rule id: '40107' + Level: '14' + Description: 'Heap overflow in the Solaris cachefsd service.' + Info - CVE: '2002-0033' +**Alert to be generated. + + diff --git a/contrib/logtesting/36/log b/contrib/logtesting/36/log new file mode 100644 index 0000000..a08d835 --- /dev/null +++ b/contrib/logtesting/36/log @@ -0,0 +1 @@ +May 16 22:46:24 victim-host inetd[600]: /usr/lib/fs/cachefs/cachefsd: Segmentation Fault - core dumped diff --git a/contrib/logtesting/36/res b/contrib/logtesting/36/res new file mode 100644 index 0000000..2899796 --- /dev/null +++ b/contrib/logtesting/36/res @@ -0,0 +1,17 @@ +**Phase 1: Completed pre-decoding. + full event: 'May 16 22:46:24 victim-host inetd[600]: /usr/lib/fs/cachefs/cachefsd: Segmentation Fault - core dumped' + hostname: 'victim-host' + program_name: 'inetd' + log: '/usr/lib/fs/cachefs/cachefsd: Segmentation Fault - core dumped' + +**Phase 2: Completed decoding. + No decoder matched. + +**Phase 3: Completed filtering (rules). + Rule id: '40107' + Level: '14' + Description: 'Heap overflow in the Solaris cachefsd service.' + Info - CVE: '2002-0033' +**Alert to be generated. + + diff --git a/contrib/logtesting/37/log b/contrib/logtesting/37/log new file mode 100644 index 0000000..3c30aae --- /dev/null +++ b/contrib/logtesting/37/log @@ -0,0 +1 @@ +Apr 17 22:20:29 hostj named[312]: [ID 295310 daemon.notice] security: notice: dropping source port zero packet from [64.211.251.254].0 diff --git a/contrib/logtesting/37/res b/contrib/logtesting/37/res new file mode 100644 index 0000000..61c466e --- /dev/null +++ b/contrib/logtesting/37/res @@ -0,0 +1,17 @@ +**Phase 1: Completed pre-decoding. + full event: 'Apr 17 22:20:29 hostj named[312]: [ID 295310 daemon.notice] security: notice: dropping source port zero packet from [64.211.251.254].0' + hostname: 'hostj' + program_name: 'named' + log: 'security: notice: dropping source port zero packet from [64.211.251.254].0' + +**Phase 2: Completed decoding. + decoder: 'named' + srcip: '64.211.251.254' + +**Phase 3: Completed filtering (rules). + Rule id: '12101' + Level: '12' + Description: 'Invalid DNS packet. Possibility of attack.' +**Alert to be generated. + + diff --git a/contrib/logtesting/38/log b/contrib/logtesting/38/log new file mode 100644 index 0000000..9c1608c --- /dev/null +++ b/contrib/logtesting/38/log @@ -0,0 +1 @@ +sshd[7386]: error: Bad prime description in line 73 diff --git a/contrib/logtesting/38/res b/contrib/logtesting/38/res new file mode 100644 index 0000000..ddd59dd --- /dev/null +++ b/contrib/logtesting/38/res @@ -0,0 +1,16 @@ +**Phase 1: Completed pre-decoding. + full event: 'sshd[7386]: error: Bad prime description in line 73' + hostname: 'melancia' + program_name: '(null)' + log: 'sshd[7386]: error: Bad prime description in line 73' + +**Phase 2: Completed decoding. + No decoder matched. + +**Phase 3: Completed filtering (rules). + Rule id: '1002' + Level: '2' + Description: 'Unknown problem somewhere in the system.' +**Alert to be generated. + + diff --git a/contrib/logtesting/39/log b/contrib/logtesting/39/log new file mode 100644 index 0000000..3685e94 --- /dev/null +++ b/contrib/logtesting/39/log @@ -0,0 +1 @@ +Jan 12 20:48:29 elrond sshd[19734]: refused connect from accsys.elink.net.au (203.31.101.11) diff --git a/contrib/logtesting/39/res b/contrib/logtesting/39/res new file mode 100644 index 0000000..f3d7668 --- /dev/null +++ b/contrib/logtesting/39/res @@ -0,0 +1,16 @@ +**Phase 1: Completed pre-decoding. + full event: 'Jan 12 20:48:29 elrond sshd[19734]: refused connect from accsys.elink.net.au (203.31.101.11)' + hostname: 'elrond' + program_name: 'sshd' + log: 'refused connect from accsys.elink.net.au (203.31.101.11)' + +**Phase 2: Completed decoding. + decoder: 'sshd' + +**Phase 3: Completed filtering (rules). + Rule id: '2503' + Level: '5' + Description: 'Connection blocked by Tcp Wrappers.' +**Alert to be generated. + + diff --git a/contrib/logtesting/4/log b/contrib/logtesting/4/log new file mode 100644 index 0000000..5571201 --- /dev/null +++ b/contrib/logtesting/4/log @@ -0,0 +1 @@ +Dec 18 18:06:28 hostname cimserver[18575]: PGS17200: Authentication failed for user jones_b. diff --git a/contrib/logtesting/4/res b/contrib/logtesting/4/res new file mode 100644 index 0000000..00fe563 --- /dev/null +++ b/contrib/logtesting/4/res @@ -0,0 +1,17 @@ +**Phase 1: Completed pre-decoding. + full event: 'Dec 18 18:06:28 hostname cimserver[18575]: PGS17200: Authentication failed for user jones_b.' + hostname: 'hostname' + program_name: 'cimserver' + log: 'PGS17200: Authentication failed for user jones_b.' + +**Phase 2: Completed decoding. + decoder: 'cimserver' + dstuser: 'jones_b.' + +**Phase 3: Completed filtering (rules). + Rule id: '9610' + Level: '5' + Description: 'Compaq Insight Manager authentication failure.' +**Alert to be generated. + + diff --git a/contrib/logtesting/40/log b/contrib/logtesting/40/log new file mode 100644 index 0000000..4da5f03 --- /dev/null +++ b/contrib/logtesting/40/log @@ -0,0 +1 @@ +Aug 1 15:44:10 enigma sshd[13752]: Failed password for invalid user ss7 from 65.202.215.2 port 18546 ssh2 diff --git a/contrib/logtesting/40/res b/contrib/logtesting/40/res new file mode 100644 index 0000000..cde3af4 --- /dev/null +++ b/contrib/logtesting/40/res @@ -0,0 +1,16 @@ +**Phase 1: Completed pre-decoding. + full event: 'Aug 1 15:44:10 enigma sshd[13752]: Failed password for invalid user ss7 from 65.202.215.2 port 18546 ssh2' + hostname: 'melancia' + program_name: '(null)' + log: 'Aug 1 15:44:10 enigma sshd[13752]: Failed password for invalid user ss7 from 65.202.215.2 port 18546 ssh2' + +**Phase 2: Completed decoding. + No decoder matched. + +**Phase 3: Completed filtering (rules). + Rule id: '1002' + Level: '2' + Description: 'Unknown problem somewhere in the system.' +**Alert to be generated. + + diff --git a/contrib/logtesting/41/log b/contrib/logtesting/41/log new file mode 100644 index 0000000..ec267f9 --- /dev/null +++ b/contrib/logtesting/41/log @@ -0,0 +1 @@ +Aug 1 15:44:10 enigma sshd[6682]: Failed password for invalid user ss7 from 65.202.215.2 port 18546 ssh2 diff --git a/contrib/logtesting/41/res b/contrib/logtesting/41/res new file mode 100644 index 0000000..145936e --- /dev/null +++ b/contrib/logtesting/41/res @@ -0,0 +1,16 @@ +**Phase 1: Completed pre-decoding. + full event: 'Aug 1 15:44:10 enigma sshd[6682]: Failed password for invalid user ss7 from 65.202.215.2 port 18546 ssh2' + hostname: 'melancia' + program_name: '(null)' + log: 'Aug 1 15:44:10 enigma sshd[6682]: Failed password for invalid user ss7 from 65.202.215.2 port 18546 ssh2' + +**Phase 2: Completed decoding. + No decoder matched. + +**Phase 3: Completed filtering (rules). + Rule id: '1002' + Level: '2' + Description: 'Unknown problem somewhere in the system.' +**Alert to be generated. + + diff --git a/contrib/logtesting/42/log b/contrib/logtesting/42/log new file mode 100644 index 0000000..47f2fd4 --- /dev/null +++ b/contrib/logtesting/42/log @@ -0,0 +1 @@ +[Tue Sep 12 10:38:15 2006] [error] [client 127.0.0.1] request failed: URI too long (longer than 8190) diff --git a/contrib/logtesting/42/res b/contrib/logtesting/42/res new file mode 100644 index 0000000..c228b7b --- /dev/null +++ b/contrib/logtesting/42/res @@ -0,0 +1,17 @@ +**Phase 1: Completed pre-decoding. + full event: '[Tue Sep 12 10:38:15 2006] [error] [client 127.0.0.1] request failed: URI too long (longer than 8190)' + hostname: 'melancia' + program_name: '(null)' + log: '[error] [client 127.0.0.1] request failed: URI too long (longer than 8190)' + +**Phase 2: Completed decoding. + decoder: 'apache-errorlog' + srcip: '127.0.0.1' + +**Phase 3: Completed filtering (rules). + Rule id: '30117' + Level: '10' + Description: 'Invalid URI, file name too long.' +**Alert to be generated. + + diff --git a/contrib/logtesting/43/log b/contrib/logtesting/43/log new file mode 100644 index 0000000..7a1ba34 --- /dev/null +++ b/contrib/logtesting/43/log @@ -0,0 +1 @@ +[Mon Sep 11 16:55:08 2006] [error] [client 127.0.0.1] (36)File name too long: access to /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffgggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggghhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkklllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm failed diff --git a/contrib/logtesting/43/res b/contrib/logtesting/43/res new file mode 100644 index 0000000..392f224 --- /dev/null +++ b/contrib/logtesting/43/res @@ -0,0 +1,17 @@ +**Phase 1: Completed pre-decoding. + full event: '[Mon Sep 11 16:55:08 2006] [error] [client 127.0.0.1] (36)File name too long: access to /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffgggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggghhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkklllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm failed' + hostname: 'melancia' + program_name: '(null)' + log: '[error] [client 127.0.0.1] (36)File name too long: access to /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffgggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggghhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkklllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm failed' + +**Phase 2: Completed decoding. + decoder: 'apache-errorlog' + srcip: '127.0.0.1' + +**Phase 3: Completed filtering (rules). + Rule id: '30117' + Level: '10' + Description: 'Invalid URI, file name too long.' +**Alert to be generated. + + diff --git a/contrib/logtesting/44/log b/contrib/logtesting/44/log new file mode 100644 index 0000000..2d503b9 --- /dev/null +++ b/contrib/logtesting/44/log @@ -0,0 +1 @@ +Sep 1 10:29:33 10.10.10.1 %IPS-4-SIGNATURE: Sig:3051 Subsig:1 Sev:4 TCP Connection Window Size DoS [192.168.100.12:1234 -> 192.168.100.1:443] diff --git a/contrib/logtesting/44/res b/contrib/logtesting/44/res new file mode 100644 index 0000000..fcd8b85 --- /dev/null +++ b/contrib/logtesting/44/res @@ -0,0 +1,8 @@ +**Phase 1: Completed pre-decoding. + full event: 'Sep 1 10:29:33 10.10.10.1 %IPS-4-SIGNATURE: Sig:3051 Subsig:1 Sev:4 TCP Connection Window Size DoS [192.168.100.12:1234 -> 192.168.100.1:443]' + hostname: 'melancia' + program_name: '(null)' + log: 'Sep 1 10:29:33 10.10.10.1 %IPS-4-SIGNATURE: Sig:3051 Subsig:1 Sev:4 TCP Connection Window Size DoS [192.168.100.12:1234 -> 192.168.100.1:443]' + +**Phase 2: Completed decoding. + No decoder matched. diff --git a/contrib/logtesting/5/log b/contrib/logtesting/5/log new file mode 100644 index 0000000..c545162 --- /dev/null +++ b/contrib/logtesting/5/log @@ -0,0 +1 @@ +Apr 27 15:22:23 niban sudo: dcid : TTY=pts/4 ; PWD=/home/dcid ; USER=root ; COMMAND=/usr/bin/tail /var/log/snort/alert.fast diff --git a/contrib/logtesting/5/res b/contrib/logtesting/5/res new file mode 100644 index 0000000..5ac8830 --- /dev/null +++ b/contrib/logtesting/5/res @@ -0,0 +1,17 @@ +**Phase 1: Completed pre-decoding. + full event: 'Apr 27 15:22:23 niban sudo: dcid : TTY=pts/4 ; PWD=/home/dcid ; USER=root ; COMMAND=/usr/bin/tail /var/log/snort/alert.fast' + hostname: 'niban' + program_name: 'sudo' + log: ' dcid : TTY=pts/4 ; PWD=/home/dcid ; USER=root ; COMMAND=/usr/bin/tail /var/log/snort/alert.fast' + +**Phase 2: Completed decoding. + decoder: 'sudo' + dstuser: 'dcid' + +**Phase 3: Completed filtering (rules). + Rule id: '5403' + Level: '4' + Description: 'First time user executed sudo.' +**Alert to be generated. + + diff --git a/contrib/logtesting/6/log b/contrib/logtesting/6/log new file mode 100644 index 0000000..821e304 --- /dev/null +++ b/contrib/logtesting/6/log @@ -0,0 +1 @@ +Sun Aug 27 16:28:20 2006 [pid 13962] [xx] OK UPLOAD: Client "1.2.3.4", "/a.php", 8338 bytes, 18.77Kbyte/sec diff --git a/contrib/logtesting/6/res b/contrib/logtesting/6/res new file mode 100644 index 0000000..fbe5a6f --- /dev/null +++ b/contrib/logtesting/6/res @@ -0,0 +1,13 @@ +**Phase 1: Completed pre-decoding. + full event: 'Sun Aug 27 16:28:20 2006 [pid 13962] [xx] OK UPLOAD: Client "1.2.3.4", "/a.php", 8338 bytes, 18.77Kbyte/sec' + hostname: 'melancia' + program_name: '(null)' + log: 'Sun Aug 27 16:28:20 2006 [pid 13962] [xx] OK UPLOAD: Client "1.2.3.4", "/a.php", 8338 bytes, 18.77Kbyte/sec' + +**Phase 2: Completed decoding. + decoder: 'vsftpd' + +**Phase 3: Completed filtering (rules). + Rule id: '11404' + Level: '0' + Description: 'FTP server file upload.' diff --git a/contrib/logtesting/7/log b/contrib/logtesting/7/log new file mode 100644 index 0000000..37f5735 --- /dev/null +++ b/contrib/logtesting/7/log @@ -0,0 +1 @@ +MySQL log: 060516 22:38:46 mysqld ended diff --git a/contrib/logtesting/7/res b/contrib/logtesting/7/res new file mode 100644 index 0000000..33e0039 --- /dev/null +++ b/contrib/logtesting/7/res @@ -0,0 +1,16 @@ +**Phase 1: Completed pre-decoding. + full event: 'MySQL log: 060516 22:38:46 mysqld ended' + hostname: 'melancia' + program_name: '(null)' + log: 'MySQL log: 060516 22:38:46 mysqld ended' + +**Phase 2: Completed decoding. + decoder: 'mysql_log' + +**Phase 3: Completed filtering (rules). + Rule id: '50120' + Level: '12' + Description: 'Database shutdown messge.' +**Alert to be generated. + + diff --git a/contrib/logtesting/8/log b/contrib/logtesting/8/log new file mode 100644 index 0000000..1779e50 --- /dev/null +++ b/contrib/logtesting/8/log @@ -0,0 +1 @@ +Nov 24 18:18:28 gandalf pop3d: LOGIN FAILED, ip=[::ffff:1.2.3.4] diff --git a/contrib/logtesting/8/res b/contrib/logtesting/8/res new file mode 100644 index 0000000..8d62b8d --- /dev/null +++ b/contrib/logtesting/8/res @@ -0,0 +1,17 @@ +**Phase 1: Completed pre-decoding. + full event: 'Nov 24 18:18:28 gandalf pop3d: LOGIN FAILED, ip=[::ffff:1.2.3.4]' + hostname: 'gandalf' + program_name: 'pop3d' + log: 'LOGIN FAILED, ip=[::ffff:1.2.3.4]' + +**Phase 2: Completed decoding. + decoder: 'courier' + srcip: '::ffff:1.2.3.4' + +**Phase 3: Completed filtering (rules). + Rule id: '3902' + Level: '5' + Description: 'Courier (imap/pop3) authentication failed.' +**Alert to be generated. + + diff --git a/contrib/logtesting/9/log b/contrib/logtesting/9/log new file mode 100644 index 0000000..250fedb --- /dev/null +++ b/contrib/logtesting/9/log @@ -0,0 +1 @@ +type=SYSCALL msg=audit(1307045440.943:148): arch=c000003e syscall=59 success=yes exit=0 a0=de1fa8 a1=de23a8 a2=dc3008 a3=7fff1db3cc60 items=2 ppid=11719 pid=12140 auid=4294967295 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=pts8 ses=4294967295 comm="wget" exe="/tmp/wget" key="webserver-watch-tmp" diff --git a/contrib/logtesting/9/res b/contrib/logtesting/9/res new file mode 100644 index 0000000..2f97bf0 --- /dev/null +++ b/contrib/logtesting/9/res @@ -0,0 +1,12 @@ +**Phase 1: Completed pre-decoding. + full event: 'type=SYSCALL msg=audit(1307045440.943:148): arch=c000003e syscall=59 success=yes exit=0 a0=de1fa8 a1=de23a8 a2=dc3008 a3=7fff1db3cc60 items=2 ppid=11719 pid=12140 auid=4294967295 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=pts8 ses=4294967295 comm="wget" exe="/tmp/wget" key="webserver-watch-tmp"' + hostname: 'melancia' + program_name: '(null)' + log: 'type=SYSCALL msg=audit(1307045440.943:148): arch=c000003e syscall=59 success=yes exit=0 a0=de1fa8 a1=de23a8 a2=dc3008 a3=7fff1db3cc60 items=2 ppid=11719 pid=12140 auid=4294967295 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=pts8 ses=4294967295 comm="wget" exe="/tmp/wget" key="webserver-watch-tmp"' + +**Phase 2: Completed decoding. + decoder: 'auditd' + action: 'SYSCALL' + id: '148' + status: 'yes' + extra_data: '/tmp/wget' diff --git a/contrib/logtesting/dotests.sh b/contrib/logtesting/dotests.sh new file mode 100755 index 0000000..e0c65a9 --- /dev/null +++ b/contrib/logtesting/dotests.sh @@ -0,0 +1,35 @@ +#!/bin/sh + +echo "Starting log unit tests (must be run as root and on a system with OSSEC installed)." +echo "(it will make sure the current rules aree working as they should)." +rm -f ./tmpres +for i in ./*/log; do + idir=`dirname $i` + + rm -f ./tmpres || exit "Unable to remove tmpres."; + cat $i | /var/ossec/bin/ossec-logtest 2>&1|grep -v ossec-testrule |grep -A 500 "Phase 1:" > ./tmpres + + if [ ! -f $idir/res ]; then + echo "** Creating entry for $i - Not set yet." + cat ./tmpres > $idir/res + rm -f tmpres + continue; + fi + MD1=`md5sum ./tmpres | cut -d " " -f 1` + MD2=`md5sum $idir/res | cut -d " " -f 1` + + if [ ! $MD1 = $MD2 ]; then + echo "**ERROR: Unit testing failed. Output for the test $i failed." + echo "== OLD OUTPUT: ==" + cat $idir/res + echo "== NEW OUTPUT: ==" + cat tmpres + echo "** ERROR: Exiting." + rm -f tmpres + exit 0; + fi + +done + +echo "" +echo "Log unit tests completed. Everything seems ok (nothing changed since last test regarding the outputs)." diff --git a/contrib/ossec-batch-manager.pl b/contrib/ossec-batch-manager.pl index 6564298..bcc28d8 100755 --- a/contrib/ossec-batch-manager.pl +++ b/contrib/ossec-batch-manager.pl @@ -11,6 +11,28 @@ # started as a hack to properly script manage_agents. # # # # # ########################################################## +# Modified by Tim Meader (Timothy.A.Meader@nasa.gov) +# on 2010/12/08 +# +# - fixed two errors that were popping up during add or +# remove operations due to the code not taking into +# account the old key entries that have the "#*#*#*" +# pattern after the ID number. Simple fix was to do +# a "if (defined(xxx))" on the vars +# - fixed the "list" operation to only show valid key +# entries +# - changed the extract operation to store options +# in an array, and subsequently rewrote the +# "extract_key" (now called "extract_keys") func +# to accept this new behavior +# - modified "extract_keys" func to accept either ID, +# name, or IP address as the argument after the +# "-e" operator. Output of key extraction now +# includes the name and IP address by default in the +# format: "name,IP extracted_key" +# +######################################################### + #$Id$ # TODO: @@ -28,14 +50,14 @@ use Getopt::Long; use constant AUTH_KEY_FILE => "/var/ossec/etc/client.keys"; -my ($key, $add, $remove, $extract, $import, $listagents); +my ($key, $add, $remove, @extracts, $import, $listagents); my ($agentid, $agentname, $ipaddress); GetOptions( 'k|key=s' => \$key, # Unencoded ssh key 'a|add' => \$add, # Add a new agent 'r|remove=s' => \$remove, # Remove an agent - 'e|extract=s' => \$extract, # Extract a key + 'e|extract=s' => \@extracts, # Extract a key 'm|import' => \$import, # Import a key 'l|list' => \$listagents, # List all agents 'i|id=s' => \$agentid, # Unique agent id @@ -48,10 +70,9 @@ if ($listagents) { list_agents(); } # Decode and extract the key for $agentid -elsif ($extract) { - $agentid = $extract; - if ($agentid) { - extract_key($agentid); +elsif (@extracts) { + if (@extracts) { + extract_keys(@extracts); } else { usage(); @@ -79,7 +100,7 @@ elsif ($add) { close(FH); if (@used_agent_ids) { - @used_agent_ids = sort(@used_agent_ids); + @used_agent_ids = sort { $a <=> $b } @used_agent_ids; $agentid = sprintf("%03d", $used_agent_ids[-1] + 1); } } @@ -134,16 +155,16 @@ else { sub usage { warn "Usage: $0 [OPERATION] [OPTIONS]\n"; warn " [operations]\n"; - warn " -a or --add = Add a new agent\n"; - warn " -r or --remove [id] = Remove agent\n"; - warn " -e or --extract [id] = Extract key\n"; - warn " -m or --import [keydata] = Import key\n"; - warn " -l or --list = List available agents\n"; + warn " -a or --add = Add a new agent\n"; + warn " -r or --remove [id] = Remove agent\n"; + warn " -e or --extract [id|name|ip] = Extract key\n"; + warn " -m or --import [keydata] = Import key\n"; + warn " -l or --list = List available agents\n"; warn " [options]\n"; - warn " -k or --key [keydata] = Key data\n"; - warn " -n or --name [name] = Agent name (32 character max)\n"; - warn " -i or --id [id] = Agent identification (integer)\n"; - warn " -p or --ip [ip] = IP address\n\n"; + warn " -k or --key [keydata] = Key data\n"; + warn " -n or --name [name] = Agent name (32 character max)\n"; + warn " -i or --id [id] = Agent identification (integer)\n"; + warn " -p or --ip [ip] = IP address\n\n"; exit 1; } @@ -162,35 +183,56 @@ sub list_agents { while () { chomp; my ($id, $name, $ip, $key) = split; - print "$id", " " x (25 - length($id)), - "$name", " " x (25 - length($name)), - "$ip", " " x (25 - length($ip)) . "\n"; + if (defined($key)) { + print "$id", " " x (25 - length($id)), + "$name", " " x (25 - length($name)), + "$ip", " " x (25 - length($ip)) . "\n"; + } } close(FH); exit 0; } -sub extract_key { - my $extractid = shift; - my ($encoded, $decoded); - +sub extract_keys { if (-r AUTH_KEY_FILE) { open (FH, "<", AUTH_KEY_FILE); } else { die "No ".AUTH_KEY_FILE."!\n"; } - while () { - chomp; - my ($id, $name, $ip, $key) = split; - if ($id == $extractid) { - # Newlines are valid base64 characters so use '' instead for \n - $decoded = MIME::Base64::encode($_, ''); - print "$decoded\n"; - exit 0; + + foreach my $extract (@_) { + my ($encoded, $decoded); + my $found = 0; + + while () { + chomp; + my ($id, $name, $ip, $key) = split; + # Check to make sure it's a valid entry + if (defined($key)) { + if (($extract =~ /^\d+$/) && ($id == $extract)) { + $found = 1; + } + elsif ($name eq $extract) { + $found = 1; + } + elsif ($ip eq $extract) { + $found = 1; + } + else { + next; + } + # Newlines are valid base64 characters so use '' instead for \n + $decoded = MIME::Base64::encode($_, ''); + print "$name,$ip $decoded\n"; + next; + } } + if (!$found) { + warn "Error: Agent $extract doesn't exist!\n"; + } + seek FH,0,0; } - warn "Error: Agent ID $extractid doesn't exist!\n"; } sub add_agent { @@ -282,9 +324,11 @@ sub check_if_exists { while () { chomp; my ($id, $name, $ip, $key) = split; - $rval = 1 if ($id == $newid && $rval == 0); - $rval = 2 if ($name eq $newname && $rval == 0); - $rval = 3 if ($ip eq $newip && $rval == 0); + if(defined($key)) { + $rval = 1 if ($id == $newid && $rval == 0); + $rval = 2 if ($name eq $newname && $rval == 0); + $rval = 3 if ($ip eq $newip && $rval == 0); + } } close(FH); } diff --git a/contrib/ossec2rss.php b/contrib/ossec2rss.php new file mode 100644 index 0000000..c5ab83a --- /dev/null +++ b/contrib/ossec2rss.php @@ -0,0 +1,124 @@ + 30000) +{ + fseek($fh, -30000, SEEK_END); + $line = fgets($fh, 4096); +} + + +$lastlines = array(); +$event = array(); +while($line = fgets($fh, 4096)) +{ + $line = trim($line); + if($line == "") + { + continue; + } + + if(strncmp($line, "** Alert ", 9) == 0) + { + if(strncmp($event, "** Alert ", 9) == 0) + { + array_push($lastlines, $event); + } + unset($event); + $event = array(); + $event[] = htmlspecialchars($line); + } + else + { + $event[] = htmlspecialchars($line); + } +} +fclose($fh); + +$lastlines = array_reverse($lastlines); +$myhost = gethostname(); +if($myhost === FALSE) +{ + $myhost = ""; +} + +echo ' + + + +OSSEC '.$myhost.' RSS Feed +http://ossec.net +OSSEC RSS Feed for '.$myhost.' +en-us +'.date("r", $timelp).' +'.date("r", $timelp).' +(C) OSSEC.net 2008-2011 +OSSEC.net RSS feed +30 +dcid@ossec.net + + + OSSEC Alert Feed + http://www.ossec.net/img/ossec_logo.jpg + http://ossec.net + +'; + +foreach($lastlines as $myentry) +{ +echo $myentry; + + if(preg_match("/^.. Alert (\d+)\./", $myentry[0], $regs, PREG_OFFSET_CAPTURE, 0)) + { + $myunixtime = $regs[1][0]; + } + else + { + continue; + } + + + echo ' + + '.$myentry[2]." ,from ".substr($myentry[1], 20).' + http://ossec.net + '.$myentry[0].' + \n"; } + + echo ' + ]]> + '.date("r", $myunixtime).' + + '; +} + +echo ' + + +'; + + +?> diff --git a/contrib/ossec_report_contrib.pl b/contrib/ossec_report_contrib.pl index 4278dfb..0ec061b 100755 --- a/contrib/ossec_report_contrib.pl +++ b/contrib/ossec_report_contrib.pl @@ -27,8 +27,8 @@ while(<>){ $stats{$alerthost}{rule}{$rule}++; $stats{$alerthost}{level}{$level}++; $stats{$alerthost}{description}{$description}++; - $stats{$alerthost}{srcip}{$srcip}++; - $stats{$alerthost}{user}{$user}++; + if (defined $srcip) { $stats{$alerthost}{srcip}{$srcip}++; } + if (defined $user) { $stats{$alerthost}{user}{$user}++; } next ; } if (m/^\*\* Alert ([0-9]+).([0-9]+):(.*)$/){ diff --git a/contrib/util.sh b/contrib/util.sh new file mode 100755 index 0000000..f4d1030 --- /dev/null +++ b/contrib/util.sh @@ -0,0 +1,182 @@ +#!/bin/sh +# Simple utilities +# Add a new file +# Add a new remote host to be monitored via lynx +# Add a new remote host to be monitored (DNS) +# Add a new command to be monitored +# by Daniel B. Cid - dcid ( at ) ossec.net + +ACTION=$1 +FILE=$2 +FORMAT=$3 + +if [ "X$FILE" = "X" ]; then + echo "$0: addfile []" + echo "$0: addsite " + echo "$0: adddns " + #echo "$0: addcommand " + echo "" + #echo "Example: $0 addcommand 'netstat -tan |grep LISTEN| grep -v 127.0.0.1'" + echo "Example: $0 adddns ossec.net" + echo "Example: $0 addsite dcid.me" + exit 1; +fi + +if [ "X$FORMAT" = "X" ]; then + FORMAT="syslog" +fi + +# Adding a new file +if [ $ACTION = "addfile" ]; then + # Checking if file is already configured + grep "$FILE" /var/ossec/etc/ossec.conf > /dev/null 2>&1 + if [ $? = 0 ]; then + echo "$0: File $FILE already configured at ossec." + exit 1; + fi + + # Checking if file exist + ls -la $FILE > /dev/null 2>&1 + if [ ! $? = 0 ]; then + echo "$0: File $FILE does not exist." + exit 1; + fi + + echo " + + + $FORMAT + $FILE + + + " >> /var/ossec/etc/ossec.conf + + echo "$0: File $FILE added."; + exit 0; +fi + + +# Adding a new DNS check +if [ $ACTION = "adddns" ]; then + COMMAND="host -W 5 -t NS $FILE; host -W 5 -t A $FILE | sort" + echo $FILE | grep -E '^[a-z0-9A-Z.-]+$' >/dev/null 2>&1 + if [ $? = 1 ]; then + echo "$0: Invalid domain: $FILE" + exit 1; + fi + + grep "host -W 5 -t NS $FILE" /var/ossec/etc/ossec.conf >/dev/null 2>&1 + if [ $? = 0 ]; then + echo "$0: Already configured for $FILE" + exit 1; + fi + + MYERR=0 + echo " + + + full_command + $COMMAND + + + " >> /var/ossec/etc/ossec.conf || MYERR=1; + + if [ $MYERR = 1 ]; then + echo "$0: Unable to modify the configuration file."; + exit 1; + fi + + FIRSTRULE="150010" + while [ 1 ]; do + grep "\"$FIRSTRULE\"" /var/ossec/rules/local_rules.xml > /dev/null 2>&1 + if [ $? = 0 ]; then + FIRSTRULE=`expr $FIRSTRULE + 1` + else + break; + fi + done + + + echo " + + + 530 + + ^ossec: output: 'host -W 5 -t NS $FILE + DNS Changed for $FILE + + + " >> /var/ossec/rules/local_rules.xml || MYERR=1; + + if [ $MYERR = 1 ]; then + echo "$0: Unable to modify the local rules file."; + exit 1; + fi + + echo "Domain $FILE added to be monitored." + exit 0; +fi + + +# Adding a new lynx check +if [ $ACTION = "addsite" ]; then + COMMAND="lynx --connect_timeout 10 --dump $FILE | head -n 10" + echo $FILE | grep -E '^[a-z0-9A-Z.-]+$' >/dev/null 2>&1 + if [ $? = 1 ]; then + echo "$0: Invalid domain: $FILE" + exit 1; + fi + + grep "lynx --connect_timeout 10 --dump $FILE" /var/ossec/etc/ossec.conf >/dev/null 2>&1 + if [ $? = 0 ]; then + echo "$0: Already configured for $FILE" + exit 1; + fi + + MYERR=0 + echo " + + + full_command + $COMMAND + + + " >> /var/ossec/etc/ossec.conf || MYERR=1; + + if [ $MYERR = 1 ]; then + echo "$0: Unable to modify the configuration file."; + exit 1; + fi + + FIRSTRULE="150010" + while [ 1 ]; do + grep "\"$FIRSTRULE\"" /var/ossec/rules/local_rules.xml > /dev/null 2>&1 + if [ $? = 0 ]; then + FIRSTRULE=`expr $FIRSTRULE + 1` + else + break; + fi + done + + + echo " + + + 530 + + ^ossec: output: 'lynx --connect_timeout 10 --dump $FILE + DNS Changed for $FILE + + + " >> /var/ossec/rules/local_rules.xml || MYERR=1; + + if [ $MYERR = 1 ]; then + echo "$0: Unable to modify the local rules file."; + exit 1; + fi + + echo "Domain $FILE added to be monitored." + exit 0; +fi + + diff --git a/doc/README.config b/doc/README.config old mode 100755 new mode 100644 diff --git a/doc/active-response-internal.txt b/doc/active-response-internal.txt old mode 100755 new mode 100644 diff --git a/doc/active-response.txt b/doc/active-response.txt old mode 100755 new mode 100644 diff --git a/doc/br/INSTALL.br b/doc/br/INSTALL.br old mode 100755 new mode 100644 diff --git a/doc/br/README.config b/doc/br/README.config old mode 100755 new mode 100644 diff --git a/doc/br/TRANSLATION b/doc/br/TRANSLATION old mode 100755 new mode 100644 diff --git a/doc/br/active-response-internal.txt b/doc/br/active-response-internal.txt old mode 100755 new mode 100644 diff --git a/doc/br/active-response.txt b/doc/br/active-response.txt old mode 100755 new mode 100644 diff --git a/doc/br/logs.txt b/doc/br/logs.txt old mode 100755 new mode 100644 diff --git a/doc/br/manager.txt b/doc/br/manager.txt old mode 100755 new mode 100644 diff --git a/doc/br/rootcheck.txt b/doc/br/rootcheck.txt old mode 100755 new mode 100644 diff --git a/doc/br/rule_ids.txt b/doc/br/rule_ids.txt old mode 100755 new mode 100644 diff --git a/doc/br/rules.txt b/doc/br/rules.txt old mode 100755 new mode 100644 diff --git a/doc/logs.txt b/doc/logs.txt old mode 100755 new mode 100644 diff --git a/doc/manage_agents.txt b/doc/manage_agents.txt new file mode 100644 index 0000000..3ff392f --- /dev/null +++ b/doc/manage_agents.txt @@ -0,0 +1,32 @@ + +== How to add an agent without any keyboard input == + +By default, to add an agent from server side, you must provide your agent +information to `manage_agents` program, by using its interactive mode. +This is really tedious if you have many servers / agents to add. Luckily, +you can use following environment variables as responses + + | variable name | value | description | + +------------------------+---------+----------------------+ + | OSSEC_ACTION | A/a | add an agent | + | OSSEC_AGENT_NAME | string | name of agent | + | OSSEC_AGENT_IP | CIDR | ip address of agent | + | OSSEC_AGENT_ID | integer | max length = 8 | + | OSSEC_AGENT_KEY | string | base64 format | (*) + | OSSEC_ACTION_CONFIRMED | y/Y/n/N | y -> confirmed | + + (*) OSSEC_AGENT_KEY is used only on agent (when key is being imported) + +Please note that it's your duty to ensure that name, ip,... of agent are +valid. Otherwise, the program will fall back to interactive mode. In most +case, you should ensure that you new agent has an unique name/id. You can +simply know that by using `manage_agents -l` to list all known agents. + +For more details, please refer to OSSEC document + http://www.ossec.net/doc/manual/agent/agent-management.html + +PS: you may use some tools (`expect`) to send strings to `manage_agents`, +insead of using the above environment variables. It's your choice. + +-- +Anh K. Huynh diff --git a/doc/manager.txt b/doc/manager.txt old mode 100755 new mode 100644 diff --git a/doc/nmap.txt b/doc/nmap.txt old mode 100755 new mode 100644 diff --git a/doc/pl/INSTALL.pl b/doc/pl/INSTALL.pl old mode 100755 new mode 100644 diff --git a/doc/pl/README.config b/doc/pl/README.config old mode 100755 new mode 100644 diff --git a/doc/pl/TRANSLATION b/doc/pl/TRANSLATION old mode 100755 new mode 100644 diff --git a/doc/pl/active-response-internal.txt b/doc/pl/active-response-internal.txt old mode 100755 new mode 100644 diff --git a/doc/pl/active-response.txt b/doc/pl/active-response.txt old mode 100755 new mode 100644 diff --git a/doc/pl/logs.txt b/doc/pl/logs.txt old mode 100755 new mode 100644 diff --git a/doc/pl/manager.txt b/doc/pl/manager.txt old mode 100755 new mode 100644 diff --git a/doc/pl/rootcheck.txt b/doc/pl/rootcheck.txt old mode 100755 new mode 100644 diff --git a/doc/pl/rule_ids.txt b/doc/pl/rule_ids.txt old mode 100755 new mode 100644 diff --git a/doc/pl/rules.txt b/doc/pl/rules.txt old mode 100755 new mode 100644 diff --git a/doc/rootcheck.txt b/doc/rootcheck.txt old mode 100755 new mode 100644 diff --git a/doc/rule_ids.txt b/doc/rule_ids.txt old mode 100755 new mode 100644 diff --git a/doc/rules.txt b/doc/rules.txt old mode 100755 new mode 100644 diff --git a/etc/decoder.xml b/etc/decoder.xml index cb07a93..669508e 100755 --- a/etc/decoder.xml +++ b/etc/decoder.xml @@ -1,4 +1,4 @@ - + pam rhost=\S+\s+user=\S+ @@ -75,7 +83,6 @@ srcip - @@ -188,6 +215,55 @@ srcip + + sshd + ^Connection closed + ^by (\S+)$ + srcip + + + + sshd + ^Received disconnect + ^from (\S+): + srcip + + + + + + sshd + ^pam_ldap: + user "uid=(\S+),ou=\w+,dc=\w+,dc=\w+" + user + + + + + + ^dropbear + + + + dropbear + for '(\S+)' from (\S+):\d+$ + dstuser,srcip + + + ^\S+ [(\d+.\d+.\d+.\d+)]$|^(\S+) srcip @@ -474,6 +575,8 @@ - arpwatch: new station 192.168.1.103 0:11:43:5e:5d:80 eth0 - arpwatch: bogon 172.16.150.149 0:2:b3:d6:e5:68 eth0 - arpwatch: new station 192.168.2.10 0:c0:4f:78:32:be + - arpwatch: pcap open re0: /dev/bpf0: Permission denied + - arpwatch: reused old ethernet address 192.168.17.248 0:e:3b:a:cb:67 (0:1e:8c:72:b0:d0) --> ^arpwatch @@ -675,11 +778,21 @@ - Examples: - valhalla named[7885]: client 192.168.1.231#1142: update 'hayaletgemi.edu/IN' denied - named[12637]: client 1.2.3.4#32769: query (cache) 'somedomain.com/MX/IN' denied + - Oct 22 10:12:33 junction named[31687]: /etc/blocked.slave:9892: syntax error near ';' + - Oct 22 10:12:33 junction named[31687]: reloading configuration failed: unexpected token --> ^named + + named + : query: + client (\S+)#\d+: query: (\S+) IN + srcip,url + + + named ^client @@ -693,6 +806,12 @@ srcip + + named + for master + for master (\d+.\d+.\d+.\d+):(\d+) \S+ \(source (\d+.\d+.\d+.\d+)#d+\)$ + dstip,dstport,srcip + + + + smtpd + + + + smtpd + ^client + ^client (\S+) + srcip + + + + smtpd + relay= + relay=\S+ [(\S+)], + srcip + + + + + + + ^isakmpd + + + + isakmpd + message from + from (\S+) port (\d+) + srcip,srcport + + + + isakmpd + from peer + from peer (\S+):(\d+)$ + srcip,srcport + + + + web-log - ^\d+.\d+.\d+.\d+ + ^\d+.\d+.\d+.\d+ |^::ffff:\d+.\d+.\d+.\d+ ^(\d+.\d+.\d+.\d+) \S+ \S+ [\S+ \S\d+] "\w+ (\S+) HTTP\S+ (\d+) srcip, url, id @@ -1640,12 +1829,30 @@ name, location, extra_data + + ossec + ^ossec: Alert Level: + OSSECAlert_Decoder + + ^ossec$ OSSECAlert_Decoder + + + ^Mon|^Tue|^Wed|^Thu|^Fri|^Sat|^Sun \S+\s+\d+ \d\d:\d\d:\d\d \S+ \d+ /\.+/active-response + /bin/(\S+) (\S+) - (\S+) (\d+.\d+) (\d+) + action, status, srcip, id, extra_data + - ^\d\d,\d+/\d+/\d\d\d\d,\d+:\d+:\d+, - ^(\d\d), - id + ^\d\d,\d+/\d+/\d\d\d\d,\d+:\d+:\d+,| + ^\d\d,\d+/\d+/\d\d,\d+:\d+:\d+, + ^(\d\d),\d+/\d+/\d\d\d*,\d+:\d+:\d+,(\w+),(\d+.\d+.\d+.\d+) + id,extra_data,srcip -11020,05/05/09,00:00:38,DHCPV6 ^\d\d\d\d\d,\d\d/\d\d/\d\d,\d\d:\d\d:\d\d, ^(\d\d\d\d\d), @@ -1935,5 +2161,272 @@ in HTTP request too long; attack: Malformed HTTP; src: 10.10.10.4; dst: + + + ^/bsd + + + + bsd_kernel + ^arp + for (\S+) by (\S+) on \S+ + dstip, extra_data + + + + + + + ^mountd + + + + mountd + from host + (\S+) port \d+$ + srcip + + + + + + + ^bro + + + + bro-ids + no=PortscanSummary + sa=(\S+) num=(\d+) msg= + srcip,extra_data + + + + bro-ids + no=PortScan + sa=(\S+) p=(\d+)/(\S+) num=(\d+) + srcip,srcport,protocol,extra_data + + + + bro-ids + na=NOTICE + sa=(\S+) sp=(\d+)/(\S+) da=(\S+) dp=(\d+)/\S+ + srcip,srcport,protocol,dstip,dstport + + + + + + + + + + + + groupdel + ^group deleted: name=(\S+)$ + extra_data + + + + + + ^portsentry + + + + portsentry + attackalert: Connect from host: + (\S+)/\S+ to (\S+) port: (\d+)$ + srcip,protocol,dstport + + + + portsentry + is already blocked. Ignoring$ + Host: (\S+) is + srcip + + + + + + ^clamd + + + + ^freshclam + + + + + + ^slapd + ^conn=(\d+) + id + + + + + + + ^ntpd + + + + ntpd + ^bad peer + ^bad peer \S+ \p(\S+)\p$|^bad peer from pool \S+ \p(\S+)\p$ + srcip + + + + +type=USER_ACCT msg=audit(1310592861.936:1222): user pid=24675 uid=0 auid=501 ses=188 subj=system_u:system_r:unconfined_t:s0 msg='op=PAM:accounting acct="username" exe="/usr/bin/sudo" (hostname=?, addr=?, terminal=pts/5 res=success)' +type=CRED_ACQ msg=audit(1305666154.831:51859): user pid=21250 uid=0 auid=4294967295 subj=system_u:system_r:unconfined_t:s0-s0:c0.c1023 msg='PAM: setcred acct="username" : exe="/usr/sbin/sshd" (hostname=lala.example.com, addr=172.16.0.1, terminal=ssh res=success)' +type=CRED_ACQ msg=audit(1273182001.226:148635): user pid=29770 uid=0 auid=4294967295 subj=system_u:system_r:crond_t:s0-s0:c0.c1023 msg='PAM: setcred acct="root" : exe="/usr/sbin/crond" (hostname=?, addr=?, terminal=cron +type=USER_AUTH msg=audit(1305666163.690:51871): user pid=21269 uid=0 auid=500 subj=user_u:system_r:unconfined_t:s0 msg='PAM: authentication acct="root" : exe="/bin/su" (hostname=?, addr=?, terminal=pts/0 res=success)' +type=USER_ACCT msg=audit(1306939201.750:67934): user pid=4401 uid=0 auid=4294967295 subj=system_u:system_r:crond_t:s0-s0:c0.c1023 msg='PAM: accounting acct="root" : exe="/usr/sbin/crond" (hostname=?, addr=?, terminal=cron res=success)' +type=CRED_ACQ msg=audit(1306939201.751:67935): user pid=4401 uid=0 auid=4294967295 subj=system_u:system_r:crond_t:s0-s0:c0.c1023 msg='PAM: setcred acct="root" : exe="/usr/sbin/crond" (hostname=?, addr=?, terminal=cron res=success)' +type=USER_START msg=audit(1306939201.756:67937): user pid=4401 uid=0 auid=0 subj=system_u:system_r:crond_t:s0-s0:c0.c1023 msg='PAM: session open acct="root" : exe="/usr/sbin/crond" (hostname=?, addr=?, terminal=cron res=success)' +type=USER_CHAUTHTOK msg=audit(1304523288.952:37394): user pid=7258 uid=0 auid=500 subj=user_u:system_r:unconfined_t:s0 msg='op=change password id=505 exe="/usr/bin/passwd" (hostname=?, addr=?, terminal=pts/1 res=success)' + + +type=USER_ACCT msg=audit(1310592861.936:1222): user pid=24675 uid=0 auid=501 ses=188 subj=system_u:system_r:unconfined_t:s0 msg='op=PAM:accounting acct="username" exe="/usr/bin/sudo" (hostname=?, addr=?, terminal=pts/5 res=success)' + + +type=SYSCALL msg=audit(1307045440.943:148): arch=c000003e syscall=59 success=yes exit=0 a0=de1fa8 a1=de23a8 a2=dc3008 a3=7fff1db3cc60 items=2 ppid=11719 pid=12140 auid=4294967295 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=pts8 ses=4294967295 comm="wget" exe="/tmp/wget" key="webserver-watch-tmp" +type=SYSCALL msg=audit(1307045820.403:151): arch=c000003e syscall=59 success=no exit=-13 a0=de24c8 a1=de2408 a2=dc3008 a3=7fff1db3cc60 items=1 ppid=11719 pid=12347 auid=4294967295 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=pts8 ses=4294967295 comm="bash" exe="/bin/bash" key=(null) +type=SYSCALL msg=audit(1306939143.715:67933): arch=40000003 syscall=94 success=yes exit=0 a0=5 a1=180 a2=8ebd360 a3=8ec4978 items=1 ppid=4383 pid=4388 auid=500 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=pts0 ses=8038 comm="less" exe="/usr/bin/less" subj=user_u:system_r:unconfined_t:s0 key="perm_mod" +type=USER_ROLE_CHANGE msg=audit(1280266360.845:51): user pid=1978 uid=0 auid=500 subj=system_u:system_r:local_login_t:s0-s0:c0.c1023 msg='pam: default-context=user_u:system_r:unconfined_t:s0 selected-context=user_u:system_r:unconfined_t:s0: exe="/bin/login" (hostname=?, addr=?, terminal=tty1 res=success)' +type=PATH msg=audit(1306967989.163:119): item=0 name="./ls" inode=261813 dev=fb:00 mode=0100755 ouid=0 ogid=0 rdev=00:00 + + +type=PATH msg=audit(1273924468.947:179534): item=0 name=(null) inode=424783 dev=fd:07 mode=0100640 ouid=0 ogid=502 rdev=00:00 obj=user_u:object_r:file_t:s0 + +--> + + + ^type= + + + + + auditd + ^AVC + ^(AVC) msg=audit\(\d\d\d\d\d\d\d\d\d\d.\d\d\d:(\d+)\): avc: (\S+) { \.+ } for pid=\d+ comm="(\S+)" path="\S+" dev=\S+ ino=\d+ scontext=\S+ tcontext=\S+ tclass=\S+$ + action,id,status,extra_data + + + + + auditd + ^SYSCALL + ^(SYSCALL) msg=audit\(\d\d\d\d\d\d\d\d\d\d.\d\d\d:(\d+)\): arch=\w+ syscall=\d+ success=(\S+) exit=\S+ a0=\w+ a1=\w+ a2=\w+ a3=\w+ items=\d+ ppid=\d+ pid=\d+ auid=\d+ uid=\d+ gid=\d+ euid=\d+ suid=\d+ fsuid=\d+ egid=\d+ sgid=\d+ fsgid=\d+ tty=\S+ ses=\d+ comm="\S+" exe="(\.+)" + action,id,status,extra_data + + + + + auditd + ^CONFIG_CHANGE + ^(CONFIG_CHANGE) msg=audit\(\d\d\d\d\d\d\d\d\d\d.\d\d\d:(\d+)\): auid=\d+ ses=\d+ op="\.+" path="(\.+)" key="\S+" list=\d+ res=\d+$ + action,id,extra_data + + + + + auditd + ^PATH + ^(PATH) msg=audit\(\d\d\d\d\d\d\d\d\d\d.\d\d\d:(\d+)\): item=\d+ name="(\.+)" inode=\d+ dev=\S+ mode=\d+ ouid=\d+ ogid=\d+ rdev=\S+ + action,id,extra_data + + + + + auditd + ^(USER_\S+) msg=audit\(\d\d\d\d\d\d\d\d\d\d.\d\d\d:(\d+)\): user pid=\d+ uid=\d+ auid=\d+| + ^(CRED_\S+) msg=audit\(\d\d\d\d\d\d\d\d\d\d.\d\d\d:(\d+)\): user pid=\d+ uid=\d+ auid=\d+ + action,id + + + + auditd + acct="(\.+)" : exe="(\.+)" \(hostname=\S+, addr=(\S+), terminal=\S+$ + user,extra_data,srcip + + + + auditd + ses=\d+ subj=\S+ msg='\.+ acct="(\.+)" exe="(\.+)" hostname=\S+ addr=(\S+) terminal=\S+ res=(\S+)$ + user,extra_data,srcip,status + + + + auditd + subj=\S+ msg='\.+ acct="(\.+)" \p*\s*exe="(\.+)" \(hostname=\S+, addr=(\S+), terminal=\S+ res=(\S+)\)'$ + user,extra_data,srcip,status + + + + auditd + subj=\S+ msg='\.+ exe="(\.+)" \(hostname=\S+, addr=(\S+), terminal=\S+ res=(\S+)\)'$ + extra_data,srcip,status + diff --git a/etc/internal_options.conf b/etc/internal_options.conf index e404271..a826f36 100755 --- a/etc/internal_options.conf +++ b/etc/internal_options.conf @@ -34,6 +34,10 @@ logcollector.loop_timeout=2 # Logcollector number of attempts to open a log file. logcollector.open_attempts=8 +# Logcollector - If it should accept remote commands from the manager +logcollector.remote_commands=0 + + # Remoted counter io flush. remoted.recv_counter_flush=128 @@ -55,6 +59,9 @@ maild.groupping=1 # Maild full subject (0=disabled, 1=enabled) maild.full_subject=0 +# Maild display GeoIP data (0=disabled, 1=enabled) +maild.geoip=1 + # Monitord day_wait. Ammount of seconds to wait before compressing/signing # the files. diff --git a/etc/ossec-local.conf b/etc/ossec-local.conf index f800f48..2096e64 100755 --- a/etc/ossec-local.conf +++ b/etc/ossec-local.conf @@ -33,6 +33,7 @@ vmpop3d_rules.xml courier_rules.xml web_rules.xml + web_appsec_rules.xml apache_rules.xml nginx_rules.xml php_rules.xml diff --git a/etc/ossec-server.conf b/etc/ossec-server.conf index 4703df8..1a4998c 100755 --- a/etc/ossec-server.conf +++ b/etc/ossec-server.conf @@ -33,6 +33,7 @@ vmpop3d_rules.xml courier_rules.xml web_rules.xml + web_appsec_rules.xml apache_rules.xml nginx_rules.xml php_rules.xml diff --git a/etc/ossec.conf b/etc/ossec.conf index 3136722..d010d27 100755 --- a/etc/ossec.conf +++ b/etc/ossec.conf @@ -18,6 +18,7 @@ pure-ftpd_rules.xml proftpd_rules.xml web_rules.xml + web_appsec_rules.xml apache_rules.xml ids_rules.xml squid_rules.xml diff --git a/etc/preloaded-vars.conf b/etc/preloaded-vars.conf index d5cb0d2..45a2f7e 100755 --- a/etc/preloaded-vars.conf +++ b/etc/preloaded-vars.conf @@ -75,9 +75,18 @@ ### Agent Installation variables. ### -# USER_AGENT_SERVER_IP specifies the IP address of the +# Specifies the IP address or hostname of the # ossec server. Only used on agent installations. -#USER_AGENT_SERVER_IP="1.2.3.4" +# Choose only one, not both. +# USER_AGENT_SERVER_IP="1.2.3.4" +# USER_AGENT_SERVER_NAME + + +# USER_AGENT_CONFIG_PROFILE specifies the agent's config profile +# name. This is used to create agent.conf configuration profiles +# for this particular profile name. Only used on agent installations. +# Can be any string. E.g. LinuxDBServer or WindowsDomainController +#USER_AGENT_CONFIG_PROFILE="generic" diff --git a/etc/rules/apache_rules.xml b/etc/rules/apache_rules.xml index f823886..425c0b9 100755 --- a/etc/rules/apache_rules.xml +++ b/etc/rules/apache_rules.xml @@ -1,4 +1,5 @@ - diff --git a/etc/rules/asterisk_rules.xml b/etc/rules/asterisk_rules.xml index 3582766..bed0e71 100755 --- a/etc/rules/asterisk_rules.xml +++ b/etc/rules/asterisk_rules.xml @@ -1,4 +1,5 @@ - + + + 6201 + No registration for peer + Login session failed (invalid iax user). + invalid_login, + + + + + 6253 + + Extension IAX Enumeration. + + + + + 6202 + Don't know how to respond via + Possible Registration Hijacking. + invalid_login, + + + + + 6201 + failed MD5 authentication + IAX peer Wrong Password. + invalid_login, + + + + + 6256 + + Multiple failed logins. + + diff --git a/etc/rules/attack_rules.xml b/etc/rules/attack_rules.xml index 016d214..fe4d65d 100755 --- a/etc/rules/attack_rules.xml +++ b/etc/rules/attack_rules.xml @@ -1,4 +1,5 @@ - + + + + + bro-ids + Grouping for all bro-ids events. + + + + 52000 + Starting incremental serialization + Bro-ids has been started. + + + + 52000 + Finished incremental serialization + Bro-ids has been stopped. + + + + 52000 + msg=AckAboveHole + XXX Ack Above Hole + + + + 52000 + msg=ContentGap + XXX Content Gap + + + + 52000 + no=ResourceSummary + Bro-ids resource summary. + + + + 52000 + no=PortScanSummary + Bro-ids port scan summary. + + + + 52000 + no=ZoneTransfer + Bro-ids Zone Transfer alert. + + + + 52000 + no=SensitivePortMapperAccess + Bro-ids detected acces to the portmapper port. + + + + 52000 + no=PortScan + Bro-ids detected a portscan. + + + + + + + diff --git a/etc/rules/cimserver_rules.xml b/etc/rules/cimserver_rules.xml index 0cc1dde..0516c8c 100755 --- a/etc/rules/cimserver_rules.xml +++ b/etc/rules/cimserver_rules.xml @@ -1,4 +1,5 @@ - diff --git a/etc/rules/courier_rules.xml b/etc/rules/courier_rules.xml index eb29f24..2212d32 100755 --- a/etc/rules/courier_rules.xml +++ b/etc/rules/courier_rules.xml @@ -1,4 +1,5 @@ - + + + + + + + + + dropbear + Grouping for dropbear rules. + + + + 51000 + Failed to get kex value + Failed to get key exchange value + + + + 51000 + Premature kexdh_init message received + Premature kexdh_init message + + + + 51000 + bad password attempt for + Bad password attempt. + authentication_failed, + + + + 51003 + + dropbear brute force attempt. + authentication_failures, + + + + 51000 + exit after auth \(\S+\): Disconnect received + User disconnected. + + + + 51000 + exit before auth + Client exited before authentication. + recon, + + + + 51000 + + dropbear brute force attempt. + authentication_failures, + + + + + 51000 + Incompatible remote version + Incompatible remote version. + recon, + + + + 51000 + password auth succeeded for + User successfully logged in using a password. + authentication_success, + + + + + + + diff --git a/etc/rules/firewall_rules.xml b/etc/rules/firewall_rules.xml index f3a1b4d..d4bb435 100755 --- a/etc/rules/firewall_rules.xml +++ b/etc/rules/firewall_rules.xml @@ -1,4 +1,5 @@ - -^259|^100|^1000|^1001|^1002|^1003|^1004|^1005|^1006|^1007|^1008|^5003|^5005|^5008|^5010|^5011|^5019|^5020|^5021|^5022|^5030|^5031|^5032|^5033|^5034|^5035|^5046|^5047|^5048|^5049|^5051|^5054|^5057|^5059|^5060|^5063|^5063 -^258|^5001|^5028|^5036|^5037|^5038|^5039|^5040|^5041|^5053|^5056|^5061|^5062|^5065 -^257|^5000|^5026|^5052|^5055 +^259$|^100$|^1000$|^1001$|^1002$|^1003$|^1004$|^1005$|^1006$|^1007$|^1008$|^5003$|^5005$|^5008$|^5010$|^5011$|^5019$|^5020$|^5021$|^5022$|^5030$|^5031$|^5032$|^5033$|^5034$|^5035$|^5046$|^5047$|^5048$|^5049$|^5051$|^5054$|^5057$|^5059$|^5060$|^5063$|^5063$ +^258$|^5001$|^5028$|^5036$|^5037$|^5038$|^5039$|^5040$|^5041$|^5053$|^5056$|^5061$|^5062$|^5065$ +^257$|^5000$|^5026$|^5052$|^5055$ quarantined|moved to quarantine|file was deleted|deleted successfully|has been deleted|message deleted|deleted after|cleaned|successfully deleted The file \.+ contain|infected with|User defined detection|scan found|error attempting to clean 10 @@ -76,7 +77,7 @@ McAfee Windows AV - Scan completed with no viruses found. - + 7500 scan was cancelled |has taken too long McAfee Windows AV - Virus scan cancelled. diff --git a/etc/rules/ms-exchange_rules.xml b/etc/rules/ms-exchange_rules.xml index e0f46db..1ef5b05 100755 --- a/etc/rules/ms-exchange_rules.xml +++ b/etc/rules/ms-exchange_rules.xml @@ -1,4 +1,5 @@ - 18106 - ^529 + ^529$ Logon Failure - Unknown user or bad password. http://www.ultimatewindowssecurity.com/events/com190.html win_authentication_failed, @@ -209,7 +210,7 @@ 18106 - ^530 + ^530$ Logon Failure - Account logon time restriction violation. http://www.ultimatewindowssecurity.com/events/com191.html @@ -218,7 +219,7 @@ 18106 - ^531 + ^531$ Logon Failure - Account currently disabled. http://www.ultimatewindowssecurity.com/events/com192.html win_authentication_failed,login_denied, @@ -226,7 +227,7 @@ 18106 - ^532 + ^532$ Logon Failure - Specified account expired. http://www.ultimatewindowssecurity.com/events/com193.html win_authentication_failed,login_denied, @@ -234,7 +235,7 @@ 18106 - ^533 + ^533$ Logon Failure - User not allowed to login at this computer. http://www.ultimatewindowssecurity.com/events/com194.html @@ -243,7 +244,7 @@ 18106 - ^534 + ^534$ Logon Failure - User not granted logon type. http://www.ultimatewindowssecurity.com/events/com195.html win_authentication_failed, @@ -251,7 +252,7 @@ 18106 - ^535 + ^535$ Logon Failure - Account's password expired. http://www.ultimatewindowssecurity.com/events/com196.html win_authentication_failed, @@ -259,35 +260,35 @@ 18106 - ^536|^537 + ^536$|^537$ Logon Failure - Internal error. win_authentication_failed, 18106 - ^539 + ^539$ Logon Failure - Account locked out. win_authentication_failed, 18105 - ^672|^673|^675|^676|^681|^4769 + ^672$|^673$|^675$|^676$|^681$|^4769$ Windows DC Logon Failure. win_authentication_failed, - + 18104 - ^520 + ^520$ System time changed. time_changed, 18102 - ^1076 + ^1076$ unexpected shutdown system_error, system_shutdown, Unexpected Windows shutdown. @@ -295,7 +296,7 @@ 18104 - ^671|^4767 + ^671$|^4767$ User account unlocked. http://www.ultimatewindowssecurity.com/events/com291.html account_changed, @@ -303,14 +304,14 @@ 18114 - ^631|^635|^658 + ^631$|^635$|^658$ Security enabled group created. adduser,account_changed, 18114 - ^634|^638|^662 + ^634$|^638$|^662$ Security enabled group deleted. adduser,account_changed, @@ -318,7 +319,7 @@ 18101 - ^7040 + ^7040$ policy_changed, Service startup type was changed. This does not appear to be logged on Windows 2000. @@ -326,27 +327,27 @@ 18101 - ^11724 + ^11724$ alert_by_email Application Uninstalled. 18101 - ^11707 + ^11707$ alert_by_email Application Installed. 18104 - ^4608 + ^4608$ Windows is starting up. 18104 - ^538|^4634|^4647 + ^538$|^4634$|^4647$ Windows User Logoff. @@ -490,7 +491,7 @@ 18207,18208 - ID:\s+\p*S-1-5-32-544\p* + ID:\s+\p*S-1-5-32-544 Administrators Group Changed group_changed,win_group_changed, http://support.microsoft.com/kb/243330 @@ -812,7 +813,7 @@ --> 18107,18149 - ^528|^538|^540 + ^528$|^538$|^540$ ^LOCAL SERVICE|^NETWORK SERVICE|^ANONYMOUS LOGON Windows Logon Success (ignored). @@ -848,14 +849,14 @@ 18105 - ^18456 + ^18456$ win_authentication_failed, MS SQL Server Logon Failure. 18104 - ^18454|^18453 + ^18454$|^18453$ MS SQL Server Logon Success. authentication_success, diff --git a/etc/rules/mysql_rules.xml b/etc/rules/mysql_rules.xml index 2286a25..f9c3742 100755 --- a/etc/rules/mysql_rules.xml +++ b/etc/rules/mysql_rules.xml @@ -1,4 +1,5 @@ - - + 12100 - query (cache) denied - Query cache denied (maybe config error). + query (cache) denied|: query (cache) + Query cache denied (probably config error). http://www.reedmedia.net/misc/dns/errors.html @@ -100,5 +100,218 @@ ^zone \S+: expired Zone transfer error. - + + + 12100 + zone transfer deferred due to quota + Zone transfer deferred. + + + + 12100 + bad owner name (check-names) + Hostname contains characters that check-names does not like. + + + + 12100 + loaded serial|transferred serial + Zone transfer. + + + + 12100 + syntax error near| + reloading configuration failed: unexpected token + Syntax error in a named configuration file. + + + + + 12100 + refresh: retry limit for master \S+ exceeded + Zone transfer rety limit exceeded + + + + 12100 + already exists previous definition + Zone has been duplicated. + + + + 12100 + starting BIND + BIND has been started + + + + 12100 + has no address records + Missing A or AAAA record + + + + 12100 + zone \S+: \(master\) removed + Zone has been removed from a master server + + + + 12100 + loading from master file \S+ failed: not at top of zone$ + Origin of zone and owner name of SOA do not match. + + + + 12100 + already exists previous definition + Zone has been duplicated + + + + 12100 + reloading configuration failed: unexpected end of input + BIND Configuration error. + + + + 12100 + zone \S+: \(master\) removed + Zone has been removed from a master server + + + + 12100 + loading from master file \S+ failed: not at top of zone$ + Origin of zone and owner name of SOA do not match. + + + + 12100 + ^transfer of| + AXFR started$ + Zone transfer. + + + + 12128 + failed to connect: connection refused + Zone transfer failed, unable to connect to master. + + + + 12100 + IPv6 interfaces failed + Could not listen on IPv6 interface. + + + + 12100 + failed; interface ignored + Could not bind to an interface. + + + + 12128 + failed while receiving responses: not authoritative + Master is not authoritative for zone. + + + + 12100 + open: \S+: permission denied$ + Could not open configuration file, permission denied. + + + + 12100 + loading configuration: permission denied + Could not open configuration file, permission denied. + + + + 12100 + IN SOA -E + Domain in SOA -E. + + + + 12128 + failed to connect: host unreachable + Master appears to be down. + + + + 12100 + IN AXFR - + Domain is queried for a zone transferred. + + + + 12100 + IN A + + Domain A record found. + + + + 12100 + client \S+: bad zone transfer request: \S+: non-authoritative zone \(NOTAUTH\) + Bad zone transfer request. + + + + 12100 + refresh: failure trying master + Cannot refresh a domain from the master server. + + + + 12100 + SOA record not at top of zone + Origin of zone and owner name of SOA do not match. + + + + 12100 + command channel listening on + named command channel is listening. + + + + 12100 + automatic empty zone + named has created an automatic empty zone. + + + + 12100 + reloading configuration failed: out of memory + Server does not have enough memory to reload the configuration. + + + + 12100 + zone transfer \S+ denied + zone transfer denied + + + + 12100 + error sending response: host unreachable$ + Cannot send a DNS response. + + + + 12100 + update forwarding \.+ denied$ + Cannot update forwarding domain. + + + + 12100 + : parsing failed$ + Parsing of a configuration file has failed. + + diff --git a/etc/rules/netscreenfw_rules.xml b/etc/rules/netscreenfw_rules.xml index 88749c1..03b2d1f 100755 --- a/etc/rules/netscreenfw_rules.xml +++ b/etc/rules/netscreenfw_rules.xml @@ -1,4 +1,5 @@ - + + + + + + + + + bsd_kernel + Grouping of bsd_kernel alerts + + + + 51500 + ichiic0: abort failed, status 0x40 + A timeout occurred waiting for a transfer. + + + + 51500 + Check Condition (error 0x70) on opcode 0x0 + Check media in optical drive. + + + + 51500 + BBB bulk-in clear stall failed + A disk has timed out. + + + + 51500 + arp info overwritten for + arp info has been overwritten for a host + + + + 51500 + was not properly unmounted + A filesystem was not properly unmounted, likely system crash + + + + 51500 + UKC> quit + UKC was used, possibly modifying a kernel at boot time. + + + + 51500 + Michael MIC failure + Michael MIC failure: Checksum failure in the tkip protocol. + + + + 51500 + soft error (corrected) + A soft error has been corrected on a hard drive, + this is a possible early sign of failure. + + + + 51500 + acpithinkpad\d: + unknown event + Unknown acpithinkpad event + + + + 51500 + Critical temperature, shutting down + System shutdown due to temperature + + + + 51500 + _AL0[0] _PR0 failed + Unknown ACPI event (bug 6299 in OpenBSD bug tracking system). + + + + 51500 + ehci_freex: xfer=0xffff8000003ef800 not busy, 0x4f4e5155 + USB diagnostic message. + + + + 51500 + ichiic0: abort failed, status 0x0 + Possible APM or ACPI event. + + + + 51500 + Filesystem is not clean - run fsck + Unclean filesystem, run fsck. + + + + 51500 + atascsi_passthru_done, timeout + Timeout in atascsi_passthru_done. + + + + 51500 + RTC BIOS diagnostic error 80\pclock_battery\p + Clock battery error 80 + + + + 51500 + i/o error on block + I/O error on a storage device + + + + 51500 + kbc: cmd word write error + kbc error. + + + + 51500 + BBB reset failed, IOERROR + USB reset failed, IOERROR. + + + + groupdel + Grouping for groupdel rules. + groupdel, + + + + 51521 + group deleted + Group deleted. + groupdel, + + + + savecore + no core dump + No core dumps. + + + + reboot + rebooted by + System was rebooted. + + + + ^ftp-proxy + proxy cannot connect to server + ftp-proxy cannot connect to a server. + + + + bsd_kernel + uncorrectable data error reading fsbn + Hard drive is dying. + + + + bsd_kernel + ^carp + state transition + MASTER -> BACKUP + CARP master to backup. + + + + bsd_kernel + duplicate IP6 address + Duplicate IPv6 address. + + + + bsd_kernel + failed loadfirmware of file + Could not load a firmware. + + + + ^hotplugd + Permission denied$ + hotplugd could not open a file. + + + + + + diff --git a/etc/rules/ossec_rules.xml b/etc/rules/ossec_rules.xml index fdff361..2abebdb 100755 --- a/etc/rules/ossec_rules.xml +++ b/etc/rules/ossec_rules.xml @@ -1,4 +1,5 @@ - 500 @@ -137,7 +145,30 @@ cdrom|/media|usb|/mount|floppy|dvd Ignoring external medias. - + + + 530 + ossec: output: 'netstat -tan + + Listened ports status (netstat) changed (new port opened or closed). + + + + 530 + ossec: output: 'w' + + no_log + List of logged in users. It will not be alerted by default. + + + + 530 + ossec: output: 'last -n + + no_log + List of the last logged in users. + + ossec syscheck_integrity_changed @@ -216,4 +247,104 @@ Microsoft Event log cleared. logs_cleared, + + + ossec + 550 + syscheck-registry + syscheck, + Registry Integrity Checksum Changed + + + + ossec + 551 + syscheck-registry + syscheck, + Registry Integrity Checksum Changed Again (2nd time) + + + + ossec + 552 + syscheck-registry + syscheck, + Registry Integrity Checksum Changed Again (3rd time) + + + + ossec + 553 + syscheck-registry + syscheck, + Registry Entry Deleted. Unable to Retrieve Checksum + + + + ossec + 554 + syscheck-registry + syscheck, + Registry Entry Added to the System + + + + + + ar_log + Active Response Messages Grouped + active_response, + + + + 600 + firewall-drop.sh + add + Host Blocked by firewall-drop.sh Active Response + active_response, + + + + 600 + firewall-drop.sh + delete + Host Unblocked by firewall-drop.sh Active Response + active_response, + + + + 600 + host-deny.sh + add + Host Blocked by host-deny.sh Active Response + active_response, + + + + 600 + host-deny.sh + delete + Host Unblocked by host-deny.sh Active Response + active_response, + + + + 600 + route-null.sh + add + Host Blocked by route-null.sh Active Response + active_response, + + + + 600 + route-null.sh + delete + Host Unblocked by route-null.sh Active Response + active_response, + + diff --git a/etc/rules/pam_rules.xml b/etc/rules/pam_rules.xml index f70a813..c6209eb 100755 --- a/etc/rules/pam_rules.xml +++ b/etc/rules/pam_rules.xml @@ -1,4 +1,5 @@ - diff --git a/etc/rules/php_rules.xml b/etc/rules/php_rules.xml index 0505eac..8f995e8 100755 --- a/etc/rules/php_rules.xml +++ b/etc/rules/php_rules.xml @@ -1,4 +1,5 @@ - diff --git a/etc/rules/policy_rules.xml b/etc/rules/policy_rules.xml index 7769466..c89818a 100755 --- a/etc/rules/policy_rules.xml +++ b/etc/rules/policy_rules.xml @@ -1,4 +1,5 @@ - diff --git a/etc/rules/solaris_bsm_rules.xml b/etc/rules/solaris_bsm_rules.xml index 67802d4..2df7842 100755 --- a/etc/rules/solaris_bsm_rules.xml +++ b/etc/rules/solaris_bsm_rules.xml @@ -1,4 +1,5 @@ - diff --git a/etc/rules/symantec-av_rules.xml b/etc/rules/symantec-av_rules.xml index a560ea4..27318e9 100755 --- a/etc/rules/symantec-av_rules.xml +++ b/etc/rules/symantec-av_rules.xml @@ -1,4 +1,5 @@ - @@ -154,6 +161,26 @@ ^Authentication passed Pop3 Authentication passed. + + + openldap + OpenLDAP group. + + + + 2507 + ACCEPT from + OpenLDAP connection open. + + + + 2507 + 2508 + + RESULT tag=97 err=49 + OpenLDAP authentication failed. + + @@ -288,7 +315,7 @@ 5100 - ipw2200: Firmware error detected. + ipw2200: Firmware error detected.| ACPI Error Kernel device error. @@ -403,6 +430,14 @@ alert_by_email First time (su) is executed by user. + + + 5300 + unknown class + OpenBSD uses login classes, and an inappropriate login class was used. + A user has attempted to su to an unknown class. + + diff --git a/etc/rules/telnetd_rules.xml b/etc/rules/telnetd_rules.xml index 17f2088..f35e216 100755 --- a/etc/rules/telnetd_rules.xml +++ b/etc/rules/telnetd_rules.xml @@ -1,4 +1,5 @@ - + + + + + + + + + + 31100 + POST / + /wp-comments-post.php + Googlebot|MSNBot|BingBot + WordPress Comment Spam (coming from a fake search engine UA). + + + + + 31100 + thumb.php|timthumb.php + "GET \S+thumb.php?src=\S+.php + TimThumb vulnerability exploit attempt. + + + + + 31100 + login.php + "POST /\S+.php/login.php?cPath= + osCommerce login.php bypass attempt. + + + + + 31100 + login.php + "GET /\S+/admin/file_manager.php/login.php + osCommerce file manager login.php bypass attempt. + + + + + 31100 + /cache/external + "GET /\S+/cache/external\S+.php + TimThumb backdoor access attempt. + + + + + 31100 + cart.php + "GET /\S+cart.php?\S+templatefile=../ + Cart.php directory transversal attempt. + + + + + 31100 + DECLARE%20@S%20CHAR|%20AS%20CHAR + MSSQL Injection attempt (ur.php, urchin.js). + + + + + 31100 + "ZmEu"| "libwww-perl/ + Blacklisted user agent (known malicious user agent). + + + + + 31108 + wp-login.php + ] "POST \S+wp-login.php + WordPress login attempt. + + + + + 31509 + + WordPress wp-login.php brute force attempt. + + + + + 31100 + " "Wget/ + Blacklisted user agent (wget). + + + + + 31100 + uploadify.php + "GET /\S+/uploadify.php?src=http://\S+.php + TimThumb vulnerability exploit attempt. + + + + + 31100 + delete.php + "GET \S+/delete.php?board_skin_path=http://\S+.php + BBS delete.php exploit attempt. + + + + + 31100 + %00 + "GET /\S+.php?\S+%00 + Anomaly URL query (attempting to pass null termination). + + + + + + + + + + diff --git a/etc/rules/web_rules.xml b/etc/rules/web_rules.xml index 9f0b00e..b35d899 100755 --- a/etc/rules/web_rules.xml +++ b/etc/rules/web_rules.xml @@ -1,4 +1,5 @@ - @@ -85,7 +102,7 @@ Ignored URLs for the web attacks - + 31100 URL too long. Higher than allowed on most browsers. Possible attack. @@ -134,7 +151,7 @@ 31101 - Mutiple web server 400 error codes + Multiple web server 400 error codes from same source ip. web_scan,recon, diff --git a/etc/rules/wordpress_rules.xml b/etc/rules/wordpress_rules.xml index 0561aab..edbb837 100755 --- a/etc/rules/wordpress_rules.xml +++ b/etc/rules/wordpress_rules.xml @@ -1,4 +1,5 @@ -" >> $NEWCONFIG LOG_FILES=`cat ${SYSLOG_TEMPLATE}` for i in ${LOG_FILES}; do - # If log file present, add it + # If log file present, add it ls $i > /dev/null 2>&1 if [ $? = 0 ]; then echo " -- $i" @@ -260,7 +272,8 @@ SetupLogs() echo " $i" >>$NEWCONFIG echo " " >> $NEWCONFIG fi - done + done + # Getting snort files SNORT_FILES=`cat ${SNORT_TEMPLATE}` @@ -269,7 +282,7 @@ SetupLogs() if [ $? = 0 ]; then echo "" >> $NEWCONFIG echo " " >> $NEWCONFIG - + head -n 1 $i|grep "\[**\] "|grep -v "Classification:" > /dev/null if [ $? = 0 ]; then echo " snort-full" >> $NEWCONFIG @@ -279,10 +292,10 @@ SetupLogs() echo " -- $i (snort-fast file)" fi echo " $i" >>$NEWCONFIG - echo " " >> $NEWCONFIG + echo " " >> $NEWCONFIG fi - done - + done + # Getting apache logs APACHE_FILES=`cat ${APACHE_TEMPLATE}` for i in ${APACHE_FILES}; do @@ -293,7 +306,7 @@ SetupLogs() echo " apache" >> $NEWCONFIG echo " $i" >>$NEWCONFIG echo " " >> $NEWCONFIG - + echo " -- $i (apache log)" fi done @@ -308,13 +321,33 @@ SetupLogs() echo " postgresql_log" >> $NEWCONFIG echo " $i" >>$NEWCONFIG echo " " >> $NEWCONFIG - + echo " -- $i (postgresql log)" fi done - - - echo "" + + if [ "X$NUNAME" = "XLinux" ]; then + echo "" >> $NEWCONFIG + echo " " >> $NEWCONFIG + echo " command" >> $NEWCONFIG + echo " df -h" >> $NEWCONFIG + echo " " >> $NEWCONFIG + echo "" >> $NEWCONFIG + echo " " >> $NEWCONFIG + echo " full_command" >> $NEWCONFIG + echo " netstat -tan |grep LISTEN |grep -v 127.0.0.1 | sort" >> $NEWCONFIG + echo " " >> $NEWCONFIG + echo "" >> $NEWCONFIG + echo " " >> $NEWCONFIG + echo " full_command" >> $NEWCONFIG + echo " last -n 5" >> $NEWCONFIG + echo " " >> $NEWCONFIG + fi + + + + + echo "" catMsg "0x106-logs" @@ -325,37 +358,50 @@ SetupLogs() +# install.sh ########## # ConfigureClient() ########## ConfigureClient() { - echo "" - echo "3- ${configuring} $NAME." - echo "" - - if [ "X${USER_AGENT_SERVER_IP}" = "X" ]; then - # Looping and asking for server ip + echo "" + echo "3- ${configuring} $NAME." + echo "" + + if [[ "X${USER_AGENT_SERVER_IP}" = "X" && "X${USER_AGENT_SERVER_NAME}" = "X" ]]; then + # Looping and asking for server ip or hostname while [ 1 ]; do - $ECHO " 3.1- ${serverip}: " - read IPANSWER - echo $IPANSWER | grep -E "^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$" > /dev/null 2>&1 + $ECHO " 3.1- ${serveraddr}: " + read ADDRANSWER + # Is it an IP? + echo $ADDRANSWER | grep -E "^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$" > /dev/null 2>&1 if [ $? = 0 ]; then - echo "" - IP=$IPANSWER - echo " - ${addingip} $IP" + echo "" + IP=$ADDRANSWER + echo " - ${addingip} $IP" + break; + # Must be a name + elif [ $? != 0 ]; then + echo "" + HNAME=$ADDRANSWER + echo " - ${addingname} $HNAME" break; fi done else IP=${USER_AGENT_SERVER_IP} - fi + HNAME=${USER_AGENT_SERVER_NAME} + fi - echo "" > $NEWCONFIG + echo "" > $NEWCONFIG echo " " >> $NEWCONFIG - echo " $IP" >> $NEWCONFIG - echo " " >> $NEWCONFIG + if [ "X${IP}" != "X" ]; then + echo " $IP" >> $NEWCONFIG + elif [ "X${HNAME}" != "X" ]; then + echo " $HNAME" >> $NEWCONFIG + fi + echo " " >> $NEWCONFIG echo "" >> $NEWCONFIG # Syscheck? @@ -371,8 +417,8 @@ ConfigureClient() read ANY else ANY=${USER_ENABLE_ACTIVE_RESPONSE} - fi - + fi + case $ANY in $nomatch) echo "" @@ -405,18 +451,18 @@ ConfigureServer() { echo "" echo "3- ${configuring} $NAME." - - + + # Configuring e-mail notification echo "" $ECHO " 3.1- ${mailnotify} ($yes/$no) [$yes]: " - + if [ "X${USER_ENABLE_EMAIL}" = "X" ]; then read ANSWER else ANSWER=${USER_ENABLE_EMAIL} fi - + case $ANSWER in $nomatch) echo "" @@ -427,7 +473,7 @@ ConfigureServer() EMAILNOTIFY="yes" $ECHO " - ${whatsemail} " if [ "X${USER_EMAIL_ADDRESS}" = "X" ]; then - + read EMAIL echo "${EMAIL}" | grep -E "^[a-zA-Z0-9_.-]{1,36}@[a-zA-Z0-9_.-]{1,54}$" > /dev/null 2>&1 ;RVAL=$?; # Ugly e-mail validation @@ -439,24 +485,25 @@ ConfigureServer() else EMAIL=${USER_EMAIL_ADDRESS} fi - + ls ${HOST_CMD} > /dev/null 2>&1 if [ $? = 0 ]; then - HOSTTMP=`${HOST_CMD} -W 5 -t mx devmail.ossec.net 2>/dev/null` + HOSTTMP=`${HOST_CMD} -W 5 -t mx ossec.net 2>/dev/null` if [ $? = 1 ]; then - # Trying without the -W - HOSTTMP=`${HOST_CMD} -t mx devmail.ossec.net 2>/dev/null` - fi - if [ "X$HOSTTMP" = "X${OSSECMX}" -o "X$HOSTTMP" = "X${OSSECMX2}" -o "X$HOSTTMP" = "X${OSSECMX3}" ];then + # Trying without the -W + HOSTTMP=`${HOST_CMD} -t mx ossec.net 2>/dev/null` + fi + echo "x$HOSTTMP" | grep "ossec.net mail is handled" > /dev/null 2>&1 + if [ $? = 0 ]; then # Breaking down the user e-mail EMAILHOST=`echo ${EMAIL} | cut -d "@" -f 2` if [ "X${EMAILHOST}" = "Xlocalhost" ]; then SMTPHOST="127.0.0.1" - else + else HOSTTMP=`${HOST_CMD} -W 5 -t mx ${EMAILHOST}` SMTPHOST=`echo ${HOSTTMP} | cut -d " " -f 7` - fi - fi + fi + fi fi if [ "X${USER_EMAIL_SMTP}" = "X" ]; then @@ -473,7 +520,7 @@ ConfigureServer() *) SMTP=${SMTPHOST} echo "" - echo " --- ${usingsmtp} ${SMTP}" + echo " --- ${usingsmtp} ${SMTP}" ;; esac fi @@ -481,16 +528,16 @@ ConfigureServer() if [ "X${SMTP}" = "X" ]; then $ECHO " - ${whatsmtp} " read SMTP - fi + fi else SMTP=${USER_EMAIL_SMTP} - fi + fi ;; esac - # Writting global parameters - echo "" > $NEWCONFIG + # Writting global parameters + echo "" > $NEWCONFIG echo " " >> $NEWCONFIG if [ "$EMAILNOTIFY" = "yes" ]; then echo " yes" >> $NEWCONFIG @@ -500,10 +547,10 @@ ConfigureServer() else echo " no" >> $NEWCONFIG fi - - echo " " >> $NEWCONFIG + + echo " " >> $NEWCONFIG echo "" >> $NEWCONFIG - + # Writting rules configuration cat ${RULES_TEMPLATE} >> $NEWCONFIG echo "" >> $NEWCONFIG @@ -511,7 +558,7 @@ ConfigureServer() # Checking if syscheck should run UseSyscheck - + # Checking if rootcheck should run UseRootcheck @@ -519,13 +566,13 @@ ConfigureServer() # Active response catMsg "0x107-ar" $ECHO " - ${enable_ar} ($yes/$no) [$yes]: " - + if [ "X${USER_ENABLE_ACTIVE_RESPONSE}" = "X" ]; then read AR else AR=${USER_ENABLE_ACTIVE_RESPONSE} fi - + case $AR in $nomatch) echo "" @@ -540,16 +587,16 @@ ConfigureServer() ACTIVERESPONSE="yes" echo "" catMsg "0x108-ar-enabled" - + echo "" $ECHO " - ${firewallar} ($yes/$no) [$yes]: " - + if [ "X${USER_ENABLE_FIREWALL_RESPONSE}" = "X" ]; then read HD2 else HD2=${USER_ENABLE_FIREWALL_RESPONSE} fi - + echo "" case $HD2 in $nomatch) @@ -559,7 +606,7 @@ ConfigureServer() echo " - ${yesfirewall}" FIREWALLDROP="yes" ;; - esac + esac echo "" >> $NEWCONFIG echo " " >> $NEWCONFIG echo " 127.0.0.1" >> $NEWCONFIG @@ -585,9 +632,9 @@ ConfigureServer() # if [ "X${USER_ENABLE_PF}" = "X" ]; then # read PFENABLE # else - # PFENABLE=${USER_ENABLE_PF} + # PFENABLE=${USER_ENABLE_PF} # fi - # + # # echo "" # case $PFENABLE in # $nomatch) @@ -597,24 +644,24 @@ ConfigureServer() # AddPFTable # ;; # esac - #fi + #fi echo " " >> $NEWCONFIG ;; - esac - - + esac + + if [ "X$INSTYPE" = "Xserver" ]; then - # Configuring remote syslog + # Configuring remote syslog echo "" $ECHO " 3.5- ${syslog} ($yes/$no) [$yes]: " - + if [ "X${USER_ENABLE_SYSLOG}" = "X" ]; then read ANSWER else ANSWER=${USER_ENABLE_SYSLOG} fi - + echo "" case $ANSWER in $nomatch) @@ -629,9 +676,9 @@ ConfigureServer() # Configuring remote connections SLOG="yes" fi - - - + + + if [ "X$RLOG" = "Xyes" ]; then echo "" >> $NEWCONFIG echo " " >> $NEWCONFIG @@ -673,12 +720,12 @@ ConfigureServer() echo "" >> $NEWCONFIG cat ${ACTIVE_RESPONSE_TEMPLATE} >> $NEWCONFIG echo "" >> $NEWCONFIG - fi + fi fi - + # Setting up the logs SetupLogs "3.6" - echo "" >> $NEWCONFIG + echo "" >> $NEWCONFIG } @@ -702,27 +749,27 @@ setEnv() if [ $? = 0 ]; then INSTALLDIR=$ANSWER; break; - fi + fi else - break; - fi + break; + fi done else INSTALLDIR=${USER_DIR} - fi + fi + - CEXTRA="$CEXTRA -DDEFAULTDIR=\\\"${INSTALLDIR}\\\"" - + echo "" echo " - ${installat} ${INSTALLDIR} ." - + if [ "X$INSTYPE" = "Xagent" ]; then CEXTRA="$CEXTRA -DCLIENT" elif [ "X$INSTYPE" = "Xlocal" ]; then - CEXTRA="$CEXTRA -DLOCAL" - fi + CEXTRA="$CEXTRA -DLOCAL" + fi ls $INSTALLDIR >/dev/null 2>&1 if [ $? = 0 ]; then @@ -733,13 +780,13 @@ setEnv() else ANSWER=${USER_DELETE_DIR} fi - + case $ANSWER in $yesmatch) rm -rf $INSTALLDIR if [ ! $? = 0 ]; then exit 2; - fi + fi ;; esac fi @@ -797,11 +844,11 @@ AddWhite() else ANSWER=$yes fi - + if [ "X${ANSWER}" = "X" ] ; then ANSWER=$no fi - + case $ANSWER in $no) break; @@ -813,7 +860,7 @@ AddWhite() else IPS=${USER_WHITE_LIST} fi - + for ip in ${IPS}; do if [ ! "X${ip}" = "X" ]; then @@ -823,7 +870,7 @@ AddWhite() fi fi done - + break; ;; esac @@ -844,7 +891,7 @@ AddPFTable() echo " - ${pfmessage}:" echo " ${moreinfo}" echo " http://www.ossec.net/en/manual.html#active-response-tools" - + echo "" echo "" echo " table <${TABLE}> persist #$TABLE " @@ -869,57 +916,57 @@ main() if [ ! `isFile ${PREDEF_FILE}` = "${FALSE}" ]; then . ${PREDEF_FILE} fi - + # If user language is not set - + if [ "X${USER_LANGUAGE}" = "X" ]; then - + # Choosing the language. while [ 1 ]; do echo "" - for i in `ls ${TEMPLATE}`; do + for i in `ls ${TEMPLATE}`; do # ignore CVS (should not be there anyways and config) if [ "$i" = "CVS" -o "$i" = "config" ]; then continue; fi cat "${TEMPLATE}/$i/language.txt" if [ ! "$i" = "en" ]; then LG="${LG}/$i" - fi + fi done $ECHO " (${LG}) [en]: " read USER_LG; if [ "X${USER_LG}" = "X" ]; then USER_LG="en" - fi - + fi + ls "${TEMPLATE}/${USER_LG}" > /dev/null 2>&1 if [ $? = 0 ]; then break; fi - done; + done; LANGUAGE=${USER_LG} - + else - + # If provided language is not valid, default to english ls "${TEMPLATE}/${USER_LANGUAGE}" > /dev/null 2>&1 if [ $? = 0 ]; then LANGUAGE=${USER_LANGUAGE} else LANGUAGE="en" - fi + fi fi # for USER_LANGUAGE - - + + . ./src/init/shared.sh . ./src/init/language.sh . ./src/init/functions.sh . ./src/init/init.sh . ${TEMPLATE}/${LANGUAGE}/messages.txt - - + + # Must be executed as ./install.sh if [ `isFile ${VERSION_FILE}` = "${FALSE}" ]; then catError "0x1-location"; @@ -928,17 +975,17 @@ main() # Must be root if [ ! "X$ME" = "Xroot" ]; then catError "0x2-beroot"; - fi + fi # Checking dependencies checkDependencies clear - + # Initial message echo " $NAME $VERSION ${installscript} - http://www.ossec.net" - + catMsg "0x101-initial" echo " - $system: $UNAME" @@ -954,7 +1001,7 @@ main() . ./src/init/update.sh # Is this an update? - if [ "`isUpdate`" = "${TRUE}" ]; then + if [ "`isUpdate`" = "${TRUE}" -a "x${USER_CLEANINSTALL}" = "x" ]; then echo "" ct="1" while [ $ct = "1" ]; do @@ -964,7 +1011,7 @@ main() read ANY else ANY=$yes - fi + fi case $ANY in $yes) @@ -976,10 +1023,10 @@ main() ;; *) ct="1" - ;; + ;; esac done - + # Do some of the update steps. if [ "X${update_only}" = "Xyes" ]; then @@ -996,41 +1043,44 @@ main() USER_INSTALL_TYPE=`getPreinstalled` USER_DIR=`getPreinstalledDir` USER_DELETE_DIR="$nomatch" - fi + fi ct="1" - + # We dont need to update the rules on agent installs if [ "X${USER_INSTALL_TYPE}" = "Xagent" ]; then ct="0" fi - + while [ $ct = "1" ]; do - ct="0" + ct="0" $ECHO " - ${updaterules} ($yes/$no): " if [ "X${USER_UPDATE_RULES}" = "X" ]; then read ANY - else + else ANY=$yes fi - + case $ANY in $yes) update_rules="yes" break; ;; - $no) + $no) break; ;; *) ct="1" ;; - esac + esac done - fi + fi echo "" - fi - + fi + + hybrid="hybrid" + HYBID="" + hybridm=`echo ${hybrid} | cut -b 1` serverm=`echo ${server} | cut -b 1` localm=`echo ${local} | cut -b 1` agentm=`echo ${agent} | cut -b 1` @@ -1047,28 +1097,35 @@ main() read ANSWER case $ANSWER in - + ${helpm}|${help}) catMsg "0x102-installhelp" ;; - + ${server}|${serverm}) echo "" echo " - ${serverchose}." INSTYPE="server" break; ;; - + ${agent}|${agentm}) echo "" echo " - ${clientchose}." INSTYPE="agent" break; ;; - + + ${hybrid}|${hybridm}) + echo "" + echo " - ${localchose} (hybrid)." + INSTYPE="local" + HYBID="go" + break; + ;; ${local}|${localm}) echo "" - echo " - ${localchose}." + echo " - ${localchose}." INSTYPE="local" break; ;; @@ -1083,21 +1140,21 @@ main() # Setting up the environment setEnv - + # Configuring the system (based on the installation type) - if [ "X${update_only}" = "X" ]; then - if [ "X$INSTYPE" = "Xserver" ]; then + if [ "X${update_only}" = "X" ]; then + if [ "X$INSTYPE" = "Xserver" ]; then ConfigureServer elif [ "X$INSTYPE" = "Xagent" ]; then ConfigureClient elif [ "X$INSTYPE" = "Xlocal" ]; then - ConfigureServer + ConfigureServer else catError "0x4-installtype" fi - fi + fi - # Installing (calls the respective script + # Installing (calls the respective script # -- InstallAgent.sh or InstallServer.sh Install @@ -1117,22 +1174,22 @@ main() catMsg "0x103-thanksforusing" - + if [ "X${update_only}" = "Xyes" ]; then # Message for the update if [ "X`sh ./src/init/fw-check.sh`" = "XPF" -a "X${ACTIVERESPONSE}" = "Xyes" ]; then if [ "X$USER_NO_STOP" = "X" ]; then read ANY - fi + fi AddPFTable - fi + fi echo "" echo " - ${updatecompleted}" echo "" exit 0; - fi + fi + - if [ "X$USER_NO_STOP" = "X" ]; then read ANY fi @@ -1141,11 +1198,11 @@ main() # PF firewall message if [ "X`sh ./src/init/fw-check.sh`" = "XPF" -a "X${ACTIVERESPONSE}" = "Xyes" ]; then AddPFTable - fi + fi if [ "X$INSTYPE" = "Xserver" ]; then - echo "" + echo "" echo " - ${addserveragent}" echo " ${runma}:" echo "" @@ -1154,9 +1211,9 @@ main() echo " ${moreinfo}" echo " http://www.ossec.net/en/manual.html#ma" echo "" - + elif [ "X$INSTYPE" = "Xagent" ]; then - catMsg "0x104-client" + catMsg "0x104-client" echo " $INSTALLDIR/bin/manage_agents" echo "" echo " ${moreinfo}" @@ -1171,16 +1228,46 @@ main() fi } +_f_cfg="./install.cfg.sh" - +if [ -f $_f_cfg ]; then + . $_f_cfg +fi ### Calling main function where everything happens main -exit 0 +if [ "x$HYBID" = "xgo" ]; then + echo " --------------------------------------------" + echo " Finishing Hybrid setup (agent configuration)" + echo " --------------------------------------------" + echo 'USER_LANGUAGE="en"' > ./etc/preloaded-vars.conf + echo "" >> ./etc/preloaded-vars.conf + echo 'USER_NO_STOP="y"' >> ./etc/preloaded-vars.conf + echo "" >> ./etc/preloaded-vars.conf + echo 'USER_INSTALL_TYPE="agent"' >> ./etc/preloaded-vars.conf + echo "" >> ./etc/preloaded-vars.conf + echo "USER_DIR=\"$INSTALLDIR/ossec-agent\"" >> ./etc/preloaded-vars.conf + echo "" >> ./etc/preloaded-vars.conf + echo 'USER_ENABLE_ROOTCHECK="n"' >> ./etc/preloaded-vars.conf + echo "" >> ./etc/preloaded-vars.conf + echo 'USER_ENABLE_SYSCHECK="n"' >> ./etc/preloaded-vars.conf + echo "" >> ./etc/preloaded-vars.conf + echo 'USER_ENABLE_ACTIVE_RESPONSE="n"' >> ./etc/preloaded-vars.conf + echo "" >> ./etc/preloaded-vars.conf + echo 'USER_UPDATE="n"' >> ./etc/preloaded-vars.conf + echo "" >> ./etc/preloaded-vars.conf + echo 'USER_UPDATE_RULES="n"' >> ./etc/preloaded-vars.conf + echo "" >> ./etc/preloaded-vars.conf + echo 'USER_CLEANINSTALL="y"' >> ./etc/preloaded-vars.conf + echo "" >> ./etc/preloaded-vars.conf + ./install.sh +fi +exit 0 + -## EOF ## +#### exit ? ### diff --git a/src/Config.Make b/src/Config.Make index a0e4e89..460ce6a 100755 --- a/src/Config.Make +++ b/src/Config.Make @@ -8,7 +8,7 @@ include ${PT}LOCATION include ${PT}Config.OS -CFLAGS = -g -Wall -I${PT} -I${PT}headers ${CPATH} ${CEXTRA} ${DEXTRA} ${EEXTRA} ${FEXTRA} ${GEXTRA} ${HEXTRA} -DARGV0=\"${NAME}\" -DXML_VAR=\"var\" -DOSSECHIDS +CFLAGS = -g -Wall -I${PT} -I${PT}headers ${CPATH} ${CEXTRA} ${DEXTRA} ${EEXTRA} ${FEXTRA} ${GEXTRA} ${HEXTRA} ${CGEOIP} -DARGV0=\"${NAME}\" -DXML_VAR=\"var\" -DOSSECHIDS SOURCES = *.c OBJECTS = *.o diff --git a/src/InstallAgent.sh b/src/InstallAgent.sh index 5747929..4dcd94c 100755 --- a/src/InstallAgent.sh +++ b/src/InstallAgent.sh @@ -190,11 +190,15 @@ chown root:${GROUP} ${DIR}/var/run # Moving the binary files cp -pr ../bin/ossec-agentd ${DIR}/bin/ +cp -pr ../bin/agent-auth ${DIR}/bin/ cp -pr ../bin/ossec-logcollector ${DIR}/bin/ cp -pr ../bin/ossec-syscheckd ${DIR}/bin/ cp -pr ../bin/ossec-execd ${DIR}/bin/ cp -pr ./init/ossec-client.sh ${DIR}/bin/ossec-control cp -pr ../bin/manage_agents ${DIR}/bin/ +cp -pr ../contrib/util.sh ${DIR}/bin/ +chown root:${GROUP} ${DIR}/bin/util.sh +chmod +x ${DIR}/bin/util.sh # Copying active response modules sh ./init/fw-check.sh execute > /dev/null diff --git a/src/InstallServer.sh b/src/InstallServer.sh index c9f15ff..3c9dd49 100755 --- a/src/InstallServer.sh +++ b/src/InstallServer.sh @@ -121,8 +121,10 @@ for i in ${subdirs}; do done # Default for all directories -chmod -R 550 ${DIR} -chown -R root:${GROUP} ${DIR} +chmod 550 ${DIR} +chmod 550 ${DIR}/* +chown root:${GROUP} ${DIR} +chown root:${GROUP} ${DIR}/* # AnalysisD needs to write to alerts: log, mail and cmds chown -R ${USER}:${GROUP} ${DIR}/queue/alerts @@ -135,7 +137,7 @@ chmod -R 770 ${DIR}/queue/ossec # To the ossec fts queue chown -R ${USER}:${GROUP} ${DIR}/queue/fts chmod -R 750 ${DIR}/queue/fts -chmod 740 ${DIR}/queue/fts/* > /dev/null 2>&1 +chmod 750 ${DIR}/queue/fts/* > /dev/null 2>&1 # To the ossec syscheck/rootcheck queue chown -R ${USER}:${GROUP} ${DIR}/queue/syscheck @@ -146,20 +148,21 @@ chown -R ${USER}:${GROUP} ${DIR}/queue/rootcheck chmod -R 750 ${DIR}/queue/rootcheck chmod 740 ${DIR}/queue/rootcheck/* > /dev/null 2>&1 -chown -R ${USER}:${GROUP} ${DIR}/queue/diff -chmod -R 750 ${DIR}/queue/diff +chown ${USER}:${GROUP} ${DIR}/queue/diff +chown ${USER}:${GROUP} ${DIR}/queue/diff/* > /dev/null 2>&1 +chmod 750 ${DIR}/queue/diff chmod 740 ${DIR}/queue/diff/* > /dev/null 2>&1 chown -R ${USER_REM}:${GROUP} ${DIR}/queue/agent-info -chmod -R 755 ${DIR}/queue/agent-info -chmod 744 ${DIR}/queue/agent-info/* > /dev/null 2>&1 +chmod -R 750 ${DIR}/queue/agent-info +chmod 740 ${DIR}/queue/agent-info/* > /dev/null 2>&1 chown -R ${USER_REM}:${GROUP} ${DIR}/queue/rids -chmod -R 755 ${DIR}/queue/rids -chmod 744 ${DIR}/queue/rids/* > /dev/null 2>&1 +chmod -R 750 ${DIR}/queue/rids +chmod 740 ${DIR}/queue/rids/* > /dev/null 2>&1 chown -R ${USER}:${GROUP} ${DIR}/queue/agentless -chmod -R 755 ${DIR}/queue/agentless -chmod 744 ${DIR}/queue/agentless/* > /dev/null 2>&1 +chmod -R 750 ${DIR}/queue/agentless +chmod 740 ${DIR}/queue/agentless/* > /dev/null 2>&1 # For the stats directory @@ -171,7 +174,11 @@ chown -R ${USER}:${GROUP} ${DIR}/logs chmod -R 750 ${DIR}/logs touch ${DIR}/logs/ossec.log chown ${USER}:${GROUP} ${DIR}/logs/ossec.log -chmod 664 ${DIR}/logs/ossec.log +chmod 660 ${DIR}/logs/ossec.log + +touch ${DIR}/logs/active-responses.log +chown ${USER}:${GROUP} ${DIR}/logs/active-responses.log +chmod 660 ${DIR}/logs/active-responses.log # For the rules directory ls ${DIR}/rules/*.xml > /dev/null 2>&1 @@ -189,6 +196,7 @@ if [ $? = 0 ]; then fi cp -pr ../etc/rules/* ${DIR}/rules/ +find ${DIR}/rules/ -type f -exec chmod 440 {} \; # If the local_rules is saved, moved it back ls ${DIR}/rules/saved_local_rules.xml.$$ > /dev/null 2>&1 @@ -206,21 +214,21 @@ chown -R root:${GROUP} ${DIR}/etc ls /etc/localtime > /dev/null 2>&1 if [ $? = 0 ]; then cp -pL /etc/localtime ${DIR}/etc/; - chmod 555 ${DIR}/etc/localtime + chmod 440 ${DIR}/etc/localtime chown root:${GROUP} ${DIR}/etc/localtime fi # Solaris Needs some extra files if [ "$UNAME" = "SunOS" ]; then mkdir -p ${DIR}/usr/share/lib/zoneinfo/ - chmod -R 555 ${DIR}/usr/ + chmod -R 550 ${DIR}/usr/ cp -pr /usr/share/lib/zoneinfo/* ${DIR}/usr/share/lib/zoneinfo/ fi ls /etc/TIMEZONE > /dev/null 2>&1 if [ $? = 0 ]; then cp -p /etc/TIMEZONE ${DIR}/etc/; - chmod 555 ${DIR}/etc/TIMEZONE + chmod 550 ${DIR}/etc/TIMEZONE fi @@ -238,6 +246,9 @@ cp -pr ../bin/list_agents ${DIR}/bin/ cp -pr ../bin/agent_control ${DIR}/bin/ cp -pr ../bin/syscheck_control ${DIR}/bin/ cp -pr ../bin/rootcheck_control ${DIR}/bin/ +cp -pr ../contrib/util.sh ${DIR}/bin/ +chown root:${GROUP} ${DIR}/bin/util.sh +chmod +x ${DIR}/bin/util.sh # Local install chosen if [ "X$LOCAL" = "Xlocal" ]; then @@ -292,7 +303,7 @@ sh ./init/fw-check.sh execute > /dev/null cp -p ../active-response/*.sh ${DIR}/active-response/bin/ cp -p ../active-response/firewalls/*.sh ${DIR}/active-response/bin/ -chmod 755 ${DIR}/active-response/bin/* +chmod 550 ${DIR}/active-response/bin/* chown root:${GROUP} ${DIR}/active-response/bin/* chown root:${GROUP} ${DIR}/bin/* diff --git a/src/Makeall b/src/Makeall index f129cb4..71a11c6 100755 --- a/src/Makeall +++ b/src/Makeall @@ -40,7 +40,7 @@ LIBS="os_xml os_regex os_net os_crypto" # Shares sources SOURCES="shared config" # Binaries -BINARIES="os_maild os_dbd os_csyslogd agentlessd os_execd analysisd logcollector remoted client-agent addagent util rootcheck syscheckd monitord" +BINARIES="os_maild os_dbd os_csyslogd agentlessd os_execd analysisd logcollector remoted client-agent addagent util rootcheck syscheckd monitord os_auth" ROOTCHECKBIN="rootcheck" DIRECTORIES="" # Directories to make @@ -63,14 +63,21 @@ if [ "X${ARGV}" = "Xall" -o "X${ARGV}" = "Xrootcheck" -o "X${ARGV}" = "Xlibs" ]; ls /usr/include/openssl/opensslconf.h > /dev/null 2>&1 if [ $? = 0 ]; then echo "DEXTRA=-DUSE_OPENSSL" >> Config.OS + echo "OPENSSLCMD=-lssl -lcrypto" >> Config.OS fi # Checking for inotify if [ "X$OS" = "XLinux" ]; then - ls /usr/include/sys/inotify.h > /dev/null 2>&1 - if [ $? = 0 ]; then + #ls /usr/include/sys/inotify.h > /dev/null 2>&1 + #if [ $? = 0 ]; then + # echo "EEXTRA=-DUSEINOTIFY" >> Config.OS + #fi + + if [ -e /usr/include/sys/inotify.h ]; then echo "EEXTRA=-DUSEINOTIFY" >> Config.OS - fi + elif [ -e /usr/include/x86_64-linux-gnu/sys/inotify.h ]; then + echo "EEXTRA=-DUSEINOTIFY" >> Config.OS + fi fi diff --git a/src/Makefile b/src/Makefile index 976c594..35be86a 100755 --- a/src/Makefile +++ b/src/Makefile @@ -18,6 +18,7 @@ none: @echo "\"make setdb\" to enable database support." @echo "\"make unsetdb\" to disable database support." @echo "\"make setoneway\" to enable one-way connection to the manager." + @echo "\"make setgeoip\" to enable source IP geolocalization." clean: @/bin/sh ./Makeall clean @@ -54,6 +55,9 @@ unsetclang: setprelude: @echo "CPRELUDE=-DPRELUDE -lprelude `libprelude-config --pthread-cflags` `libprelude-config --libs`" >> ./Config.OS +setgeoip: + @echo "CGEOIP=-DGEOIP -I/usr/local/include -L/usr/local/lib -lGeoIP" >> ./Config.OS + setdb: @cd ./os_dbd; echo "CDB=`./dbmake.sh`" >> ../Config.OS; setmaxagents: diff --git a/src/VERSION b/src/VERSION index 2c3fc41..6354a50 100755 --- a/src/VERSION +++ b/src/VERSION @@ -1 +1 @@ -v2.5.1 +v2.7 diff --git a/src/addagent/b64.c b/src/addagent/b64.c index 00c0d05..45ecb49 100755 --- a/src/addagent/b64.c +++ b/src/addagent/b64.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/addagent/b64.c, 2011/09/08 dcid Exp $ + */ /* * Copyright (C), 2000-2004 by the monit project group. * All Rights Reserved. @@ -12,7 +13,7 @@ * 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 @@ -35,7 +36,7 @@ static unsigned char decode(char c); /** - * Implementation of base64 encoding/decoding. + * Implementation of base64 encoding/decoding. * * @author Jan-Henrik Haukeland, * @@ -67,7 +68,7 @@ char *encode_base64(int size, char *src) { out = (char *)calloc(sizeof(char), size*4/3+4); if(!out) return NULL; - + p = out; for(i = 0; i < size; i+=3) { @@ -113,45 +114,45 @@ char *encode_base64(int size, char *src) { * 'dest'. The dest buffer is NUL terminated. * Return NULL in case of error */ -char *decode_base64(const char *src) +char *decode_base64(const char *src) { - if(src && *src) + if(src && *src) { char *dest; unsigned char *p; int k, l = strlen(src)+1; unsigned char *buf; - + /* The size of the dest will always be less than * the source */ dest = (char *)calloc(sizeof(char), l + 13); if(!dest) return(NULL); - + p = (unsigned char *)dest; - + buf = malloc(l); if(!buf) return(NULL); /* Ignore non base64 chars as per the POSIX standard */ - for(k=0, l=0; src[k]; k++) + for(k=0, l=0; src[k]; k++) { - if(is_base64(src[k])) + if(is_base64(src[k])) { buf[l++]= src[k]; } - } + } - for(k=0; k /** help **/ void helpmsg() @@ -23,7 +24,8 @@ void helpmsg() printf("\t-V Display OSSEC version.\n"); printf("\t-l List available agents.\n"); printf("\t-e Extracts key for an agent (Manager only).\n"); - printf("\t-i Import authentication key (Agent only).\n\n"); + printf("\t-i Import authentication key (Agent only).\n"); + printf("\t-f Bulk generate client keys from file. (Manager only).\n\n"); exit(1); } @@ -70,19 +72,20 @@ int main(int argc, char **argv) int c = 0, cmdlist = 0; char *cmdexport = NULL; char *cmdimport = NULL; - + char *cmdbulk = NULL; + #ifndef WIN32 char *dir = DEFAULTDIR; char *group = GROUPGLOBAL; int gid; #endif - + /* Setting the name */ OS_SetName(ARGV0); - - while((c = getopt(argc, argv, "Vhle:i:")) != -1){ + + while((c = getopt(argc, argv, "Vhle:i:f:")) != -1){ switch(c){ case 'V': print_version(); @@ -109,6 +112,15 @@ int main(int argc, char **argv) ErrorExit("%s: -i needs an argument",ARGV0); cmdimport = optarg; break; + case 'f': + #ifdef CLIENT + ErrorExit("%s: You can't bulk generate keys on an agent.", ARGV0); + #endif + if(!optarg) + ErrorExit("%s: -f needs an argument",ARGV0); + cmdbulk = optarg; + printf("Bulk load file: %s\n", cmdbulk); + break; case 'l': cmdlist = 1; break; @@ -118,30 +130,30 @@ int main(int argc, char **argv) } } - - + + /* Getting currently time */ time1 = time(0); restart_necessary = 0; - - - #ifndef WIN32 + + + #ifndef WIN32 /* Getting the group name */ gid = Privsep_GetGroup(group); if(gid < 0) { ErrorExit(USER_ERROR, ARGV0, "", group); } - - + + /* Setting the group */ if(Privsep_SetGroup(gid) < 0) { ErrorExit(SETGID_ERROR, ARGV0, group); } - - + + /* Chrooting to the default directory */ if(Privsep_Chroot(dir) < 0) { @@ -173,6 +185,11 @@ int main(int argc, char **argv) k_extract(cmdexport); exit(0); } + else if(cmdbulk) + { + k_bulkload(cmdbulk); + exit(0); + } @@ -181,9 +198,17 @@ int main(int argc, char **argv) { int leave_s = 0; print_banner(); - - user_msg = read_from_user(); - + + /* Get ACTION from the environment. If ACTION is specified, + * we must set leave_s = 1 to ensure that the loop will end */ + user_msg = getenv("OSSEC_ACTION"); + if (user_msg == NULL) { + user_msg = read_from_user(); + } + else{ + leave_s = 1; + } + /* All the allowed actions */ switch(user_msg[0]) { @@ -198,11 +223,11 @@ int main(int argc, char **argv) case 'i': case 'I': k_import(NULL); - break; + break; case 'l': case 'L': list_agents(0); - break; + break; case 'r': case 'R': remove_agent(); @@ -212,20 +237,20 @@ int main(int argc, char **argv) leave_s = 1; break; case 'V': - print_version(); + print_version(); break; - default: + default: printf("\n ** Invalid Action ** \n\n"); - break; + break; } if(leave_s) { - break; + break; } - + continue; - + } /* Checking if restart message is necessary */ @@ -238,7 +263,7 @@ int main(int argc, char **argv) printf("\n"); } printf(EXIT); - + return(0); } diff --git a/src/addagent/manage_agents.c b/src/addagent/manage_agents.c index 504ffeb..aa28808 100755 --- a/src/addagent/manage_agents.c +++ b/src/addagent/manage_agents.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/addagent/manage_agents.c, 2012/02/07 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -20,7 +21,7 @@ #include "manage_agents.h" #include "os_crypto/md5/md5_op.h" - +#include /* Global internal variables */ @@ -36,8 +37,8 @@ char *chomp(char *str) /* Removing spaces from the beginning */ while(*str == ' ' || *str == '\t') str++; - - + + /* Removing any trailing new lines or \r */ do { @@ -55,17 +56,17 @@ char *chomp(char *str) } }while(tmp_str != NULL); - + /* Removing spaces at the end of the string */ tmp_str = str; size = strlen(str)-1; - + while((size >= 0) && (tmp_str[size] == ' ' || tmp_str[size] == '\t')) { tmp_str[size] = '\0'; size--; } - + return(str); } @@ -78,10 +79,10 @@ int add_agent() FILE *fp; char str1[STR_SIZE +1]; char str2[STR_SIZE +1]; - + os_md5 md1; os_md5 md2; - + char *user_input; char *_name; char *_id; @@ -104,16 +105,16 @@ int add_agent() /* Allocating for c_ip */ os_calloc(1, sizeof(os_ip), c_ip); - - + + #ifndef WIN32 chmod(AUTH_FILE, 0440); #endif - + /* Setting time 2 */ time2 = time(0); - + /* Source is time1+ time2 +pid + ppid */ #ifndef WIN32 #ifdef __OpenBSD__ @@ -127,7 +128,7 @@ int add_agent() rand1 = random(); - + /* Zeroing strings */ memset(str1,'\0', STR_SIZE +1); memset(str2,'\0', STR_SIZE +1); @@ -135,7 +136,7 @@ int add_agent() printf(ADD_NEW); - + /* Getting the name */ memset(name, '\0', FILE_SIZE +1); @@ -143,7 +144,11 @@ int add_agent() { printf(ADD_NAME); fflush(stdout); - _name = read_from_user(); + /* Read the agent's name from user environment. If it is invalid + * we should force user to provide a name from input device. */ + _name = getenv("OSSEC_AGENT_NAME"); + if (_name == NULL || NameExist(_name) || !OS_IsValidName(_name)) + _name = read_from_user(); if(strcmp(_name, QUIT) == 0) return(0); @@ -168,15 +173,19 @@ int add_agent() { printf(ADD_IP); fflush(stdout); - - _ip = read_from_user(); - + + /* Read IP address from user's environment. If that IP is invalid, + * force user to provide IP from input device */ + _ip = getenv("OSSEC_AGENT_IP"); + if (_ip == NULL || !OS_IsValidIP(_ip, c_ip)) + _ip = read_from_user(); + /* quit */ if(strcmp(_ip, QUIT) == 0) return(0); - + strncpy(ip, _ip, FILE_SIZE -1); - + if(!OS_IsValidIP(ip, c_ip)) { printf(IP_ERROR, ip); @@ -184,12 +193,12 @@ int add_agent() } } while(!_ip); - - + + do { /* Default ID */ - i = 1024; + i = MAX_AGENTS + 768; snprintf(id, 8, "%03d", i); while(!IDExist(id)) { @@ -209,9 +218,20 @@ int add_agent() printf(ADD_ID, id); fflush(stdout); - _id = read_from_user(); - + /* Get Agent id from environment. If 0, use default ID. If null, + * get from user input. If value from environment is invalid, + * we force user to specify an ID from the terminal. Otherwise, + * our program goes to infinite loop. */ + _id = getenv("OSSEC_AGENT_ID"); + if (_id == NULL || IDExist(_id) || !OS_IsValidID(_id)) { + _id = read_from_user(); + } + /* If user specified 0 as Agent ID, he meant use default value. + * NOTE: a bad condistion can cause infinite loop. */ + if (strcmp(_id,"0") == 0) { + strncpy(_id, id, FILE_SIZE -1); + } /* quit */ if(strcmp(_id, QUIT) == 0) @@ -231,8 +251,8 @@ int add_agent() printf(ADD_ERROR_ID, id); } while(IDExist(id) || !OS_IsValidID(id)); - - + + printf(AGENT_INFO, id, name, ip); fflush(stdout); @@ -240,9 +260,15 @@ int add_agent() do { printf(ADD_CONFIRM); - user_input = read_from_user(); - - /* If user accepts to add */ + /* Confirmation by an environment variable. The valid value is y/Y. + * If the user provide anything other string, it is considered as + * n/N; please note that the old code only accepts y/Y/n/N. So if + * the variable OSSEC_ACTION_CONFIRMED is 'foobar', the program will + * go into an infinite loop. */ + user_input = getenv("OSSEC_ACTION_CONFIRMED"); + if (user_input == NULL) user_input = read_from_user(); + + /* If user accepts to add */ if(user_input[0] == 'y' || user_input[0] == 'Y') { time3 = time(0); @@ -256,22 +282,22 @@ int add_agent() #ifndef WIN32 chmod(AUTH_FILE, 0440); #endif - - + + /* Random 1: Time took to write the agent information. * Random 2: Time took to choose the action. * Random 3: All of this + time + pid * Random 4: Md5 all of this + the name, key and ip * Random 5: Final key */ - + snprintf(str1, STR_SIZE, "%d%s%d",time3-time2, name, rand1); snprintf(str2, STR_SIZE, "%d%s%s%d", time2-time1, ip, id, rand2); OS_MD5_Str(str1, md1); OS_MD5_Str(str2, md2); - snprintf(str1, STR_SIZE, "%s%d%d%d",md1,(int)getpid(), (int)random(), + snprintf(str1, STR_SIZE, "%s%d%d%d",md1,(int)getpid(), (int)random(), time3); OS_MD5_Str(str1, md1); @@ -283,7 +309,7 @@ int add_agent() restart_necessary = 1; break; } - else if(user_input[0] == 'n' || user_input[0] == 'N') + else /* if(user_input[0] == 'n' || user_input[0] == 'N') */ { printf(ADD_NOT); break; @@ -301,7 +327,7 @@ int remove_agent() FILE *fp; char *user_input; char u_id[FILE_SIZE +1]; - + u_id[FILE_SIZE] = '\0'; if(!print_agents(0, 0, 0)) @@ -315,7 +341,10 @@ int remove_agent() printf(REMOVE_ID); fflush(stdout); - user_input = read_from_user(); + user_input = getenv("OSSEC_AGENT_ID"); + if (user_input == NULL || !IDExist(user_input)) { + user_input = read_from_user(); + } if(strcmp(user_input, QUIT) == 0) return(0); @@ -327,14 +356,16 @@ int remove_agent() printf(NO_ID, user_input); } } while(!IDExist(user_input)); - + do { printf(REMOVE_CONFIRM); fflush(stdout); - user_input = read_from_user(); - + user_input = getenv("OSSEC_ACTION_CONFIRMED"); + if (user_input == NULL) { + user_input = read_from_user(); + } /* If user confirm */ if(user_input[0] == 'y' || user_input[0] == 'Y') { @@ -344,7 +375,7 @@ int remove_agent() { ErrorExit(MEM_ERROR, ARGV0); } - + fp = fopen(AUTH_FILE, "r+"); if(!fp) { @@ -364,7 +395,7 @@ int remove_agent() /* Remove counter for id */ - delete_agentinfo(full_name); + delete_agentinfo(full_name); OS_RemoveCounter(u_id); free(full_name); full_name = NULL; @@ -374,7 +405,7 @@ int remove_agent() restart_necessary = 1; break; } - else if(user_input[0] == 'n' || user_input[0] == 'N') + else /* if(user_input[0] == 'n' || user_input[0] == 'N') */ { printf(REMOVE_NOT); break; diff --git a/src/addagent/manage_agents.h b/src/addagent/manage_agents.h index e9ba6fc..474c740 100755 --- a/src/addagent/manage_agents.h +++ b/src/addagent/manage_agents.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/addagent/manage_agents.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -29,6 +30,7 @@ int remove_agent(); /* Extract or import a key */ int k_extract(char *cmdextract); int k_import(char *cmdimport); +int k_bulkload(char *cmdbulk); /* Validation functions */ int OS_IsValidName(char *u_name); @@ -36,12 +38,14 @@ int OS_IsValidID(char *id); int IDExist(char *id); int NameExist(char *u_name); char *getFullnameById(char *id); +char *OS_AddNewAgent(char *name, char *ip, char *id, char *key); + /* Print available agents */ int print_agents(int print_status, int active_only, int csv_output); int list_agents(int cmdlist); - + /* clear a line */ char *chomp(char *str); @@ -84,8 +88,8 @@ fpos_t fp_pos; #define ADDED "Added.\n" #define ADD_NOT "Not Adding ..\n" #define PRESS_ENTER "** Press ENTER to return to the main menu.\n" -#define MUST_RESTART "\n** You must restart the server for your changes" \ - " to have effect.\n\n" +#define MUST_RESTART "\n** You must restart OSSEC for your changes" \ + " to take effect.\n\n" /* Add errors */ #define ADD_ERROR_ID "\n** ID '%s' already present. They must be unique.\n\n" @@ -94,7 +98,7 @@ fpos_t fp_pos; #define NO_AGENT "\n** No agent available. You need to add one first.\n" #define NO_ID "\n** Invalid ID '%s' given. ID is not present.\n" #define NO_KEY "\n** Invalid authentication key. Starting over again.\n" -#define INVALID_ID "\n** Invalid ID '%s' given. ID must be numeric (max 5 digits).\n\n" +#define INVALID_ID "\n** Invalid ID '%s' given. ID must be numeric (max 8 digits).\n\n" #define INVALID_NAME "\n** Invalid name '%s' given. Name must contain only alphanumeric characters (min=2, max=32).\n\n" /* Remove agent */ @@ -103,13 +107,13 @@ fpos_t fp_pos; #define REMOVE_DONE "Agent '%s' removed.\n" #define REMOVE_NOT "Not removing ..\n" -/* Import agent */ +/* Import agent */ #define IMPORT_KEY "\n* Provide the Key generated by the server.\n" \ "* The best approach is to cut and paste it.\n" \ "*** OBS: Do not include spaces or new lines.\n\n" \ "Paste it here (or '\\q' to quit): " - -/* extract key */ + +/* extract key */ #define EXTRACT_KEY "Provide the ID of the agent to extract " \ "the key (or '\\q' to quit): " #define EXTRACT_MSG "\nAgent key information for '%s' is: \n%s\n" @@ -125,7 +129,7 @@ fpos_t fp_pos; "\n* %s %s Agent manager. *" \ "\n* The following options are available: *" \ "\n****************************************\n" - + #define BANNER_OPT " (A)dd an agent (A).\n" \ " (E)xtract key for an agent (E).\n" \ " (L)ist already added agents (L).\n" \ @@ -136,5 +140,5 @@ fpos_t fp_pos; #define BANNER_CLIENT " (I)mport key from the server (I).\n" \ " (Q)uit.\n" \ "Choose your action: I or Q: " - + /* EOF */ diff --git a/src/addagent/manage_keys.c b/src/addagent/manage_keys.c index 8f250ff..a46379d 100755 --- a/src/addagent/manage_keys.c +++ b/src/addagent/manage_keys.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/addagent/manage_keys.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,18 +9,38 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ #include "manage_agents.h" - +#include "os_crypto/md5/md5_op.h" +#include /* b64 function prototypes */ char *decode_base64(const char *src); char *encode_base64(int size, char *src); +char *trimwhitespace(char *str) +{ + char *end; + + // Trim leading space + while(isspace(*str)) str++; + + if(*str == 0) // All spaces? + return str; + + // Trim trailing space + end = str + strlen(str) - 1; + while(end > str && isspace(*end)) end--; + + // Write new null terminator + *(end+1) = 0; + + return str; +} /* Import a key */ int k_import(char *cmdimport) @@ -27,11 +48,11 @@ int k_import(char *cmdimport) FILE *fp; char *user_input; char *b64_dec; - + char *name; char *ip; char *tmp_key; - + char line_read[FILE_SIZE +1]; - + /* Parsing user argument. */ if(cmdimport) @@ -42,14 +63,17 @@ int k_import(char *cmdimport) { printf(IMPORT_KEY); - user_input = read_from_user(); + user_input = getenv("OSSEC_AGENT_KEY"); + if (user_input == NULL) { + user_input = read_from_user(); + } } /* quit */ if(strcmp(user_input, QUIT) == 0) return(0); - + b64_dec = decode_base64(user_input); if(b64_dec == NULL) { @@ -59,7 +83,7 @@ int k_import(char *cmdimport) return(0); } - + memset(line_read, '\0', FILE_SIZE +1); strncpy(line_read, b64_dec, FILE_SIZE); @@ -82,16 +106,19 @@ int k_import(char *cmdimport) return(0); } *tmp_key = '\0'; - - printf("\n"); + + printf("\n"); printf(AGENT_INFO, b64_dec, name, ip); - + while(1) { printf(ADD_CONFIRM); fflush(stdout); - user_input = read_from_user(); + user_input = getenv("OSSEC_ACTION_CONFIRMED"); + if (user_input == NULL) { + user_input = read_from_user(); + } if(user_input[0] == 'y' || user_input[0] == 'Y') { @@ -108,14 +135,14 @@ int k_import(char *cmdimport) /* Removing sender counter. */ OS_RemoveCounter("sender"); - + printf(ADDED); printf(PRESS_ENTER); read_from_user(); restart_necessary = 1; return(1); } - else if(user_input[0] == 'n' || user_input[0] == 'N') + else /* if(user_input[0] == 'n' || user_input[0] == 'N') */ { printf("%s", ADD_NOT); return(0); @@ -123,7 +150,7 @@ int k_import(char *cmdimport) } } } - + printf(NO_KEY); printf(PRESS_ENTER); read_from_user(); @@ -179,20 +206,20 @@ int k_extract(char *cmdextract) } while(!IDExist(user_input)); } - + /* Trying to open the auth file */ fp = fopen(AUTH_FILE, "r"); if(!fp) { ErrorExit(FOPEN_ERROR, ARGV0, AUTH_FILE); } - + fsetpos(fp, &fp_pos); memset(n_id, '\0', USER_SIZE +1); strncpy(n_id, user_input, USER_SIZE -1); - - + + if(fgets(line_read, FILE_SIZE, fp) == NULL) { printf(ERROR_KEYS); @@ -201,7 +228,7 @@ int k_extract(char *cmdextract) } chomp(line_read); - + b64_enc = encode_base64(strlen(line_read),line_read); if(b64_enc == NULL) { @@ -223,5 +250,180 @@ int k_extract(char *cmdextract) return(0); } +/* Bulk generate client keys from file */ +int k_bulkload(char *cmdbulk) +{ + int i = 1; + FILE *fp, *infp; + char str1[STR_SIZE +1]; + char str2[STR_SIZE +1]; + + os_md5 md1; + os_md5 md2; + char line[FILE_SIZE+1]; + char name[FILE_SIZE +1]; + char id[FILE_SIZE +1]; + char ip[FILE_SIZE+1]; + os_ip *c_ip; + char delims[] = ","; + char * token = NULL; + + /* Checking if we can open the input file */ + printf("Opening: [%s]\n", cmdbulk); + infp = fopen(cmdbulk,"r"); + if(!infp) + { + perror("Failed."); + ErrorExit(FOPEN_ERROR, ARGV0, cmdbulk); + } + + + /* Checking if we can open the auth_file */ + fp = fopen(AUTH_FILE,"a"); + if(!fp) + { + ErrorExit(FOPEN_ERROR, ARGV0, AUTH_FILE); + } + fclose(fp); + + /* Allocating for c_ip */ + os_calloc(1, sizeof(os_ip), c_ip); + + while(fgets(line, FILE_SIZE - 1, infp) != NULL) + { + if (1 >= strlen(trimwhitespace(line))) + continue; + + memset(ip, '\0', FILE_SIZE +1); + token = strtok(line, delims); + strncpy(ip, trimwhitespace(token),FILE_SIZE -1); + + memset(name, '\0', FILE_SIZE +1); + token = strtok(NULL, delims); + strncpy(name, trimwhitespace(token),FILE_SIZE -1); + + #ifndef WIN32 + chmod(AUTH_FILE, 0440); + #endif + + /* Setting time 2 */ + time2 = time(0); + + + /* Source is time1+ time2 +pid + ppid */ + #ifndef WIN32 + #ifdef __OpenBSD__ + srandomdev(); + #else + srandom(time2 + time1 + getpid() + getppid()); + #endif + #else + srandom(time2 + time1 + getpid()); + #endif + + rand1 = random(); + + + /* Zeroing strings */ + memset(str1,'\0', STR_SIZE +1); + memset(str2,'\0', STR_SIZE +1); + + + /* check the name */ + if(!OS_IsValidName(name)) + { + printf(INVALID_NAME,name); + continue; + } + + /* Search for name -- no duplicates */ + if(NameExist(name)) + { + printf(ADD_ERROR_NAME, name); + continue; + } + + + if(!OS_IsValidIP(ip, c_ip)) + { + printf(IP_ERROR, ip); + continue; + } + + do + { + /* Default ID */ + i = 1024; + snprintf(id, 8, "%03d", i); + while(!IDExist(id)) + { + i--; + snprintf(id, 8, "%03d", i); + + /* No key present, use id 0 */ + if(i <= 0) + { + i = 0; + break; + } + } + snprintf(id, 8, "%03d", i+1); + + if(!OS_IsValidID(id)) + printf(INVALID_ID, id); + + /* Search for ID KEY -- no duplicates */ + if(IDExist(id)) + printf(ADD_ERROR_ID, id); + + } while(IDExist(id) || !OS_IsValidID(id)); + + printf(AGENT_INFO, id, name, ip); + fflush(stdout); + + + time3 = time(0); + rand2 = random(); + + fp = fopen(AUTH_FILE,"a"); + if(!fp) + { + ErrorExit(FOPEN_ERROR, ARGV0, KEYS_FILE); + } + #ifndef WIN32 + chmod(AUTH_FILE, 0440); + #endif + + + /* Random 1: Time took to write the agent information. + * Random 2: Time took to choose the action. + * Random 3: All of this + time + pid + * Random 4: Md5 all of this + the name, key and ip + * Random 5: Final key + */ + + snprintf(str1, STR_SIZE, "%d%s%d",time3-time2, name, rand1); + snprintf(str2, STR_SIZE, "%d%s%s%d", time2-time1, ip, id, rand2); + + OS_MD5_Str(str1, md1); + OS_MD5_Str(str2, md2); + + snprintf(str1, STR_SIZE, "%s%d%d%d",md1,(int)getpid(), (int)random(), + time3); + OS_MD5_Str(str1, md1); + + //fprintf(fp,"%s %s %s %s%s\n",id, name, ip, md1,md2); + fprintf(fp,"%s %s %s %s%s\n",id, name, c_ip->ip, md1,md2); + + fclose(fp); + + printf(AGENT_ADD); + restart_necessary = 1; + }; + + fclose(infp); + return(0); +} + /* EOF */ diff --git a/src/addagent/read_from_user.c b/src/addagent/read_from_user.c index 13ccca5..c46d158 100755 --- a/src/addagent/read_from_user.c +++ b/src/addagent/read_from_user.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/addagent/read_from_user.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -22,7 +23,7 @@ char *read_from_user() { memset(__user_buffer, '\0', USER_SIZE +1); - if((fgets(__user_buffer, USER_SIZE -1, stdin) == NULL) || + if((fgets(__user_buffer, USER_SIZE -1, stdin) == NULL) || (strlen(__user_buffer) >= (USER_SIZE -2))) { printf(INPUT_LARGE); diff --git a/src/addagent/validate.c b/src/addagent/validate.c index 344e4ee..60dec16 100755 --- a/src/addagent/validate.c +++ b/src/addagent/validate.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/addagent/validate.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -12,20 +13,90 @@ #include "manage_agents.h" +#include "os_crypto/md5/md5_op.h" + +char *OS_AddNewAgent(char *name, char *ip, char *id, char *key) +{ + int i = 0; + FILE *fp; + int rand1; + os_md5 md1; + os_md5 md2; + char str1[STR_SIZE +1]; + char str2[STR_SIZE +1]; + char *muname = NULL; + char *finals = NULL; + + char nid[9]; + + + #ifndef WIN32 + #ifdef __OpenBSD__ + srandomdev(); + #else + srandom(time(0) + getpid() + getppid()); + #endif + #else + srandom(time(0) + getpid()); + #endif + + rand1 = random(); + muname = getuname(); + + snprintf(str1, STR_SIZE, "%d%s%d%s",(int)time(0), name, rand1, muname); + snprintf(str2, STR_SIZE, "%s%s%ld", ip, id, (long int)random()); + OS_MD5_Str(str1, md1); + OS_MD5_Str(str2, md2); + + + nid[8] = '\0'; + if(id == NULL) + { + i = 1024; + snprintf(nid, 6, "%d", i); + while(IDExist(nid)) + { + i++; + snprintf(nid, 6, "%d", i); + if(i >= 4000) + { + return(NULL); + } + } + id = nid; + } + + fp = fopen(KEYSFILE_PATH,"a"); + if(!fp) + { + return(NULL); + } + + os_calloc(2048, sizeof(char), finals); + if (ip == NULL){ + snprintf(finals, 2048, "%s %s any %s%s",id, name, md1,md2); + } else { + snprintf(finals, 2048, "%s %s %s %s%s",id, name, ip, md1,md2); + } + fprintf(fp, "%s\n",finals); + + fclose(fp); + return(finals); +} int OS_IsValidID(char *id) { int id_len = 0; int i = 0; - - /* ID must not be null */ + + /* ID must not be null */ if(!id) return(0); id_len = strlen(id); - /* Check ID length, it should contain max. 5 characters */ + /* Check ID length, it should contain max. 8 characters */ if (id_len > 8) return(0); @@ -35,7 +106,7 @@ int OS_IsValidID(char *id) if(!(isdigit((int)id[i]))) return(0); } - + return(1); } @@ -85,7 +156,7 @@ char *getFullnameById(char *id) { continue; } - + ip = strchr(name, ' '); if(ip) { @@ -107,7 +178,7 @@ char *getFullnameById(char *id) snprintf(final_str, FILE_SIZE -1, "%s-%s", name, ip); fclose(fp); - return(final_str); + return(final_str); } } } @@ -124,18 +195,22 @@ int IDExist(char *id) FILE *fp; char line_read[FILE_SIZE +1]; line_read[FILE_SIZE] = '\0'; - - /* ID must not be null */ + + /* ID must not be null */ if(!id) return(0); - fp = fopen(AUTH_FILE, "r"); + if(isChroot()) + fp = fopen(AUTH_FILE, "r"); + else + fp = fopen(KEYSFILE_PATH, "r"); + if(!fp) return(0); - + fseek(fp, 0, SEEK_SET); fgetpos(fp, &fp_pos); - + while(fgets(line_read,FILE_SIZE -1, fp) != NULL) { char *name; @@ -145,7 +220,7 @@ int IDExist(char *id) fgetpos(fp, &fp_pos); continue; } - + name = strchr(line_read, ' '); if(name) { @@ -180,7 +255,7 @@ int OS_IsValidName(char *u_name) /* check if it contains any non-alphanumeric characters */ for(i = 0; i < strlen(u_name); i++) { - if(!isalnum((int)u_name[i]) && (u_name[i] != '-') && + if(!isalnum((int)u_name[i]) && (u_name[i] != '-') && (u_name[i] != '_') && (u_name[i] != '.')) return(0); } @@ -202,7 +277,11 @@ int NameExist(char *u_name) (*u_name == '\n')) return(0); - fp = fopen(AUTH_FILE, "r"); + if(isChroot()) + fp = fopen(AUTH_FILE, "r"); + else + fp = fopen(KEYSFILE_PATH, "r"); + if(!fp) return(0); @@ -228,7 +307,7 @@ int NameExist(char *u_name) { continue; } - + ip = strchr(name, ' '); if(ip) { @@ -261,16 +340,16 @@ int print_agents(int print_status, int active_only, int csv_output) return(0); fseek(fp, 0, SEEK_SET); - + memset(line_read,'\0',FILE_SIZE); - + while(fgets(line_read, FILE_SIZE -1, fp) != NULL) { char *name; if(line_read[0] == '#') continue; - + name = strchr(line_read, ' '); if(name) { @@ -284,7 +363,7 @@ int print_agents(int print_status, int active_only, int csv_output) { continue; } - + ip = strchr(name, ' '); if(ip) { @@ -299,7 +378,7 @@ int print_agents(int print_status, int active_only, int csv_output) printf(PRINT_AVAILABLE); total++; - + if(print_status) { int agt_status = get_agent_status(name, ip); @@ -307,15 +386,15 @@ int print_agents(int print_status, int active_only, int csv_output) { continue; } - + if(csv_output) { - printf("%s,%s,%s,%s,\n", line_read, name, ip, - print_agent_status(agt_status)); + printf("%s,%s,%s,%s,\n", line_read, name, ip, + print_agent_status(agt_status)); } else { - printf(PRINT_AGENT_STATUS, line_read, name, ip, + printf(PRINT_AGENT_STATUS, line_read, name, ip, print_agent_status(agt_status)); } } @@ -324,7 +403,7 @@ int print_agents(int print_status, int active_only, int csv_output) printf(PRINT_AGENT, line_read, name, ip); } } - + } } } @@ -336,7 +415,7 @@ int print_agents(int print_status, int active_only, int csv_output) char *aip = NULL; DIR *dirp; struct dirent *dp; - + if(!csv_output) { printf("\nList of agentless devices:\n"); @@ -379,8 +458,8 @@ int print_agents(int print_status, int active_only, int csv_output) fclose(fp); if(total) return(1); - - return(0); + + return(0); } diff --git a/src/agentlessd/agentlessd.c b/src/agentlessd/agentlessd.c index 2db347f..505d43b 100755 --- a/src/agentlessd/agentlessd.c +++ b/src/agentlessd/agentlessd.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/agentlessd/agentlessd.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -24,7 +25,7 @@ int save_agentless_entry(char *host, char *script, char *agttype) char sys_location[1024 +1]; sys_location[1024] = '\0'; - snprintf(sys_location, 1024, "%s/(%s) %s", + snprintf(sys_location, 1024, "%s/(%s) %s", AGENTLESS_ENTRYDIRPATH, script, host); fp = fopen(sys_location, "w"); @@ -50,7 +51,7 @@ int send_intcheck_msg(char *script, char *host, char *msg) sys_location[1024] = '\0'; snprintf(sys_location, 1024, "(%s) %s->%s", script, host, SYSCHECK); - + if(SendMSG(lessdc.queue, msg, sys_location, SYSCHECK_MQ) < 0) { merror(QUEUE_SEND, ARGV0); @@ -76,7 +77,7 @@ int send_log_msg(char *script, char *host, char *msg) sys_location[1024] = '\0'; snprintf(sys_location, 1024, "(%s) %s->%s", script, host, SYSCHECK); - + if(SendMSG(lessdc.queue, msg, sys_location, LOCALFILE_MQ) < 0) { merror(QUEUE_SEND, ARGV0); @@ -107,7 +108,7 @@ int gen_diff_alert(char *host, char *script, int alert_diff_time) snprintf(buf, 2048, "%s/%s->%s/diff.%d", DIFF_DIR_PATH, host, script, alert_diff_time); - + fp = fopen(buf, "r"); if(!fp) { @@ -132,7 +133,7 @@ int gen_diff_alert(char *host, char *script, int alert_diff_time) else { /* Weird diff with only one large line. */ - buf[256] = '\0'; + buf[256] = '\0'; } } else @@ -145,19 +146,19 @@ int gen_diff_alert(char *host, char *script, int alert_diff_time) /* Getting up to 8 line changes. */ tmp_str = buf; - + while(tmp_str && (*tmp_str != '\0')) { tmp_str = strchr(tmp_str, '\n'); if(!tmp_str) - break; + break; else if(n >= 7) { - *tmp_str = '\0'; + *tmp_str = '\0'; break; } n++; - tmp_str++; + tmp_str++; } @@ -166,10 +167,10 @@ int gen_diff_alert(char *host, char *script, int alert_diff_time) buf, n>=7? "\nMore changes..": ""); - - + + snprintf(buf, 1024, "(%s) %s->agentless", script, host); - + if(SendMSG(lessdc.queue, diff_alert, buf, LOCALFILE_MQ) < 0) { merror(QUEUE_SEND, ARGV0); @@ -202,7 +203,7 @@ int check_diff_file(char *host, char *script) os_md5 md5sum_old; os_md5 md5sum_new; - + old_location[1024] = '\0'; new_location[1024] = '\0'; tmp_location[1024] = '\0'; @@ -228,7 +229,7 @@ int check_diff_file(char *host, char *script) if(OS_MD5_File(new_location, md5sum_new) != 0) { merror("%s: ERROR: Invalid internal state (missing '%s').", - ARGV0, new_location); + ARGV0, new_location); return(0); } @@ -250,15 +251,15 @@ int check_diff_file(char *host, char *script) /* Run diff. */ date_of_change = File_DateofChange(old_location); - snprintf(diff_cmd, 2048, "diff \"%s\" \"%s\" > \"%s/%s->%s/diff.%d\" " + snprintf(diff_cmd, 2048, "diff \"%s\" \"%s\" > \"%s/%s->%s/diff.%d\" " "2>/dev/null", - tmp_location, old_location, + tmp_location, old_location, DIFF_DIR_PATH, host, script, date_of_change); if(system(diff_cmd) != 256) { merror("%s: ERROR: Unable to run diff for %s->%s", ARGV0, host, script); - return(0); + return(0); } @@ -276,7 +277,7 @@ FILE *open_diff_file(char *host, char *script) { FILE *fp = NULL; char sys_location[1024 +1]; - + sys_location[1024] = '\0'; snprintf(sys_location, 1024, "%s/%s->%s/%s", DIFF_DIR_PATH, host, script, DIFF_NEW_FILE); @@ -297,7 +298,7 @@ FILE *open_diff_file(char *host, char *script) } } - snprintf(sys_location, 1024, "%s/%s->%s/%s", DIFF_DIR_PATH, host, + snprintf(sys_location, 1024, "%s/%s->%s/%s", DIFF_DIR_PATH, host, script, DIFF_NEW_FILE); fp = fopen(sys_location, "w"); if(!fp) @@ -321,13 +322,13 @@ int run_periodic_cmd(agentlessd_entries *entry, int test_it) char command[OS_SIZE_1024 +1]; FILE *fp; FILE *fp_store = NULL; - - + + buf[0] = '\0'; command[0] = '\0'; - command[OS_SIZE_1024] = '\0'; - - + command[OS_SIZE_1024] = '\0'; + + while(entry->server[i]) { /* Ignored entry. */ @@ -336,14 +337,14 @@ int run_periodic_cmd(agentlessd_entries *entry, int test_it) i++; continue; } - - - /* We only test for the first server entry. */ + + + /* We only test for the first server entry. */ else if(test_it) { int ret_code = 0; - snprintf(command, OS_SIZE_1024, - "%s/%s test test >/dev/null 2>&1", + snprintf(command, OS_SIZE_1024, + "%s/%s test test >/dev/null 2>&1", AGENTLESSDIRPATH, entry->type); ret_code = system(command); @@ -354,7 +355,7 @@ int run_periodic_cmd(agentlessd_entries *entry, int test_it) { merror("%s: ERROR: Expect command not found (or bad " "arguments) for '%s'.", - ARGV0, entry->type); + ARGV0, entry->type); } merror("%s: ERROR: Test failed for '%s' (%d). Ignoring.", ARGV0, entry->type, ret_code/256); @@ -365,23 +366,23 @@ int run_periodic_cmd(agentlessd_entries *entry, int test_it) verbose("%s: INFO: Test passed for '%s'.", ARGV0, entry->type); return(0); } - + if(entry->server[i][0] == 's') { - snprintf(command, OS_SIZE_1024, "%s/%s \"use_su\" \"%s\" %s 2>&1", - AGENTLESSDIRPATH, entry->type, entry->server[i] +1, + snprintf(command, OS_SIZE_1024, "%s/%s \"use_su\" \"%s\" %s 2>&1", + AGENTLESSDIRPATH, entry->type, entry->server[i] +1, entry->options); } else if(entry->server[i][0] == 'o') { - snprintf(command, OS_SIZE_1024, "%s/%s \"use_sudo\" \"%s\" %s 2>&1", - AGENTLESSDIRPATH, entry->type, entry->server[i] +1, + snprintf(command, OS_SIZE_1024, "%s/%s \"use_sudo\" \"%s\" %s 2>&1", + AGENTLESSDIRPATH, entry->type, entry->server[i] +1, entry->options); } else { - snprintf(command, OS_SIZE_1024, "%s/%s \"%s\" %s 2>&1", - AGENTLESSDIRPATH, entry->type, entry->server[i] +1, + snprintf(command, OS_SIZE_1024, "%s/%s \"%s\" %s 2>&1", + AGENTLESSDIRPATH, entry->type, entry->server[i] +1, entry->options); } @@ -397,23 +398,23 @@ int run_periodic_cmd(agentlessd_entries *entry, int test_it) tmp_str = strchr(buf, '\n'); if(tmp_str) *tmp_str = '\0'; - + if(strncmp(buf, "ERROR: ", 7) == 0) { - merror("%s: ERROR: %s: %s: %s", ARGV0, + merror("%s: ERROR: %s: %s: %s", ARGV0, entry->type, entry->server[i] +1, buf +7); entry->error_flag++; break; } else if(strncmp(buf, "INFO: ", 6) == 0) { - verbose("%s: INFO: %s: %s: %s", ARGV0, + verbose("%s: INFO: %s: %s: %s", ARGV0, entry->type, entry->server[i] +1, buf +6); } else if(strncmp(buf, "FWD: ", 4) == 0) { tmp_str = buf + 5; - send_intcheck_msg(entry->type, entry->server[i]+1, + send_intcheck_msg(entry->type, entry->server[i]+1, tmp_str); } else if(strncmp(buf, "LOG: ", 4) == 0) @@ -425,7 +426,7 @@ int run_periodic_cmd(agentlessd_entries *entry, int test_it) else if((entry->state & LESSD_STATE_DIFF) && (strncmp(buf, "STORE: ", 7) == 0)) { - fp_store = open_diff_file(entry->server[i]+1, + fp_store = open_diff_file(entry->server[i]+1, entry->type); } else if(fp_store) @@ -447,14 +448,14 @@ int run_periodic_cmd(agentlessd_entries *entry, int test_it) } else { - save_agentless_entry(entry->server[i] +1, + save_agentless_entry(entry->server[i] +1, entry->type, "syscheck"); } pclose(fp); } else { - merror("%s: ERROR: popen failed on '%s' for '%s'.", ARGV0, + merror("%s: ERROR: popen failed on '%s' for '%s'.", ARGV0, entry->type, entry->server[i] +1); entry->error_flag++; } @@ -466,7 +467,7 @@ int run_periodic_cmd(agentlessd_entries *entry, int test_it) { fclose(fp_store); } - + return(0); } @@ -475,10 +476,10 @@ int run_periodic_cmd(agentlessd_entries *entry, int test_it) /* Main agentlessd */ void Agentlessd() { - time_t tm; - struct tm *p; + time_t tm; + struct tm *p; - int today = 0; + int today = 0; int thismonth = 0; int thisyear = 0; int test_it = 1; @@ -489,16 +490,16 @@ void Agentlessd() /* Waiting a few seconds to settle */ sleep(2); memset(str, '\0', OS_SIZE_1024 +1); - - + + /* Getting currently time before starting */ tm = time(NULL); p = localtime(&tm); - + today = p->tm_mday; thismonth = p->tm_mon; thisyear = p->tm_year+1900; - + /* Connecting to the message queue * Exit if it fails. @@ -534,7 +535,7 @@ void Agentlessd() if(lessdc.entries[i]->error_flag != 99) { merror("%s: ERROR: Too many failures for '%s'. Ignoring it.", - ARGV0, lessdc.entries[i]->type); + ARGV0, lessdc.entries[i]->type); lessdc.entries[i]->error_flag = 99; } @@ -543,22 +544,22 @@ void Agentlessd() continue; } - + /* Run the check again if the frequency has elapsed. */ if((lessdc.entries[i]->state & LESSD_STATE_PERIODIC) && - ((lessdc.entries[i]->current_state + + ((lessdc.entries[i]->current_state + lessdc.entries[i]->frequency) < tm)) { run_periodic_cmd(lessdc.entries[i], test_it); if(!test_it) lessdc.entries[i]->current_state = tm; } - + i++; sleep(i); } - + /* We only check every minute */ test_it = 0; sleep(60); diff --git a/src/agentlessd/agentlessd.h b/src/agentlessd/agentlessd.h index 7fd6f2e..d96910c 100755 --- a/src/agentlessd/agentlessd.h +++ b/src/agentlessd/agentlessd.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/agentlessd/agentlessd.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. diff --git a/src/agentlessd/main.c b/src/agentlessd/main.c index f970cc5..1d3ce3b 100755 --- a/src/agentlessd/main.c +++ b/src/agentlessd/main.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/agentlessd/main.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -28,7 +29,7 @@ int main(int argc, char **argv) /* Setting the name */ OS_SetName(ARGV0); - + while((c = getopt(argc, argv, "Vdhtfu:g:D:c:")) != -1){ switch(c){ @@ -58,13 +59,14 @@ int main(int argc, char **argv) if(!optarg) ErrorExit("%s: -D needs an argument",ARGV0); dir=optarg; + break; case 'c': if(!optarg) ErrorExit("%s: -c needs an argument",ARGV0); cfg = optarg; break; case 't': - test_config = 1; + test_config = 1; break; default: help(ARGV0); @@ -101,30 +103,30 @@ int main(int argc, char **argv) if(test_config) exit(0); - + /* Going on daemon mode */ - if(!run_foreground) + if(!run_foreground) { nowDaemon(); goDaemonLight(); } chdir(dir); - + /* Exiting if not configured. */ if(!lessdc.entries) { verbose("%s: INFO: Not configured. Exiting.", ARGV0); exit(0); } - - + + /* Privilege separation */ if(Privsep_SetGroup(gid) < 0) ErrorExit(SETGID_ERROR,ARGV0,group); - - /* Changing user */ + + /* Changing user */ if(Privsep_SetUser(uid) < 0) ErrorExit(SETUID_ERROR,ARGV0,user); @@ -136,16 +138,16 @@ int main(int argc, char **argv) /* Signal manipulation */ StartSIG(ARGV0); - + /* Creating PID files */ if(CreatePID(ARGV0, getpid()) < 0) ErrorExit(PID_ERROR,ARGV0); - + /* Start up message */ verbose(STARTUP_MSG, ARGV0, (int)getpid()); - + /* the real daemon now */ Agentlessd(); diff --git a/src/agentlessd/scripts/main.exp b/src/agentlessd/scripts/main.exp index f8ac1f9..8879484 100755 --- a/src/agentlessd/scripts/main.exp +++ b/src/agentlessd/scripts/main.exp @@ -1,6 +1,7 @@ #!/usr/bin/env expect -# @(#) $Id$ +# @(#) $Id: ./src/agentlessd/scripts/main.exp, 2011/09/08 dcid Exp $ + # Agentless monitoring # # Copyright (C) 2009 Trend Micro Inc. diff --git a/src/agentlessd/scripts/register_host.sh b/src/agentlessd/scripts/register_host.sh index edc503d..d7b939e 100755 --- a/src/agentlessd/scripts/register_host.sh +++ b/src/agentlessd/scripts/register_host.sh @@ -1,6 +1,7 @@ #!/bin/sh -# @(#) $Id$ +# @(#) $Id: ./src/agentlessd/scripts/register_host.sh, 2012/07/23 dcid Exp $ + # Agentless monitoring # # Copyright (C) 2009 Trend Micro Inc. @@ -88,6 +89,7 @@ elif [ "x$1" = "xadd" ]; then echo "ERROR: Unable to creating entry (echo failed)." exit 1; fi + chmod 744 $MYPASS echo "*Host $2 added." else diff --git a/src/agentlessd/scripts/ssh.exp b/src/agentlessd/scripts/ssh.exp index 33bca80..1a7463c 100755 --- a/src/agentlessd/scripts/ssh.exp +++ b/src/agentlessd/scripts/ssh.exp @@ -1,6 +1,7 @@ #!/usr/bin/env expect -# @(#) $Id$ +# @(#) $Id: ./src/agentlessd/scripts/ssh.exp, 2011/09/08 dcid Exp $ + # Agentless monitoring # # Copyright (C) 2009 Trend Micro Inc. diff --git a/src/agentlessd/scripts/ssh_asa-fwsmconfig_diff b/src/agentlessd/scripts/ssh_asa-fwsmconfig_diff index a62eead..7e69b63 100755 --- a/src/agentlessd/scripts/ssh_asa-fwsmconfig_diff +++ b/src/agentlessd/scripts/ssh_asa-fwsmconfig_diff @@ -1,6 +1,7 @@ #!/usr/bin/env expect -# @(#) $Id$ +# @(#) $Id: ./src/agentlessd/scripts/ssh_asa-fwsmconfig_diff, 2011/09/08 dcid Exp $ + # Agentless monitoring # # Copyright (C) 2009 Trend Micro Inc. @@ -13,7 +14,8 @@ if {$argc < 1} { - send_user "ERROR: ssh_pixconfig_diff \n"; + send_user "ERROR: ssh_asa-fwsmconfig_diff \n"; + send_user "ERROR: Must be run from /var/ossec\n"; exit 1; } diff --git a/src/agentlessd/scripts/ssh_foundry_diff b/src/agentlessd/scripts/ssh_foundry_diff index 3b845bf..8ca8d36 100755 --- a/src/agentlessd/scripts/ssh_foundry_diff +++ b/src/agentlessd/scripts/ssh_foundry_diff @@ -1,6 +1,7 @@ #!/usr/bin/env expect -# @(#) $Id$ +# @(#) $Id: ./src/agentlessd/scripts/ssh_foundry_diff, 2011/09/08 dcid Exp $ + # Agentless monitoring # # Copyright (C) 2009 Trend Micro Inc. diff --git a/src/agentlessd/scripts/ssh_generic_diff b/src/agentlessd/scripts/ssh_generic_diff index 363d031..7b7006a 100755 --- a/src/agentlessd/scripts/ssh_generic_diff +++ b/src/agentlessd/scripts/ssh_generic_diff @@ -1,6 +1,7 @@ #!/usr/bin/env expect -# @(#) $Id$ +# @(#) $Id: ./src/agentlessd/scripts/ssh_generic_diff, 2011/09/08 dcid Exp $ + # Agentless monitoring # # Copyright (C) 2009 Trend Micro Inc. diff --git a/src/agentlessd/scripts/ssh_integrity_check_bsd b/src/agentlessd/scripts/ssh_integrity_check_bsd index ee273cc..c7d55c6 100755 --- a/src/agentlessd/scripts/ssh_integrity_check_bsd +++ b/src/agentlessd/scripts/ssh_integrity_check_bsd @@ -1,6 +1,7 @@ #!/usr/bin/env expect -# @(#) $Id$ +# @(#) $Id: ./src/agentlessd/scripts/ssh_integrity_check_bsd, 2011/09/08 dcid Exp $ + # Agentless monitoring # # Copyright (C) 2009 Trend Micro Inc. diff --git a/src/agentlessd/scripts/ssh_integrity_check_linux b/src/agentlessd/scripts/ssh_integrity_check_linux index faa0e6d..6d18701 100755 --- a/src/agentlessd/scripts/ssh_integrity_check_linux +++ b/src/agentlessd/scripts/ssh_integrity_check_linux @@ -1,6 +1,7 @@ #!/usr/bin/env expect -# @(#) $Id$ +# @(#) $Id: ./src/agentlessd/scripts/ssh_integrity_check_linux, 2011/09/08 dcid Exp $ + # Agentless monitoring # # Copyright (C) 2009 Trend Micro Inc. diff --git a/src/agentlessd/scripts/ssh_nopass.exp b/src/agentlessd/scripts/ssh_nopass.exp index 03dd300..4cd2e8b 100755 --- a/src/agentlessd/scripts/ssh_nopass.exp +++ b/src/agentlessd/scripts/ssh_nopass.exp @@ -1,6 +1,7 @@ #!/usr/bin/env expect -# @(#) $Id$ +# @(#) $Id: ./src/agentlessd/scripts/ssh_nopass.exp, 2011/09/08 dcid Exp $ + # Agentless monitoring # # Copyright (C) 2009 Trend Micro Inc. diff --git a/src/agentlessd/scripts/ssh_pixconfig_diff b/src/agentlessd/scripts/ssh_pixconfig_diff index 9f130c9..57b8c9e 100755 --- a/src/agentlessd/scripts/ssh_pixconfig_diff +++ b/src/agentlessd/scripts/ssh_pixconfig_diff @@ -1,6 +1,7 @@ #!/usr/bin/env expect -# @(#) $Id$ +# @(#) $Id: ./src/agentlessd/scripts/ssh_pixconfig_diff, 2011/09/08 dcid Exp $ + # Agentless monitoring # # Copyright (C) 2009 Trend Micro Inc. @@ -128,7 +129,7 @@ expect { send_user "ERROR: Unable to connect to remote host: $hostname .\n" exit 1; } - "* password:*" { + "*Password:*" { send "$pass\r" expect { diff --git a/src/agentlessd/scripts/sshlogin.exp b/src/agentlessd/scripts/sshlogin.exp index e9fc839..287fd6b 100755 --- a/src/agentlessd/scripts/sshlogin.exp +++ b/src/agentlessd/scripts/sshlogin.exp @@ -1,6 +1,7 @@ #!/usr/bin/env expect -# @(#) $Id$ +# @(#) $Id: ./src/agentlessd/scripts/sshlogin.exp, 2011/09/08 dcid Exp $ + # Agentless monitoring # # Copyright (C) 2009 Trend Micro Inc. diff --git a/src/agentlessd/scripts/su.exp b/src/agentlessd/scripts/su.exp index 7fb22e2..dbb1cf9 100755 --- a/src/agentlessd/scripts/su.exp +++ b/src/agentlessd/scripts/su.exp @@ -1,6 +1,7 @@ #!/usr/bin/env expect -# @(#) $Id$ +# @(#) $Id: ./src/agentlessd/scripts/su.exp, 2011/09/08 dcid Exp $ + # Agentless monitoring # # Copyright (C) 2009 Trend Micro Inc. diff --git a/src/analysisd/active-response.c b/src/analysisd/active-response.c index 5c3d779..f6f2414 100755 --- a/src/analysisd/active-response.c +++ b/src/analysisd/active-response.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/active-response.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -9,7 +10,7 @@ * Foundation */ - + #include "shared.h" #include "active-response.h" @@ -55,7 +56,7 @@ int AR_ReadConfig(int test_config, char *cfgfile) /* Setting right permission */ - chmod(DEFAULTARPATH, 0444); + chmod(DEFAULTARPATH, 0440); /* Reading configuration */ diff --git a/src/analysisd/active-response.h b/src/analysisd/active-response.h index 64cd2fd..3c3fc11 100755 --- a/src/analysisd/active-response.h +++ b/src/analysisd/active-response.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/active-response.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -9,7 +10,7 @@ * Foundation */ - + #ifndef _AR__H #define _AR__H @@ -28,7 +29,7 @@ void AR_Init(); * to the appropriate lists. */ int AR_ReadConfig(int test_config, char *cfgfile); - + /* Active response commands */ OSList *ar_commands; diff --git a/src/analysisd/alerts/alerts.h b/src/analysisd/alerts/alerts.h index 0b5d473..92d9325 100755 --- a/src/analysisd/alerts/alerts.h +++ b/src/analysisd/alerts/alerts.h @@ -1,11 +1,12 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/alerts/alerts.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * * This program is a free software; you can redistribute it * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software + * License (version 2) as published by the FSF - Free Software * Foundation */ diff --git a/src/analysisd/alerts/exec.c b/src/analysisd/alerts/exec.c index 46bf4ac..073ac58 100755 --- a/src/analysisd/alerts/exec.c +++ b/src/analysisd/alerts/exec.c @@ -1,11 +1,12 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/alerts/exec.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * * This program is a free software; you can redistribute it * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software + * License (version 2) as published by the FSF - Free Software * Foundation */ @@ -25,7 +26,7 @@ #include "eventinfo.h" -/* OS_Exec v0.1 +/* OS_Exec v0.1 */ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) { @@ -37,17 +38,15 @@ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) /* Cleaning the IP */ if(lf->srcip && (ar->ar_cmd->expect & SRCIP)) { - ip = strrchr(lf->srcip, ':'); - if(ip) + if(strncmp(lf->srcip, "::ffff:", 7) == 0) { - ip++; + ip = lf->srcip + 7; } else { ip = lf->srcip; } - /* Checking if IP is to ignored */ if(Config.white_list) { @@ -64,7 +63,7 @@ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) OSMatch **wl; srcip_size = strlen(ip); - + wl = Config.hostname_white_list; while(*wl) { @@ -78,8 +77,8 @@ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) { ip = "-"; } - - + + /* Getting username */ if(lf->dstuser && (ar->ar_cmd->expect & USERNAME)) { @@ -91,17 +90,17 @@ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) } - /* active response on the server. + /* active response on the server. * The response must be here if the ar->location is set to AS * or the ar->location is set to local (REMOTE_AGENT) and the * event location is from here. - */ + */ if((ar->location & AS_ONLY) || ((ar->location & REMOTE_AGENT) && (lf->location[0] != '(')) ) { if(!(Config.ar & LOCAL_AR)) return; - + snprintf(exec_msg, OS_SIZE_1024, "%s %s %s %d.%ld %d %s", ar->name, @@ -117,27 +116,44 @@ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) merror("%s: Error communicating with execd.", ARGV0); } } - - /* Active response to the forwarder */ - else if((Config.ar & REMOTE_AR) && (lf->location[0] == '(')) + + /* Active response to the forwarder */ + else if((Config.ar & REMOTE_AR)) { - int rc; - snprintf(exec_msg, OS_SIZE_1024, - "%s %c%c%c %s %s %s %s %d.%ld %d %s", - lf->location, - (ar->location & ALL_AGENTS)?ALL_AGENTS_C:NONE_C, - (ar->location & REMOTE_AGENT)?REMOTE_AGENT_C:NONE_C, - (ar->location & SPECIFIC_AGENT)?SPECIFIC_AGENT_C:NONE_C, - ar->agent_id != NULL? ar->agent_id: "(null)", - ar->name, - user, - ip, - lf->time, - __crt_ftell, - lf->generated_rule->sigid, - lf->location); - + int rc; + /*If lf->location start with a ( was generated by remote agent and its ID is included in lf->location + if missing then it must of been generated by the local analysisd so prepend a false id tag */ + if(lf->location[0] == '(') { + snprintf(exec_msg, OS_SIZE_1024, + "%s %c%c%c %s %s %s %s %d.%ld %d", + lf->location, + (ar->location & ALL_AGENTS)?ALL_AGENTS_C:NONE_C, + (ar->location & REMOTE_AGENT)?REMOTE_AGENT_C:NONE_C, + (ar->location & SPECIFIC_AGENT)?SPECIFIC_AGENT_C:NONE_C, + ar->agent_id != NULL? ar->agent_id: "(null)", + ar->name, + user, + ip, + lf->time, + __crt_ftell, + lf->generated_rule->sigid); + } else { + snprintf(exec_msg, OS_SIZE_1024, + "(local_source) %s %c%c%c %s %s %s %s %d.%ld %d", + lf->location, + (ar->location & ALL_AGENTS)?ALL_AGENTS_C:NONE_C, + (ar->location & REMOTE_AGENT)?REMOTE_AGENT_C:NONE_C, + (ar->location & SPECIFIC_AGENT)?SPECIFIC_AGENT_C:NONE_C, + ar->agent_id != NULL? ar->agent_id: "(null)", + ar->name, + user, + ip, + lf->time, + __crt_ftell, + lf->generated_rule->sigid); + } + if((rc = OS_SendUnix(*arq, exec_msg, 0)) < 0) { if(rc == OS_SOCKBUSY) @@ -146,12 +162,12 @@ void OS_Exec(int *execq, int *arq, Eventinfo *lf, active_response *ar) } else { - merror("%s: AR socket error (shutdown?).", ARGV0); + merror("%s: AR socket error (shutdown?).", ARGV0); } merror("%s: Error communicating with ar queue (%d).", ARGV0, rc); } } - + return; } diff --git a/src/analysisd/alerts/exec.h b/src/analysisd/alerts/exec.h index 70e45e1..674796d 100755 --- a/src/analysisd/alerts/exec.h +++ b/src/analysisd/alerts/exec.h @@ -1,11 +1,12 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/alerts/exec.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * * This program is a free software; you can redistribute it * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software + * License (version 2) as published by the FSF - Free Software * Foundation */ diff --git a/src/analysisd/alerts/getloglocation.c b/src/analysisd/alerts/getloglocation.c index 0a99251..652696a 100755 --- a/src/analysisd/alerts/getloglocation.c +++ b/src/analysisd/alerts/getloglocation.c @@ -1,11 +1,12 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/alerts/getloglocation.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * * This program is a free software; you can redistribute it * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software + * License (version 2) as published by the FSF - Free Software * Foundation */ @@ -21,32 +22,32 @@ char __elogfile[OS_FLSIZE+1]; char __alogfile[OS_FLSIZE+1]; char __flogfile[OS_FLSIZE+1]; -/* OS_InitLog */ +/* OS_InitLog */ void OS_InitLog() { OS_InitFwLog(); __crt_day = 0; - - /* alerts and events log file */ - memset(__alogfile,'\0',OS_FLSIZE +1); - memset(__elogfile,'\0',OS_FLSIZE +1); - memset(__flogfile,'\0',OS_FLSIZE +1); + + /* alerts and events log file */ + memset(__alogfile,'\0',OS_FLSIZE +1); + memset(__elogfile,'\0',OS_FLSIZE +1); + memset(__flogfile,'\0',OS_FLSIZE +1); _eflog = NULL; _aflog = NULL; _fflog = NULL; - + /* Setting the umask */ umask(0027); } -/* gzips a log file +/* gzips a log file int OS_CompressLog(int yesterday, char *prev_month, int prev_year) - -- moved to monitord. -*/ + -- moved to monitord. +*/ @@ -54,11 +55,11 @@ int OS_CompressLog(int yesterday, char *prev_month, int prev_year) /* OS_GetLogLocation: v0.1, 2005/04/25 */ int OS_GetLogLocation(Eventinfo *lf) { - /* Checking what directories to create + /* Checking what directories to create * Checking if the year directory is there. * If not, create it. Same for the month directory. */ - + /* For the events */ if(_eflog) { @@ -67,7 +68,7 @@ int OS_GetLogLocation(Eventinfo *lf) fclose(_eflog); _eflog = NULL; } - + snprintf(__elogfile,OS_FLSIZE,"%s/%d/", EVENTS, lf->year); if(IsDir(__elogfile) == -1) if(mkdir(__elogfile,0770) == -1) @@ -96,11 +97,11 @@ int OS_GetLogLocation(Eventinfo *lf) _eflog = fopen(__elogfile,"a"); if(!_eflog) ErrorExit("%s: Error opening logfile: '%s'",ARGV0,__elogfile); - + /* Creating a symlink */ unlink(EVENTS_DAILY); link(__elogfile, EVENTS_DAILY); - + /* for the alerts logs */ if(_aflog) @@ -110,7 +111,7 @@ int OS_GetLogLocation(Eventinfo *lf) fclose(_aflog); _aflog = NULL; } - + snprintf(__alogfile,OS_FLSIZE,"%s/%d/", ALERTS, lf->year); if(IsDir(__alogfile) == -1) if(mkdir(__alogfile,0770) == -1) @@ -136,14 +137,14 @@ int OS_GetLogLocation(Eventinfo *lf) lf->day); _aflog = fopen(__alogfile,"a"); - + if(!_aflog) ErrorExit("%s: Error opening logfile: '%s'",ARGV0,__alogfile); - + /* Creating a symlink */ unlink(ALERTS_DAILY); link(__alogfile, ALERTS_DAILY); - + /* For the firewall events */ if(_fflog) @@ -153,7 +154,7 @@ int OS_GetLogLocation(Eventinfo *lf) fclose(_fflog); _fflog = NULL; } - + snprintf(__flogfile,OS_FLSIZE,"%s/%d/", FWLOGS, lf->year); if(IsDir(__flogfile) == -1) if(mkdir(__flogfile,0770) == -1) @@ -187,9 +188,9 @@ int OS_GetLogLocation(Eventinfo *lf) /* Creating a symlink */ unlink(FWLOGS_DAILY); link(__flogfile, FWLOGS_DAILY); - - /* Setting the new day */ + + /* Setting the new day */ __crt_day = lf->day; return(0); diff --git a/src/analysisd/alerts/getloglocation.h b/src/analysisd/alerts/getloglocation.h index 90bef61..13c600e 100755 --- a/src/analysisd/alerts/getloglocation.h +++ b/src/analysisd/alerts/getloglocation.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/alerts/getloglocation.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -30,7 +31,7 @@ void OS_InitFwLog(); * @param lf Event structure * * @retval 0 success - * -1 error + * -1 error */ int OS_GetLogLocation(Eventinfo *lf); diff --git a/src/analysisd/alerts/log.c b/src/analysisd/alerts/log.c index 4095b61..95e1e63 100755 --- a/src/analysisd/alerts/log.c +++ b/src/analysisd/alerts/log.c @@ -1,11 +1,12 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/alerts/log.c, 2012/03/30 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * * This program is a free software; you can redistribute it * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software + * License (version 2) as published by the FSF - Free Software * Foundation */ @@ -18,6 +19,86 @@ #include "eventinfo.h" #include "config.h" +#ifdef GEOIP +/* GeoIP Stuff */ +#include "GeoIP.h" +#include "GeoIPCity.h" + +#define RFC1918_10 (167772160 & 4278190080) /* 10/8 */ +#define RFC1918_172 (2886729728 & 4293918720) /* 172.17/12 */ +#define RFC1918_192 (3232235520 & 4294901760) /* 192.168/16 */ +#define NETMASK_8 4278190080 /* 255.0.0.0 */ +#define NETMASK_12 4293918720 /* 255.240.0.0 */ +#define NETMASK_16 4294901760 /* 255.255.0.0 */ + +static const char * _mk_NA( const char * p ){ + return p ? p : "N/A"; +} + +/* StrIP2Long */ +/* Convert an dot-quad IP address into long format + */ +unsigned long StrIP2Int(char *ip) { + unsigned int c1,c2,c3,c4; + /* IP address is not coming from user input -> We can trust it */ + /* only minimal checking is performed */ + int len = strlen(ip); + if ((len < 7) || (len > 15)) return 0; + + sscanf(ip, "%d.%d.%d.%d", &c1, &c2, &c3, &c4); + return((unsigned long)c4+c3*256+c2*256*256+c1*256*256*256); +} + + +/* GeoIPLookup */ +/* Use the GeoIP API to locate an IP address + */ +char *GeoIPLookup(char *ip) +{ + GeoIP *gi; + GeoIPRecord *gir; + char buffer[OS_SIZE_1024 +1]; + unsigned long longip; + + /* Dumb way to detect an IPv6 address */ + if (strchr(ip, ':')) { + /* Use the IPv6 DB */ + gi = GeoIP_open(Config.geoip_db_path, GEOIP_INDEX_CACHE); + if (gi == NULL) { + merror(INVALID_GEOIP_DB, ARGV0, Config.geoip6_db_path); + return("Unknown"); + } + gir = GeoIP_record_by_name_v6(gi, (const char *)ip); + } + else { + /* Use the IPv4 DB */ + /* If we have a RFC1918 IP, do not perform a DB lookup (performance) */ + longip = StrIP2Int(ip); + if (longip == 0 ) return("Unknown"); + if ((longip & NETMASK_8) == RFC1918_10 || + (longip & NETMASK_12) == RFC1918_172 || + (longip & NETMASK_16) == RFC1918_192) return(""); + + gi = GeoIP_open(Config.geoip_db_path, GEOIP_INDEX_CACHE); + if (gi == NULL) { + merror(INVALID_GEOIP_DB, ARGV0, Config.geoip_db_path); + return("Unknown"); + } + gir = GeoIP_record_by_name(gi, (const char *)ip); + } + if (gir != NULL) { + sprintf(buffer,"%s,%s,%s", + _mk_NA(gir->country_code), + _mk_NA(GeoIP_region_name_by_code(gir->country_code, gir->region)), + _mk_NA(gir->city) + ); + GeoIP_delete(gi); + return(buffer); + } + GeoIP_delete(gi); + return("Unknown"); +} +#endif /* GEOIP */ /* Drop/allow patterns */ OSMatch FWDROPpm; @@ -25,13 +106,22 @@ OSMatch FWALLOWpm; /* OS_Store: v0.2, 2005/02/10 */ -/* Will store the events in a file +/* Will store the events in a file * The string must be null terminated and contain * any necessary new lines, tabs, etc. * */ void OS_Store(Eventinfo *lf) { + if(strcmp(lf->location, "ossec-keepalive") == 0) + { + return; + } + if(strstr(lf->location, "->ossec-keepalive") != NULL) + { + return; + } + fprintf(_eflog, "%d %s %02d %s %s%s%s %s\n", lf->year, @@ -43,7 +133,7 @@ void OS_Store(Eventinfo *lf) lf->location, lf->full_log); - fflush(_eflog); + fflush(_eflog); return; } @@ -51,10 +141,20 @@ void OS_Store(Eventinfo *lf) void OS_LogOutput(Eventinfo *lf) { +#ifdef GEOIP + char geoip_msg_src[OS_SIZE_1024 +1]; + char geoip_msg_dst[OS_SIZE_1024 +1]; + geoip_msg_src[0] = '\0'; + geoip_msg_dst[0] = '\0'; + if (Config.loggeoip) { + if (lf->srcip) { strncpy(geoip_msg_src, GeoIPLookup(lf->srcip), OS_SIZE_1024); } + if (lf->dstip) { strncpy(geoip_msg_dst, GeoIPLookup(lf->dstip), OS_SIZE_1024); } + } +#endif printf( "** Alert %d.%ld:%s - %s\n" - "%d %s %02d %s %s%s%s\nRule: %d (level %d) -> '%s'\n" - "Src IP: %s\nUser: %s\n%.1256s\n", + "%d %s %02d %s %s%s%s\nRule: %d (level %d) -> '%s'" + "%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n%.1256s\n", lf->time, __crt_ftell, lf->generated_rule->alert_opts & DO_MAILALERT?" mail ":"", @@ -69,8 +169,38 @@ void OS_LogOutput(Eventinfo *lf) lf->generated_rule->sigid, lf->generated_rule->level, lf->generated_rule->comment, - lf->srcip == NULL?"(none)":lf->srcip, - lf->dstuser == NULL?"(none)":lf->dstuser, + + lf->srcip == NULL?"":"\nSrc IP: ", + lf->srcip == NULL?"":lf->srcip, + +#ifdef GEOIP + (strlen(geoip_msg_src) == 0)?"":"\nSrc Location: ", + (strlen(geoip_msg_src) == 0)?"":geoip_msg_src, +#else + "", + "", +#endif + + lf->srcport == NULL?"":"\nSrc Port: ", + lf->srcport == NULL?"":lf->srcport, + + lf->dstip == NULL?"":"\nDst IP: ", + lf->dstip == NULL?"":lf->dstip, + +#ifdef GEOIP + (strlen(geoip_msg_dst) == 0)?"":"\nDst Location: ", + (strlen(geoip_msg_dst) == 0)?"":geoip_msg_dst, +#else + "", + "", +#endif + + lf->dstport == NULL?"":"\nDst Port: ", + lf->dstport == NULL?"":lf->dstport, + + lf->dstuser == NULL?"":"\nUser: ", + lf->dstuser == NULL?"":lf->dstuser, + lf->full_log); @@ -98,11 +228,21 @@ void OS_LogOutput(Eventinfo *lf) /* _writefile: v0.2, 2005/02/09 */ void OS_Log(Eventinfo *lf) { +#ifdef GEOIP + char geoip_msg_src[OS_SIZE_1024 +1]; + char geoip_msg_dst[OS_SIZE_1024 +1]; + geoip_msg_src[0] = '\0'; + geoip_msg_dst[0] = '\0'; + if (Config.loggeoip) { + if (lf->srcip) { strncpy(geoip_msg_src, GeoIPLookup(lf->srcip), OS_SIZE_1024 ); } + if (lf->dstip) { strncpy(geoip_msg_dst, GeoIPLookup(lf->dstip), OS_SIZE_1024 ); } + } +#endif /* Writting to the alert log file */ fprintf(_aflog, "** Alert %d.%ld:%s - %s\n" - "%d %s %02d %s %s%s%s\nRule: %d (level %d) -> '%s'\n" - "Src IP: %s\nUser: %s\n%.1256s\n", + "%d %s %02d %s %s%s%s\nRule: %d (level %d) -> '%s'" + "%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n%.1256s\n", lf->time, __crt_ftell, lf->generated_rule->alert_opts & DO_MAILALERT?" mail ":"", @@ -117,8 +257,38 @@ void OS_Log(Eventinfo *lf) lf->generated_rule->sigid, lf->generated_rule->level, lf->generated_rule->comment, - lf->srcip == NULL?"(none)":lf->srcip, - lf->dstuser == NULL?"(none)":lf->dstuser, + + lf->srcip == NULL?"":"\nSrc IP: ", + lf->srcip == NULL?"":lf->srcip, + +#ifdef GEOIP + (strlen(geoip_msg_src) == 0)?"":"\nSrc Location: ", + (strlen(geoip_msg_src) == 0)?"":geoip_msg_src, +#else + "", + "", +#endif + + lf->srcport == NULL?"":"\nSrc Port: ", + lf->srcport == NULL?"":lf->srcport, + + lf->dstip == NULL?"":"\nDst IP: ", + lf->dstip == NULL?"":lf->dstip, + +#ifdef GEOIP + (strlen(geoip_msg_dst) == 0)?"":"\nDst Location: ", + (strlen(geoip_msg_dst) == 0)?"":geoip_msg_dst, +#else + "", + "", +#endif + + lf->dstport == NULL?"":"\nDst Port: ", + lf->dstport == NULL?"":lf->dstport, + + lf->dstuser == NULL?"":"\nUser: ", + lf->dstuser == NULL?"":lf->dstuser, + lf->full_log); @@ -156,7 +326,7 @@ void OS_InitFwLog() ErrorExit(REGEX_COMPILE, ARGV0, FWALLOW, FWALLOWpm.error); } - + } @@ -167,7 +337,8 @@ int FW_Log(Eventinfo *lf) * action, there is no point in going * forward over here */ - if(!lf->action || !lf->srcip) + if(!lf->action || !lf->srcip || !lf->dstip || !lf->srcport || + !lf->dstport || !lf->protocol) { return(0); } @@ -197,7 +368,7 @@ int FW_Log(Eventinfo *lf) os_free(lf->action); os_strdup("CLOSED", lf->action); break; - /* allow, accept, */ + /* allow, accept, */ case 'a': case 'A': /* pass/permitted */ @@ -205,9 +376,9 @@ int FW_Log(Eventinfo *lf) case 'P': /* open */ case 'o': - case 'O': + case 'O': os_free(lf->action); - os_strdup("ALLOW", lf->action); + os_strdup("ALLOW", lf->action); break; default: if(OSMatch_Execute(lf->action,strlen(lf->action),&FWDROPpm)) @@ -225,7 +396,7 @@ int FW_Log(Eventinfo *lf) os_free(lf->action); os_strdup("UNKNOWN", lf->action); } - break; + break; } @@ -245,7 +416,7 @@ int FW_Log(Eventinfo *lf) lf->srcport, lf->dstip, lf->dstport); - + fflush(_fflog); return(1); diff --git a/src/analysisd/alerts/log.h b/src/analysisd/alerts/log.h index b8ea56f..faf9796 100755 --- a/src/analysisd/alerts/log.h +++ b/src/analysisd/alerts/log.h @@ -1,11 +1,12 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/alerts/log.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * * This program is a free software; you can redistribute it * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software + * License (version 2) as published by the FSF - Free Software * Foundation */ diff --git a/src/analysisd/alerts/mail.c b/src/analysisd/alerts/mail.c index 7f22d6e..dc87751 100755 --- a/src/analysisd/alerts/mail.c +++ b/src/analysisd/alerts/mail.c @@ -5,7 +5,7 @@ * * This program is a free software; you can redistribute it * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software + * License (version 2) as published by the FSF - Free Software * Foundation */ diff --git a/src/analysisd/analysisd.c b/src/analysisd/analysisd.c index 8119c22..579f492 100755 --- a/src/analysisd/analysisd.c +++ b/src/analysisd/analysisd.c @@ -1,6 +1,7 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/analysisd.c, 2012/07/26 dcid Exp $ + */ -/* Copyright (C) 2010 Trend Micro Inc. +/* Copyright (C) 2010-2012 Trend Micro Inc. * All rights reserved. * * This program is a free software; you can redistribute it @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -16,7 +17,7 @@ /* Part of the OSSEC * Available at http://www.ossec.net */ - + /* ossec-analysisd. * Responsible for correlation and log decoding. @@ -97,7 +98,7 @@ void DecodeEvent(Eventinfo *lf); int DecodeSyscheck(Eventinfo *lf); int DecodeRootcheck(Eventinfo *lf); int DecodeHostinfo(Eventinfo *lf); - + /* For Decoders */ int ReadDecodeXML(char *file); @@ -125,7 +126,7 @@ int hourly_firewall; /** int main(int argc, char **argv) */ -#ifndef TESTRULE +#ifndef TESTRULE int main(int argc, char **argv) #else int main_analysisd(int argc, char **argv) @@ -179,13 +180,14 @@ int main_analysisd(int argc, char **argv) if(!optarg) ErrorExit("%s: -D needs an argument",ARGV0); dir = optarg; + break; case 'c': if(!optarg) ErrorExit("%s: -c needs an argument",ARGV0); cfg = optarg; break; case 't': - test_config = 1; + test_config = 1; break; default: help(ARGV0); @@ -199,7 +201,7 @@ int main_analysisd(int argc, char **argv) debug1(STARTED_MSG,ARGV0); DEBUG_MSG("%s: DEBUG: Starting on debug mode - %d ", ARGV0, (int)time(0)); - + /*Check if the user/group given are valid */ uid = Privsep_GetUser(user); gid = Privsep_GetGroup(group); @@ -210,7 +212,7 @@ int main_analysisd(int argc, char **argv) /* Found user */ debug1(FOUND_USER, ARGV0); - + /* Initializing Active response */ AR_Init(); if(AR_ReadConfig(test_config, cfg) < 0) @@ -218,8 +220,8 @@ int main_analysisd(int argc, char **argv) ErrorExit(CONFIG_ERROR,ARGV0, cfg); } debug1(ASINIT, ARGV0); - - + + /* Reading configuration file */ if(GlobalConf(cfg) < 0) { @@ -227,19 +229,19 @@ int main_analysisd(int argc, char **argv) } debug1(READ_CONFIG, ARGV0); - + /* Fixing Config.ar */ Config.ar = ar_flag; if(Config.ar == -1) Config.ar = 0; - - + + /* Getting servers hostname */ memset(__shost, '\0', 512); if(gethostname(__shost, 512 -1) != 0) { - strncpy(__shost, OSSEC_SERVER, 512 -1); + strncpy(__shost, OSSEC_SERVER, 512 -1); } else { @@ -250,14 +252,14 @@ int main_analysisd(int argc, char **argv) if(_ltmp) *_ltmp = '\0'; } - + /* going on Daemon mode */ - if(!test_config || !run_foreground) + if(!test_config && !run_foreground) { nowDaemon(); goDaemon(); } - + /* Starting prelude */ #ifdef PRELUDE @@ -285,22 +287,22 @@ int main_analysisd(int argc, char **argv) nowChroot(); - - + + /* - * Anonymous Section: Load rules, decoders, and lists + * Anonymous Section: Load rules, decoders, and lists * * As lists require two pass loading of rules that make use of list lookups - * are created with blank database structs, and need to be filled in after - * completion of all rules and lists. + * are created with blank database structs, and need to be filled in after + * completion of all rules and lists. */ { { /* Initializing the decoders list */ OS_CreateOSDecoderList(); - if(!Config.decoders) + if(!Config.decoders) { /* Legacy loading */ /* Reading decoders */ if(!ReadDecodeXML(XML_DECODER)) @@ -331,9 +333,9 @@ int main_analysisd(int argc, char **argv) verbose("%s: INFO: Reading decoder file %s.", ARGV0, *decodersfiles); if(!ReadDecodeXML(*decodersfiles)) ErrorExit(CONFIG_ERROR, ARGV0, *decodersfiles); - - free(*decodersfiles); - decodersfiles++; + + free(*decodersfiles); + decodersfiles++; } } @@ -342,7 +344,7 @@ int main_analysisd(int argc, char **argv) } { /* Load Lists */ /* Initializing the lists of list struct */ - Lists_OP_CreateLists(); + Lists_OP_CreateLists(); /* Load each list into list struct */ { char **listfiles; @@ -374,24 +376,24 @@ int main_analysisd(int argc, char **argv) verbose("%s: INFO: Reading rules file: '%s'", ARGV0, *rulesfiles); if(Rules_OP_ReadRules(*rulesfiles) < 0) ErrorExit(RULES_ERROR, ARGV0, *rulesfiles); - - free(*rulesfiles); - rulesfiles++; + + free(*rulesfiles); + rulesfiles++; } free(Config.includes); Config.includes = NULL; } - + /* Find all rules with that require list lookups and attache the - * the correct list struct to the rule. This keeps rules from having to + * the correct list struct to the rule. This keeps rules from having to * search thought the list of lists for the correct file during rule evaluation. */ OS_ListLoadRules(); } } - + /* Fixing the levels/accuracy */ { int total_rules; @@ -399,7 +401,7 @@ int main_analysisd(int argc, char **argv) total_rules = _setlevels(tmp_node, 0); if(!test_config) - verbose("%s: INFO: Total rules enabled: '%d'", ARGV0, total_rules); + verbose("%s: INFO: Total rules enabled: '%d'", ARGV0, total_rules); } @@ -415,8 +417,8 @@ int main_analysisd(int argc, char **argv) AddHash_Rule(tmp_node); } - - + + /* Ignored files on syscheck */ { char **files; @@ -425,7 +427,7 @@ int main_analysisd(int argc, char **argv) { if(!test_config) verbose("%s: INFO: Ignoring file: '%s'", ARGV0, *files); - files++; + files++; } } @@ -435,12 +437,12 @@ int main_analysisd(int argc, char **argv) "log_fw", 0, 1); - + /* Success on the configuration test */ if(test_config) exit(0); - + /* Verbose message */ debug1(PRIVSEP_MSG, ARGV0, dir, user); @@ -449,11 +451,11 @@ int main_analysisd(int argc, char **argv) StartSIG(ARGV0); - /* Setting the user */ + /* Setting the user */ if(Privsep_SetUser(uid) < 0) ErrorExit(SETUID_ERROR,ARGV0,user); - - + + /* Creating the PID file */ if(CreatePID(ARGV0, getpid()) < 0) ErrorExit(PID_ERROR,ARGV0); @@ -491,7 +493,7 @@ int main_analysisd(int argc, char **argv) if(Config.hostname_white_list == NULL) { if(Config.ar) - verbose("%s: INFO: No Hostname in the white list for active reponse.", + verbose("%s: INFO: No Hostname in the white list for active reponse.", ARGV0); } else @@ -500,7 +502,7 @@ int main_analysisd(int argc, char **argv) { int wlc = 0; OSMatch **wl; - + wl = Config.hostname_white_list; while(*wl) { @@ -526,13 +528,13 @@ int main_analysisd(int argc, char **argv) /* Going to main loop */ OS_ReadMSG(m_queue); - if (Config.picviz) + if (Config.picviz) { OS_PicvizClose(); } exit(0); - + } @@ -541,7 +543,7 @@ int main_analysisd(int argc, char **argv) * Main function. Receives the messages(events) * and analyze them all. */ -#ifndef TESTRULE +#ifndef TESTRULE void OS_ReadMSG(int m_queue) #else void OS_ReadMSG_analysisd(int m_queue) @@ -552,7 +554,7 @@ void OS_ReadMSG_analysisd(int m_queue) Eventinfo *lf; RuleInfo *stats_rule; - + /* Null to global currently pointers */ currently_rule = NULL; @@ -567,12 +569,12 @@ void OS_ReadMSG_analysisd(int m_queue) /* Initializing Rootcheck */ RootcheckInit(); - - + + /* Initializing host info */ HostinfoInit(); - - + + /* Creating the event list */ OS_CreateEventList(Config.memorysize); @@ -582,7 +584,7 @@ void OS_ReadMSG_analysisd(int m_queue) { ErrorExit(FTS_LIST_ERROR, ARGV0); } - + /* Starting the active response queues */ if(Config.ar) @@ -590,14 +592,14 @@ void OS_ReadMSG_analysisd(int m_queue) /* Waiting the ARQ to settle .. */ sleep(3); - + #ifndef LOCAL if(Config.ar & REMOTE_AR) { if((arq = StartMQ(ARQUEUE, WRITE)) < 0) { merror(ARQ_ERROR, ARGV0); - + /* If LOCAL_AR is set, keep it there */ if(Config.ar & LOCAL_AR) { @@ -614,7 +616,7 @@ void OS_ReadMSG_analysisd(int m_queue) verbose(CONN_TO, ARGV0, ARQUEUE, "active-response"); } } - + #else /* Only for LOCAL_ONLY installs */ if(Config.ar & REMOTE_AR) @@ -630,13 +632,13 @@ void OS_ReadMSG_analysisd(int m_queue) } } #endif - + if(Config.ar & LOCAL_AR) { if((execdq = StartMQ(EXECQUEUE, WRITE)) < 0) { merror(ARQ_ERROR, ARGV0); - + /* If REMOTE_AR is set, keep it there */ if(Config.ar & REMOTE_AR) { @@ -683,8 +685,8 @@ void OS_ReadMSG_analysisd(int m_queue) /* Doing some cleanup */ memset(msg, '\0', OS_MAXSTR +1); - - + + /* Initializing the logs */ { lf = (Eventinfo *)calloc(1,sizeof(Eventinfo)); @@ -701,25 +703,25 @@ void OS_ReadMSG_analysisd(int m_queue) Free_Eventinfo(lf); } - - + + debug1("%s: DEBUG: Startup completed. Waiting for new messages..",ARGV0); - + /* Daemon loop */ while(1) { lf = (Eventinfo *)calloc(1,sizeof(Eventinfo)); - + /* This shouldn't happen .. */ if(lf == NULL) { ErrorExit(MEM_ERROR,ARGV0); } - + DEBUG_MSG("%s: DEBUG: Waiting for msgs - %d ", ARGV0, (int)time(0)); - + /* Receive message from queue */ if((i = OS_RecvUnix(m_queue, OS_MAXSTR, msg))) { @@ -740,12 +742,12 @@ void OS_ReadMSG_analysisd(int m_queue) Free_Eventinfo(lf); continue; } - + /* Message before extracting header */ DEBUG_MSG("%s: DEBUG: Received msg: %s ", ARGV0, msg); - + /* Clean the msg appropriately */ if(OS_CleanMSG(msg, lf) < 0) { @@ -758,7 +760,7 @@ void OS_ReadMSG_analysisd(int m_queue) /* Msg cleaned */ DEBUG_MSG("%s: DEBUG: Msg cleanup: %s ", ARGV0, lf->log); - + /* Currently rule must be null in here */ currently_rule = NULL; @@ -793,8 +795,8 @@ void OS_ReadMSG_analysisd(int m_queue) prev_year = lf->year; } } - - + + /* Incrementing number of events received */ hourly_events++; @@ -805,7 +807,7 @@ void OS_ReadMSG_analysisd(int m_queue) if(msg[0] == SYSCHECK_MQ) { hourly_syscheck++; - + if(!DecodeSyscheck(lf)) { /* We don't process syscheck events further */ @@ -846,7 +848,7 @@ void OS_ReadMSG_analysisd(int m_queue) DecodeEvent(lf); } - + /* Firewall event */ if(lf->decoder_info->type == FIREWALL) @@ -854,7 +856,7 @@ void OS_ReadMSG_analysisd(int m_queue) /* If we could not get any information from * the log, just ignore it */ - hourly_firewall++; + hourly_firewall++; if(Config.logfw) { if(!FW_Log(lf)) @@ -885,10 +887,10 @@ void OS_ReadMSG_analysisd(int m_queue) { void *saved_rule = lf->generated_rule; char *saved_log; - + /* Saving previous log */ saved_log = lf->full_log; - + lf->generated_rule = stats_rule; lf->full_log = __stats_comment; @@ -909,13 +911,13 @@ void OS_ReadMSG_analysisd(int m_queue) /* Checking the rules */ - DEBUG_MSG("%s: DEBUG: Checking the rules - %d ", + DEBUG_MSG("%s: DEBUG: Checking the rules - %d ", ARGV0, lf->decoder_info->type); - + /* Looping all the rules */ rulenode_pt = OS_GetFirstRule(); - if(!rulenode_pt) + if(!rulenode_pt) { ErrorExit("%s: Rules in an inconsistent state. Exiting.", ARGV0); @@ -928,22 +930,22 @@ void OS_ReadMSG_analysisd(int m_queue) { if(!lf->generated_rule) { - goto CLMEM; + goto CLMEM; } - + /* We go ahead in here and process the alert. */ currently_rule = lf->generated_rule; } - + /* The categories must match */ - else if(rulenode_pt->ruleinfo->category != + else if(rulenode_pt->ruleinfo->category != lf->decoder_info->type) { continue; } /* Checking each rule. */ - else if((currently_rule = OS_CheckIfRuleMatch(lf, rulenode_pt)) + else if((currently_rule = OS_CheckIfRuleMatch(lf, rulenode_pt)) == NULL) { continue; @@ -957,7 +959,7 @@ void OS_ReadMSG_analysisd(int m_queue) } - /* Checking ignore time */ + /* Checking ignore time */ if(currently_rule->ignore_time) { if(currently_rule->time_ignored == 0) @@ -968,7 +970,7 @@ void OS_ReadMSG_analysisd(int m_queue) * is less than the time it should be ignored, * leave (do not alert again). */ - else if((lf->time - currently_rule->time_ignored) + else if((lf->time - currently_rule->time_ignored) < currently_rule->ignore_time) { break; @@ -983,7 +985,7 @@ void OS_ReadMSG_analysisd(int m_queue) /* Pointer to the rule that generated it */ lf->generated_rule = currently_rule; - + /* Checking if we should ignore it */ if(currently_rule->ckignore && IGnore(lf)) { @@ -991,8 +993,8 @@ void OS_ReadMSG_analysisd(int m_queue) lf->generated_rule = NULL; break; } - - + + /* Checking if we need to add to ignore list */ if(currently_rule->ignore) { @@ -1025,7 +1027,7 @@ void OS_ReadMSG_analysisd(int m_queue) { OS_PicvizLog(lf); } - + /* Execute an active response */ if(currently_rule->ar) @@ -1040,7 +1042,7 @@ void OS_ReadMSG_analysisd(int m_queue) do_ar = 1; if((*rule_ar)->ar_cmd->expect & USERNAME) { - if(!lf->dstuser || + if(!lf->dstuser || !OS_PRegex(lf->dstuser,"^[a-zA-Z._0-9@?-]*$")) { if(lf->dstuser) @@ -1077,19 +1079,19 @@ void OS_ReadMSG_analysisd(int m_queue) } else { - lf->sid_node_to_delete = + lf->sid_node_to_delete = currently_rule->sid_prev_matched->last_node; } } /* Group list */ else if(currently_rule->group_prev_matched) { - i = 0; - + i = 0; + while(i < currently_rule->group_prev_matched_sz) { if(!OSList_AddData( - currently_rule->group_prev_matched[i], + currently_rule->group_prev_matched[i], lf)) { merror("%s: Unable to add data to grp list.",ARGV0); @@ -1097,7 +1099,7 @@ void OS_ReadMSG_analysisd(int m_queue) i++; } } - + OS_AddEvent(lf); break; @@ -1112,10 +1114,10 @@ void OS_ReadMSG_analysisd(int m_queue) /* Cleaning the memory */ CLMEM: - + /* Only clear the memory if the eventinfo was not - * added to the stateful memory + * added to the stateful memory * -- message is free inside clean event -- */ if(lf->generated_rule == NULL) @@ -1155,39 +1157,39 @@ RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node) * status, */ RuleInfo *currently_rule = curr_node->ruleinfo; - - + + /* Can't be null */ if(!currently_rule) { merror("%s: Inconsistent state. currently rule NULL", ARGV0); return(NULL); } - + #ifdef TESTRULE if(full_output && !alert_only) print_out(" Trying rule: %d - %s", currently_rule->sigid, currently_rule->comment); #endif - - + + /* Checking if any decoder pre-matched here */ - if(currently_rule->decoded_as && + if(currently_rule->decoded_as && currently_rule->decoded_as != lf->decoder_info->id) { return(NULL); } - - + + /* Checking program name */ if(currently_rule->program_name) { if(!lf->program_name) return(NULL); - if(!OSMatch_Execute(lf->program_name, - lf->p_name_size, + if(!OSMatch_Execute(lf->program_name, + lf->p_name_size, currently_rule->program_name)) return(NULL); } @@ -1200,7 +1202,7 @@ RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node) { return(NULL); } - + if(!OSMatch_Execute(lf->id, strlen(lf->id), currently_rule->id)) @@ -1209,25 +1211,25 @@ RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node) #endif } - + /* Checking if any word to match exists */ if(currently_rule->match) { if(!OSMatch_Execute(lf->log, lf->size, currently_rule->match)) return(NULL); - } + } + - /* Checking if exist any regex for this rule */ if(currently_rule->regex) { if(!OSRegex_Execute(lf->log, currently_rule->regex)) return(NULL); } - - + + /* Checking for actions */ if(currently_rule->action) { @@ -1238,7 +1240,7 @@ RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node) return(NULL); } - + /* Checking for the url */ if(currently_rule->url) { @@ -1246,7 +1248,7 @@ RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node) { return(NULL); } - + if(!OSMatch_Execute(lf->url, strlen(lf->url), currently_rule->url)) { return(NULL); @@ -1301,7 +1303,7 @@ RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node) { return(NULL); } - + if(!OSMatch_Execute(lf->srcport, strlen(lf->srcport), currently_rule->srcport)) @@ -1318,7 +1320,7 @@ RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node) { return(NULL); } - + if(!OSMatch_Execute(lf->dstport, strlen(lf->dstport), currently_rule->dstport)) @@ -1330,7 +1332,7 @@ RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node) #endif } } /* END PACKET_INFO */ - + /* Extra information from event */ if(currently_rule->alert_opts & DO_EXTRAINFO) @@ -1563,7 +1565,7 @@ RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node) } } - + /* If it is a context rule, search for it */ if(currently_rule->context == 1) { @@ -1575,19 +1577,19 @@ RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node) if(full_output && !alert_only) print_out(" *Rule %d matched.", currently_rule->sigid); #endif - - + + /* Search for dependent rules */ if(curr_node->child) { RuleNode *child_node = curr_node->child; RuleInfo *child_rule = NULL; - + #ifdef TESTRULE if(full_output && !alert_only) print_out(" *Trying child rules."); #endif - + while(child_node) { child_rule = OS_CheckIfRuleMatch(lf, child_node); @@ -1595,19 +1597,19 @@ RuleInfo *OS_CheckIfRuleMatch(Eventinfo *lf, RuleNode *curr_node) { return(child_rule); } - + child_node = child_node->next; } } - + /* If we are set to no alert, keep going */ if(currently_rule->alert_opts & NO_ALERT) { return(NULL); } - + hourly_alerts++; currently_rule->firedtimes++; @@ -1622,14 +1624,14 @@ void LoopRule(RuleNode *curr_node, FILE *flog) { if(curr_node->ruleinfo->firedtimes) { - fprintf(flog, "%d-%d-%d-%d\n", - thishour, + fprintf(flog, "%d-%d-%d-%d\n", + thishour, curr_node->ruleinfo->sigid, curr_node->ruleinfo->level, curr_node->ruleinfo->firedtimes); curr_node->ruleinfo->firedtimes = 0; } - + if(curr_node->child) { RuleNode *child_node = curr_node->child; @@ -1698,7 +1700,7 @@ void DumpLogstats() /* Looping on all the rules and printing the stats from them */ do { - LoopRule(rulenode_pt, flog); + LoopRule(rulenode_pt, flog); }while((rulenode_pt = rulenode_pt->next) != NULL); @@ -1710,7 +1712,7 @@ void DumpLogstats() hourly_events = 0; hourly_syscheck = 0; hourly_firewall = 0; - + fclose(flog); } diff --git a/src/analysisd/analysisd.h b/src/analysisd/analysisd.h index fe580d4..d79cd4a 100755 --- a/src/analysisd/analysisd.h +++ b/src/analysisd/analysisd.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/analysisd.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. diff --git a/src/analysisd/cleanevent.c b/src/analysisd/cleanevent.c index f830438..938aa0e 100755 --- a/src/analysisd/cleanevent.c +++ b/src/analysisd/cleanevent.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/cleanevent.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -30,9 +31,9 @@ char *(month[])={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug", - + /* OS_CleanMSG v0.3: 2006/03/04 - * Format a received message in the + * Format a received message in the * Eventinfo structure. */ int OS_CleanMSG(char *msg, Eventinfo *lf) @@ -58,23 +59,23 @@ int OS_CleanMSG(char *msg, Eventinfo *lf) merror(FORMAT_ERROR, ARGV0); return(-1); } - + *pieces = '\0'; - pieces++; - - + pieces++; + + os_strdup(msg, lf->location); - - + + /* Getting the log length */ loglen = strlen(pieces) + 1; - - + + /* Assigning the values in the strucuture (lf->full_log) */ os_malloc((2*loglen) +1, lf->full_log); - - - /* Setting the whole message at full_log */ + + + /* Setting the whole message at full_log */ strncpy(lf->full_log, pieces, loglen); @@ -82,22 +83,22 @@ int OS_CleanMSG(char *msg, Eventinfo *lf) lf->log = lf->full_log+loglen; strncpy(lf->log, pieces, loglen); - - - /* Checking for the syslog date format. - * ( ex: Dec 29 10:00:01 + + + /* Checking for the syslog date format. + * ( ex: Dec 29 10:00:01 * or 2007-06-14T15:48:55-04:00 for syslog-ng isodate * or 2009-05-22T09:36:46.214994-07:00 for rsyslog ) */ if( ( - (loglen > 17) && - (pieces[3] == ' ') && - (pieces[6] == ' ') && - (pieces[9] == ':') && - (pieces[12] == ':') && + (loglen > 17) && + (pieces[3] == ' ') && + (pieces[6] == ' ') && + (pieces[9] == ':') && + (pieces[12] == ':') && (pieces[15] == ' ') && (lf->log+=16) - ) + ) || ( (loglen > 33) && @@ -106,7 +107,7 @@ int OS_CleanMSG(char *msg, Eventinfo *lf) (pieces[10] == 'T') && (pieces[13] == ':') && (pieces[16] == ':') && - + ( ((pieces[22] == ':') && (pieces[25] == ' ') && (lf->log+=26)) || @@ -114,9 +115,9 @@ int OS_CleanMSG(char *msg, Eventinfo *lf) ((pieces[19] == '.') && (pieces[29] == ':') && (lf->log+=32)) ) - + ) - ) + ) { /* Checking for an extra space in here */ if(*lf->log == ' ') @@ -125,15 +126,15 @@ int OS_CleanMSG(char *msg, Eventinfo *lf) /* Hostname */ pieces = lf->hostname = lf->log; - - + + /* Checking for a valid hostname */ while(isValidChar(*pieces) == 1) { pieces++; } - - + + /* Checking if it is a syslog without hostname (common on Solaris. */ if(*pieces == ':' && pieces[1] == ' ') { @@ -151,8 +152,8 @@ int OS_CleanMSG(char *msg, Eventinfo *lf) lf->log = pieces; } - - /* Extracting the hostname */ + + /* Extracting the hostname */ else if(*pieces != ' ') { /* Invalid hostname */ @@ -175,13 +176,13 @@ int OS_CleanMSG(char *msg, Eventinfo *lf) /* Extracting program_name */ - /* Valid names: - * p_name: + /* Valid names: + * p_name: * p_name[pid]: * p_name[pid]: [ID xx facility.severity] * auth|security:info p_name: - * - */ + * + */ while(isValidChar(*pieces) == 1) { pieces++; @@ -194,7 +195,7 @@ int OS_CleanMSG(char *msg, Eventinfo *lf) *pieces = '\0'; pieces+=2; } - + /* Checking for the second format: p_name[pid]: */ else if((*pieces == '[') && (isdigit((int)pieces[1]))) { @@ -245,7 +246,7 @@ int OS_CleanMSG(char *msg, Eventinfo *lf) pieces++; while(isalnum((int)*pieces)) pieces++; - + if(*pieces == ' ') { pieces++; @@ -301,15 +302,15 @@ int OS_CleanMSG(char *msg, Eventinfo *lf) lf->program_name = NULL; } } - - + + /* Removing [ID xx facility.severity] */ if(pieces) { /* Setting log after program name */ lf->log = pieces; - if((pieces[0] == '[') && + if((pieces[0] == '[') && (pieces[1] == 'I') && (pieces[2] == 'D') && (pieces[3] == ' ')) @@ -332,8 +333,8 @@ int OS_CleanMSG(char *msg, Eventinfo *lf) lf->p_name_size = strlen(lf->program_name); } } - - /* xferlog date format + + /* xferlog date format * Mon Apr 17 18:27:14 2006 1 64.160.42.130 */ else if((loglen > 28) && @@ -349,17 +350,17 @@ int OS_CleanMSG(char *msg, Eventinfo *lf) /* Moving log to the beginning of the message */ lf->log+=24; } - + /* Checking for snort date format - * ex: 01/28-09:13:16.240702 [**] - */ - else if( (loglen > 24) && - (pieces[2] == '/') && + * ex: 01/28-09:13:16.240702 [**] + */ + else if( (loglen > 24) && + (pieces[2] == '/') && (pieces[5] == '-') && - (pieces[8] == ':') && + (pieces[8] == ':') && (pieces[11]== ':') && - (pieces[14]== '.') && + (pieces[14]== '.') && (pieces[21] == ' ') ) { lf->log+=23; @@ -367,19 +368,19 @@ int OS_CleanMSG(char *msg, Eventinfo *lf) /* Checking for apache log format */ /* [Fri Feb 11 18:06:35 2004] [warn] */ - else if( (loglen > 27) && - (pieces[0] == '[') && + else if( (loglen > 27) && + (pieces[0] == '[') && (pieces[4] == ' ') && - (pieces[8] == ' ') && + (pieces[8] == ' ') && (pieces[11]== ' ') && - (pieces[14]== ':') && + (pieces[14]== ':') && (pieces[17]== ':') && - (pieces[20]== ' ') && + (pieces[20]== ' ') && (pieces[25]== ']') ) { lf->log+=27; } - + /* Checking for the osx asl log format. * Examples: * [Time 2006.12.28 15:53:55 UTC] [Facility auth] [Sender sshd] [PID 483] [Message error: PAM: Authentication failure for username from 192.168.0.2] [Level 3] [UID -2] [GID -2] [Host Hostname] @@ -398,8 +399,8 @@ int OS_CleanMSG(char *msg, Eventinfo *lf) { /* Do not read more than 1 message entry -> log tampering */ short unsigned int done_message = 0; - - + + /* Removing the date */ lf->log+=25; @@ -421,10 +422,10 @@ int OS_CleanMSG(char *msg, Eventinfo *lf) if(pieces) { *pieces = '\0'; - + /* Setting program_name size */ lf->p_name_size = strlen(lf->program_name); - + pieces++; } /* Invalid program name */ @@ -434,14 +435,14 @@ int OS_CleanMSG(char *msg, Eventinfo *lf) break; } } - + /* Getting message */ else if((strncmp(pieces, "Message ", 8) == 0) && (done_message == 0)) { pieces+=8; done_message = 1; - + lf->log = pieces; /* Getting the closing brackets */ @@ -471,7 +472,7 @@ int OS_CleanMSG(char *msg, Eventinfo *lf) *pieces = '\0'; pieces++; } - + /* Invalid hostname */ else { @@ -484,12 +485,12 @@ int OS_CleanMSG(char *msg, Eventinfo *lf) pieces = strchr(pieces, '['); } } - + /* Checking for squid date format * 1140804070.368 11623 * seconds from 00:00:00 1970-01-01 UTC */ - else if((loglen > 32) && + else if((loglen > 32) && (pieces[0] == '1') && (pieces[10] == '.') && (pieces[14] == ' ') && @@ -507,7 +508,7 @@ int OS_CleanMSG(char *msg, Eventinfo *lf) } - /* Every message must be in the format + /* Every message must be in the format * hostname->location or * (agent) ip->location. */ @@ -524,13 +525,13 @@ int OS_CleanMSG(char *msg, Eventinfo *lf) lf->hostname = __shost; } - + /* Setting up the event data */ lf->time = c_time; p = localtime(&c_time); - + /* Assign hour, day, year and month values */ lf->day = p->tm_mday; lf->year = p->tm_year+1900; @@ -539,14 +540,14 @@ int OS_CleanMSG(char *msg, Eventinfo *lf) p->tm_hour, p->tm_min, p->tm_sec); - + /* Setting the global hour/weekday */ __crt_hour = p->tm_hour; - __crt_wday = p->tm_wday; - - + __crt_wday = p->tm_wday; + + #ifdef TESTRULE if(!alert_only) diff --git a/src/analysisd/compiled_rules/generic_samples.c b/src/analysisd/compiled_rules/generic_samples.c index 9aae6be..57da7b0 100644 --- a/src/analysisd/compiled_rules/generic_samples.c +++ b/src/analysisd/compiled_rules/generic_samples.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/compiled_rules/generic_samples.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -19,10 +20,10 @@ -/** Note: If the rule fails to match it should return NULL. +/** Note: If the rule fails to match it should return NULL. * If you want processing to continue, return lf (the eventinfo structure). */ - + /* Example 1: @@ -114,17 +115,17 @@ void *comp_mswin_targetuser_calleruser_diff(Eventinfo *lf) if(*target_user != *caller_user) return(lf); - if(*target_user == '\t' || + if(*target_user == '\t' || (*target_user == ' ' && target_user[1] == ' ')) - break; + break; - target_user++;caller_user++; + target_user++;caller_user++; } /* If we got in here, the accounts are the same. * So, we return NULL since we only want to alert if they are different. - */ + */ return(NULL); } @@ -142,7 +143,7 @@ void *is_simple_http_request(Eventinfo *lf) return(lf); } - + /* Simple request, no query. */ if(!strchr(lf->url,'?')) { diff --git a/src/analysisd/config.c b/src/analysisd/config.c index 132dce7..f6bc2de 100755 --- a/src/analysisd/config.c +++ b/src/analysisd/config.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/config.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -52,7 +53,7 @@ int GlobalConf(char * cfgfile) Config.syscheck_ignore = NULL; Config.white_list = NULL; Config.hostname_white_list = NULL; - + /* Default actions -- only log above level 1 */ Config.mailbylevel = 7; Config.logbylevel = 1; @@ -75,7 +76,7 @@ int GlobalConf(char * cfgfile) /* Minimum memory size */ if(Config.memorysize < 64) Config.memorysize = 64; - + return(0); } diff --git a/src/analysisd/config.h b/src/analysisd/config.h index d3bb44a..f335d12 100755 --- a/src/analysisd/config.h +++ b/src/analysisd/config.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/config.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -9,7 +10,7 @@ * Foundation */ - + #ifndef _CONFIG__H diff --git a/src/analysisd/decoders/decode-xml.c b/src/analysisd/decoders/decode-xml.c index 6840ec8..f3c182d 100755 --- a/src/analysisd/decoders/decode-xml.c +++ b/src/analysisd/decoders/decode-xml.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/decoders/decode-xml.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -42,7 +43,7 @@ int getDecoderfromlist(char *name) { return(OSStore_GetPosition(os_decoder_store, name)); } - + return(0); } @@ -92,10 +93,10 @@ int os_setdecoderids(char *p_name) { int p_id = 0; char *p_name; - + nnode = node->osdecoder; - nnode->id = getDecoderfromlist(nnode->name); - + nnode->id = getDecoderfromlist(nnode->name); + /* Id can noit be 0 */ if(nnode->id == 0) { @@ -131,8 +132,8 @@ int os_setdecoderids(char *p_name) /* Setting parent name */ nnode->name = p_name; } - - + + /* Id can noit be 0 */ if(nnode->id == 0) { @@ -156,11 +157,11 @@ int ReadDecodeAttrs(char **names, char **values) { return(0); } - + if(strcmp(names[0], "offset") == 0) { int offset = 0; - + /* Offsets can be: after_parent, after_prematch * or after_regex. */ @@ -181,7 +182,7 @@ int ReadDecodeAttrs(char **names, char **values) merror(INV_OFFSET, ARGV0, values[0]); offset |= AFTER_ERROR; } - + return(offset); } @@ -194,14 +195,12 @@ int ReadDecodeAttrs(char **names, char **values) /* ReaddecodeXML */ int ReadDecodeXML(char *file) { - - debug1("ReadDecoderXML File = %s", file); OS_XML xml; XML_NODE node = NULL; - /* XML variables */ + /* XML variables */ /* These are the available options for the rule configuration */ - + char *xml_plugindecoder = "plugin_decoder"; char *xml_decoder = "decoder"; char *xml_decoder_name = "name"; @@ -218,21 +217,21 @@ int ReadDecodeXML(char *file) int i = 0; OSDecoderInfo *NULL_Decoder_tmp = NULL; - - - /* Reading the XML */ + + + /* Reading the XML */ if((i = OS_ReadXML(file,&xml)) < 0) { if((i == -2) && (strcmp(file, XML_LDECODER) == 0)) { return(-2); } - + merror(XML_ERROR, ARGV0, file, xml.err, xml.err_line); return(0); } - + /* Applying any variable found */ if(OS_ApplyVariables(&xml) != 0) { @@ -264,7 +263,7 @@ int ReadDecodeXML(char *file) NULL_Decoder = (void *)NULL_Decoder_tmp; - + i = 0; while(node[i]) { @@ -276,14 +275,14 @@ int ReadDecodeXML(char *file) char *prematch; char *p_name; - - if(!node[i]->element || + + if(!node[i]->element || strcasecmp(node[i]->element, xml_decoder) != 0) { merror(XML_INVELEM, ARGV0, node[i]->element); return(0); } - + /* Getting name */ if((!node[i]->attributes) || (!node[i]->values)|| @@ -294,7 +293,7 @@ int ReadDecodeXML(char *file) return(0); } - + /* Checking for additional entries */ if(node[i]->attributes[1] && node[i]->values[1]) { @@ -303,7 +302,7 @@ int ReadDecodeXML(char *file) merror(XML_INVELEM, ARGV0, node[i]->element); return(0); } - + if(node[i]->attributes[2]) { merror(XML_INVELEM, ARGV0, node[i]->element); @@ -311,7 +310,7 @@ int ReadDecodeXML(char *file) } } - + /* Getting decoder options */ elements = OS_GetElementsbyNode(&xml,node[i]); if(elements == NULL) @@ -327,8 +326,8 @@ int ReadDecodeXML(char *file) merror(MEM_ERROR,ARGV0); return(0); } - - + + /* Default values to the list */ pi->parent = NULL; pi->id = 0; @@ -344,19 +343,19 @@ int ReadDecodeXML(char *file) pi->get_next = 0; pi->regex_offset = 0; pi->prematch_offset = 0; - + regex = NULL; prematch = NULL; p_name = NULL; - - + + /* Checking if strdup worked */ if(!pi->name) { merror(MEM_ERROR, ARGV0); return(0); } - + /* Add decoder */ if(!addDecoder2list(pi->name)) { @@ -377,51 +376,51 @@ int ReadDecodeXML(char *file) merror(XML_VALUENULL, ARGV0, elements[j]->element); return(0); } - + /* Checking if it is a child of a rule */ else if(strcasecmp(elements[j]->element, xml_parent) == 0) { pi->parent = _loadmemory(pi->parent, elements[j]->content); } - + /* Getting the regex */ else if(strcasecmp(elements[j]->element,xml_regex) == 0) { int r_offset; r_offset = ReadDecodeAttrs(elements[j]->attributes, elements[j]->values); - + if(r_offset & AFTER_ERROR) { merror(DEC_REGEX_ERROR, ARGV0, pi->name); return(0); } - - /* Only the first regex entry may have an offset */ + + /* Only the first regex entry may have an offset */ if(regex && r_offset) { merror(DUP_REGEX, ARGV0, pi->name); merror(DEC_REGEX_ERROR, ARGV0, pi->name); return(0); } - + /* regex offset */ if(r_offset) { pi->regex_offset = r_offset; } - + /* Assign regex */ regex = _loadmemory(regex, elements[j]->content); } - + /* Getting the pre match */ else if(strcasecmp(elements[j]->element,xml_prematch)==0) { int r_offset; - + r_offset = ReadDecodeAttrs( elements[j]->attributes, elements[j]->values); @@ -431,7 +430,7 @@ int ReadDecodeXML(char *file) ErrorExit(DEC_REGEX_ERROR, ARGV0, pi->name); } - + /* Only the first prematch entry may have an offset */ if(prematch && r_offset) { @@ -443,7 +442,7 @@ int ReadDecodeXML(char *file) { pi->prematch_offset = r_offset; } - + prematch = _loadmemory(prematch, elements[j]->content); @@ -471,7 +470,7 @@ int ReadDecodeXML(char *file) int ed_c = 0; for(ed_c = 0; plugin_decoders[ed_c] != NULL; ed_c++) { - if(strcmp(plugin_decoders[ed_c], + if(strcmp(plugin_decoders[ed_c], elements[j]->content) == 0) { /* Initializing plugin */ @@ -491,8 +490,8 @@ int ReadDecodeXML(char *file) return(0); } } - - + + /* Getting the type */ else if(strcmp(elements[j]->element, xml_type) == 0) { @@ -501,17 +500,17 @@ int ReadDecodeXML(char *file) else if(strcmp(elements[j]->content, "ids") == 0) pi->type = IDS; else if(strcmp(elements[j]->content, "web-log") == 0) - pi->type = WEBLOG; + pi->type = WEBLOG; else if(strcmp(elements[j]->content, "syslog") == 0) pi->type = SYSLOG; else if(strcmp(elements[j]->content, "squid") == 0) pi->type = SQUID; else if(strcmp(elements[j]->content, "windows") == 0) - pi->type = WINDOWS; + pi->type = WINDOWS; else if(strcmp(elements[j]->content, "host-information") == 0) pi->type = HOST_INFO; else if(strcmp(elements[j]->content, "ossec") == 0) - pi->type = OSSEC_RL; + pi->type = OSSEC_RL; else { merror("%s: Invalid decoder type '%s'.", @@ -519,13 +518,13 @@ int ReadDecodeXML(char *file) return(0); } } - + /* Getting the order */ else if(strcasecmp(elements[j]->element,xml_order)==0) { char **norder, **s_norder; int order_int = 0; - + /* Maximum number is 8 for the order */ norder = OS_StrBreak(',',elements[j]->content, 8); s_norder = norder; @@ -539,7 +538,7 @@ int ReadDecodeXML(char *file) order_int++; } order_int = 0; - + /* Checking the values from the order */ while(*norder) @@ -619,23 +618,23 @@ int ReadDecodeXML(char *file) free(s_norder); } - + /* Getting the fts order */ else if(strcasecmp(elements[j]->element,xml_fts)==0) { char **norder; char **s_norder; - + /* Maximum number is 8 for the fts */ norder = OS_StrBreak(',',elements[j]->content, 8); if(norder == NULL) ErrorExit(MEM_ERROR,ARGV0); - - + + /* Saving the initial point to free later */ s_norder = norder; - - + + /* Checking the values from the fts */ while(*norder) { @@ -708,11 +707,11 @@ int ReadDecodeXML(char *file) /* NEXT */ j++; - + } /* while(elements[j]) */ - + OS_ClearNode(elements); - + /* Prematch must be set */ if(!prematch && !pi->parent && !p_name) @@ -728,7 +727,7 @@ int ReadDecodeXML(char *file) merror(DEC_REGEX_ERROR, ARGV0, pi->name); return(0); } - + /* For the offsets */ if(pi->regex_offset & AFTER_PARENT && !pi->parent) @@ -737,7 +736,7 @@ int ReadDecodeXML(char *file) merror(DEC_REGEX_ERROR, ARGV0, pi->name); return(0); } - + if(pi->regex_offset & AFTER_PREMATCH) { /* If after_prematch is set, but rule have @@ -756,7 +755,7 @@ int ReadDecodeXML(char *file) return(0); } } - + /* For the after_regex offset */ if(pi->regex_offset & AFTER_PREVREGEX) { @@ -767,7 +766,7 @@ int ReadDecodeXML(char *file) return(0); } } - + /* Checking the prematch offset */ if(pi->prematch_offset) @@ -789,7 +788,7 @@ int ReadDecodeXML(char *file) } } - + /* Compiling the regex/prematch */ if(prematch) { @@ -802,7 +801,7 @@ int ReadDecodeXML(char *file) free(prematch); } - + /* Compiling the p_name */ if(p_name) { @@ -815,7 +814,7 @@ int ReadDecodeXML(char *file) free(p_name); } - + /* We may not have the pi->regex */ if(regex) { @@ -843,11 +842,11 @@ int ReadDecodeXML(char *file) merror(DECODE_ADD, ARGV0, pi->name); return(0); } - + /* Adding osdecoder to the list */ if(!OS_AddOSDecoder(pi)) { - merror(DECODER_ERROR, ARGV0); + merror(DECODER_ERROR, ARGV0); return(0); } @@ -858,7 +857,7 @@ int ReadDecodeXML(char *file) /* Cleaning node and XML structures */ OS_ClearNode(node); - + OS_ClearXML(&xml); @@ -869,7 +868,7 @@ int ReadDecodeXML(char *file) int SetDecodeXML() -{ +{ /* Adding rootcheck decoder to list */ addDecoder2list(ROOTCHECK_MOD); addDecoder2list(SYSCHECK_MOD); diff --git a/src/analysisd/decoders/decoder.c b/src/analysisd/decoders/decoder.c index 70ac4cc..b5cb303 100755 --- a/src/analysisd/decoders/decoder.c +++ b/src/analysisd/decoders/decoder.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/decoders/decoder.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,11 +9,11 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ - + #include "shared.h" #include "os_regex/os_regex.h" #include "os_xml/os_xml.h" @@ -53,9 +54,9 @@ void DecodeEvent(Eventinfo *lf) { print_out("\n**Phase 2: Completed decoding."); } - #endif + #endif - do + do { nnode = node->osdecoder; @@ -63,7 +64,7 @@ void DecodeEvent(Eventinfo *lf) /* First checking program name */ if(lf->program_name) { - if(!OSMatch_Execute(lf->program_name, lf->p_name_size, + if(!OSMatch_Execute(lf->program_name, lf->p_name_size, nnode->program_name)) { continue; @@ -88,11 +89,11 @@ void DecodeEvent(Eventinfo *lf) #ifdef TESTRULE if(!alert_only)print_out(" decoder: '%s'", nnode->name); - #endif - + #endif + lf->decoder_info = nnode; - + child_node = node->child; @@ -121,7 +122,7 @@ void DecodeEvent(Eventinfo *lf) { char *llog; - /* If we have an offset set, use it */ + /* If we have an offset set, use it */ if(nnode->prematch_offset & AFTER_PARENT) { llog = pmatch; @@ -162,7 +163,7 @@ void DecodeEvent(Eventinfo *lf) return; child_node = child_node->next; - nnode = NULL; + nnode = NULL; } else { @@ -184,8 +185,8 @@ void DecodeEvent(Eventinfo *lf) nnode->plugindecoder(lf); return; } - - + + /* Getting the regex */ while(child_node) { @@ -272,7 +273,7 @@ void DecodeEvent(Eventinfo *lf) } /* ok to return */ - return; + return; }while((node=node->next) != NULL); #ifdef TESTRULE @@ -281,7 +282,7 @@ void DecodeEvent(Eventinfo *lf) print_out(" No decoder matched."); } #endif - + } @@ -291,7 +292,7 @@ void *DstUser_FP(Eventinfo *lf, char *field) #ifdef TESTRULE if(!alert_only)print_out(" dstuser: '%s'", field); #endif - + lf->dstuser = field; return(NULL); } @@ -300,7 +301,7 @@ void *SrcUser_FP(Eventinfo *lf, char *field) #ifdef TESTRULE if(!alert_only)print_out(" srcuser: '%s'", field); #endif - + lf->srcuser = field; return(NULL); } @@ -309,7 +310,7 @@ void *SrcIP_FP(Eventinfo *lf, char *field) #ifdef TESTRULE if(!alert_only)print_out(" srcip: '%s'", field); #endif - + lf->srcip = field; return(NULL); } @@ -318,7 +319,7 @@ void *DstIP_FP(Eventinfo *lf, char *field) #ifdef TESTRULE if(!alert_only)print_out(" dstip: '%s'", field); #endif - + lf->dstip = field; return(NULL); } @@ -327,7 +328,7 @@ void *SrcPort_FP(Eventinfo *lf, char *field) #ifdef TESTRULE if(!alert_only)print_out(" srcport: '%s'", field); #endif - + lf->srcport = field; return(NULL); } @@ -336,7 +337,7 @@ void *DstPort_FP(Eventinfo *lf, char *field) #ifdef TESTRULE if(!alert_only)print_out(" dstport: '%s'", field); #endif - + lf->dstport = field; return(NULL); } @@ -345,7 +346,7 @@ void *Protocol_FP(Eventinfo *lf, char *field) #ifdef TESTRULE if(!alert_only)print_out(" proto: '%s'", field); #endif - + lf->protocol = field; return(NULL); } @@ -354,7 +355,7 @@ void *Action_FP(Eventinfo *lf, char *field) #ifdef TESTRULE if(!alert_only)print_out(" action: '%s'", field); #endif - + lf->action = field; return(NULL); } @@ -363,7 +364,7 @@ void *ID_FP(Eventinfo *lf, char *field) #ifdef TESTRULE if(!alert_only)print_out(" id: '%s'", field); #endif - + lf->id = field; return(NULL); } @@ -372,7 +373,7 @@ void *Url_FP(Eventinfo *lf, char *field) #ifdef TESTRULE if(!alert_only)print_out(" url: '%s'", field); #endif - + lf->url = field; return(NULL); } @@ -381,7 +382,7 @@ void *Data_FP(Eventinfo *lf, char *field) #ifdef TESTRULE if(!alert_only)print_out(" extra_data: '%s'", field); #endif - + lf->data = field; return(NULL); } @@ -390,7 +391,7 @@ void *Status_FP(Eventinfo *lf, char *field) #ifdef TESTRULE if(!alert_only)print_out(" status: '%s'", field); #endif - + lf->status = field; return(NULL); } diff --git a/src/analysisd/decoders/decoder.h b/src/analysisd/decoders/decoder.h index 021f9ec..84e9e86 100755 --- a/src/analysisd/decoders/decoder.h +++ b/src/analysisd/decoders/decoder.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/decoders/decoder.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -24,8 +25,8 @@ #define AFTER_PARENT 0x001 /* 1 */ #define AFTER_PREMATCH 0x002 /* 2 */ -#define AFTER_PREVREGEX 0x004 /* 4 */ -#define AFTER_ERROR 0x010 +#define AFTER_PREVREGEX 0x004 /* 4 */ +#define AFTER_ERROR 0x010 @@ -39,16 +40,16 @@ typedef struct u_int16_t id; u_int16_t regex_offset; u_int16_t prematch_offset; - + int fts; char *parent; char *name; char *ftscomment; - + OSRegex *regex; OSRegex *prematch; OSMatch *program_name; - + void (*plugindecoder)(void *lf); void (**order)(void *lf, char *field); }OSDecoderInfo; diff --git a/src/analysisd/decoders/decoders_list.c b/src/analysisd/decoders/decoders_list.c index 5cbe9a8..652f785 100755 --- a/src/analysisd/decoders/decoders_list.c +++ b/src/analysisd/decoders/decoders_list.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/decoders/decoders_list.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -50,7 +51,7 @@ OSDecoderNode *OS_GetFirstOSDecoder(char *p_name) { return(osdecodernode_forpname); } - + return(osdecodernode_nopname); } @@ -60,11 +61,11 @@ OSDecoderNode *_OS_AddOSDecoder(OSDecoderNode *s_node, OSDecoderInfo *pi) { OSDecoderNode *tmp_node = s_node; int rm_f = 0; - + if(tmp_node) { OSDecoderNode *new_node; - + new_node = (OSDecoderNode *)calloc(1,sizeof(OSDecoderNode)); if(new_node == NULL) { @@ -82,9 +83,9 @@ OSDecoderNode *_OS_AddOSDecoder(OSDecoderNode *s_node, OSDecoderInfo *pi) if((tmp_node->osdecoder->prematch || tmp_node->osdecoder->regex) && pi->regex_offset) { - rm_f = 1; + rm_f = 1; } - + /* Multi-regexes patterns cannot have prematch */ if(pi->prematch) { @@ -109,24 +110,24 @@ OSDecoderNode *_OS_AddOSDecoder(OSDecoderNode *s_node, OSDecoderInfo *pi) return(NULL); } } - + }while(tmp_node->next && (tmp_node = tmp_node->next)); - - + + /* Must have a prematch set */ if(!rm_f && (pi->regex_offset & AFTER_PREVREGEX)) { merror(INV_OFFSET, ARGV0, pi->name); return(NULL); } - + tmp_node->next = new_node; - + new_node->next = NULL; - new_node->osdecoder = pi; + new_node->osdecoder = pi; new_node->child = NULL; } - + else { /* Must not have a previous regex set */ @@ -163,7 +164,7 @@ int OS_AddOSDecoder(OSDecoderInfo *pi) /* We can actually have two lists. One with program * name and the other without. */ - if(pi->program_name) + if(pi->program_name) { osdecodernode = osdecodernode_forpname; } @@ -172,7 +173,7 @@ int OS_AddOSDecoder(OSDecoderInfo *pi) osdecodernode = osdecodernode_nopname; } - + /* Search for parent on both lists */ if(pi->parent) { @@ -193,7 +194,7 @@ int OS_AddOSDecoder(OSDecoderInfo *pi) } tmp_node = tmp_node->next; } - + /* List without p name */ tmp_node = osdecodernode_nopname; @@ -218,9 +219,9 @@ int OS_AddOSDecoder(OSDecoderInfo *pi) { return(1); } - + merror(PPLUGIN_INV, ARGV0, pi->parent); - return(0); + return(0); } else { diff --git a/src/analysisd/decoders/hostinfo.c b/src/analysisd/decoders/hostinfo.c index 086964d..fa7c414 100755 --- a/src/analysisd/decoders/hostinfo.c +++ b/src/analysisd/decoders/hostinfo.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/decoders/hostinfo.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -94,7 +95,7 @@ void HostinfoInit() /* Opening HOSTINFO_FILE */ snprintf(_hi_buf,OS_SIZE_1024, "%s", HOSTINFO_FILE); - + /* r+ to read and write. Do not truncate */ _hi_fp = fopen(_hi_buf,"r+"); @@ -114,7 +115,7 @@ void HostinfoInit() return; } - + /* clearing the buffer */ memset(_hi_buf, '\0', OS_MAXSTR +1); @@ -147,7 +148,7 @@ int DecodeHostinfo(Eventinfo *lf) { int changed = 0; int bf_size; - + char *ip; char *portss; char *tmpstr; @@ -156,7 +157,7 @@ int DecodeHostinfo(Eventinfo *lf) char opened[OS_MAXSTR + 1]; FILE *fp; - + /* Checking maximum number of errors */ if(hi_err > 30) { @@ -164,7 +165,7 @@ int DecodeHostinfo(Eventinfo *lf) "Ignoring it.", ARGV0); return(0); } - + /* Zeroing buffers */ buffer[OS_MAXSTR] = '\0'; @@ -181,8 +182,8 @@ int DecodeHostinfo(Eventinfo *lf) /* Copying log to buffer */ strncpy(buffer,lf->log, OS_MAXSTR); - - + + /* Getting ip */ tmpstr = __go_after(buffer, HOST_HOST); if(!tmpstr) @@ -193,7 +194,7 @@ int DecodeHostinfo(Eventinfo *lf) return(0); } - + /* Setting ip */ ip = tmpstr; tmpstr = strchr(tmpstr, ','); @@ -216,8 +217,8 @@ int DecodeHostinfo(Eventinfo *lf) *tmpstr = '\0'; } bf_size = strlen(ip); - - + + /* Reads the file and search for a possible * entry */ @@ -232,13 +233,13 @@ int DecodeHostinfo(Eventinfo *lf) /* Removing new line */ tmpstr = strchr(_hi_buf, '\n'); if(tmpstr) - *tmpstr = '\0'; + *tmpstr = '\0'; /* Checking for ip */ if(strncmp(ip, _hi_buf, bf_size) == 0) { - /* Cannot use strncmp to avoid errors with crafted files */ + /* Cannot use strncmp to avoid errors with crafted files */ if(strcmp(portss, _hi_buf + bf_size) == 0) { return(0); @@ -252,9 +253,9 @@ int DecodeHostinfo(Eventinfo *lf) changed = 1; } } - } + } + - /* Adding the new entry at the end of the file */ fseek(fp, 0, SEEK_END); fprintf(fp,"%s%s\n", ip, portss); @@ -263,7 +264,7 @@ int DecodeHostinfo(Eventinfo *lf) /* Setting decoder */ lf->decoder_info = hostinfo_dec; - + /* Setting comment */ if(changed == 1) { @@ -274,7 +275,7 @@ int DecodeHostinfo(Eventinfo *lf) { hostinfo_dec->id = id_new; } - + return(1); } diff --git a/src/analysisd/decoders/plugin_decoders.h b/src/analysisd/decoders/plugin_decoders.h index 239549f..282eb31 100755 --- a/src/analysisd/decoders/plugin_decoders.h +++ b/src/analysisd/decoders/plugin_decoders.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/decoders/plugin_decoders.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -36,22 +37,22 @@ void *OSSECAlert_Decoder_Exec(void *lf); /* List of plugins. All three lists must be in the same order */ char *(plugin_decoders[])={"PF_Decoder", - "SymantecWS_Decoder", + "SymantecWS_Decoder", "SonicWall_Decoder", "OSSECAlert_Decoder", NULL}; -void *(plugin_decoders_init[]) = {PF_Decoder_Init, +void *(plugin_decoders_init[]) = {PF_Decoder_Init, SymantecWS_Decoder_Init, - SonicWall_Decoder_Init, + SonicWall_Decoder_Init, OSSECAlert_Decoder_Init, NULL}; -void *(plugin_decoders_exec[]) = {PF_Decoder_Exec, +void *(plugin_decoders_exec[]) = {PF_Decoder_Exec, SymantecWS_Decoder_Exec, SonicWall_Decoder_Exec, OSSECAlert_Decoder_Exec, NULL}; - + #endif diff --git a/src/analysisd/decoders/plugins/ossecalert_decoder.c b/src/analysisd/decoders/plugins/ossecalert_decoder.c index d0f642a..0f91fc0 100644 --- a/src/analysisd/decoders/plugins/ossecalert_decoder.c +++ b/src/analysisd/decoders/plugins/ossecalert_decoder.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/decoders/plugins/ossecalert_decoder.c, 2012/03/28 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -34,12 +35,12 @@ void *OSSECAlert_Decoder_Init() #define oa_strchr(x,y,z) z = strchr(x,y); if(!z){ return(NULL); } -/* OSSECAlert decoder +/* OSSECAlert decoder * Will extract the rule_id and point back to the original rule. * Will also extract srcip and username if available. * Examples: - * - */ + * + */ void *OSSECAlert_Decoder_Exec(Eventinfo *lf) { char *oa_id = 0; @@ -54,12 +55,13 @@ void *OSSECAlert_Decoder_Exec(Eventinfo *lf) /* Checking the alert level. */ - if(strncmp("Alert Level: ", lf->log, 12) != 0) + if(strncmp("Alert Level: ", lf->log, 12) != 0 && + strncmp("ossec: Alert Level:", lf->log, 18) != 0) { return(NULL); } - + /* Going past the level. */ oa_strchr(lf->log, ';', tmp_str); tmp_str++; @@ -71,10 +73,10 @@ void *OSSECAlert_Decoder_Exec(Eventinfo *lf) if(*tmp_str != ' ') { return(NULL); - } + } tmp_str++; - + /* Getting id. */ oa_id = tmp_str; oa_strchr(tmp_str, ' ', tmp_str); @@ -104,7 +106,7 @@ void *OSSECAlert_Decoder_Exec(Eventinfo *lf) /* Setting location; */ oa_location = tmp_str; - + oa_strchr(tmp_str, ';', tmp_str); *tmp_str = '\0'; @@ -122,7 +124,7 @@ void *OSSECAlert_Decoder_Exec(Eventinfo *lf) } else { - snprintf(oa_newlocation, 255, "%s->%s|%s", lf->hostname, + snprintf(oa_newlocation, 255, "%s->%s|%s", lf->hostname, lf->location, oa_location); free(lf->location); os_strdup(oa_newlocation, lf->location); @@ -132,7 +134,7 @@ void *OSSECAlert_Decoder_Exec(Eventinfo *lf) *tmp_str = ';'; tmp_str++; - + /* Getting additional fields. */ while((*tmp_str == ' ') && (tmp_str[1] != ' ')) { @@ -158,18 +160,18 @@ void *OSSECAlert_Decoder_Exec(Eventinfo *lf) *tmp_str = ';'; tmp_str++; } - + /* Removing space. */ while(*tmp_str == ' ') tmp_str++; - - + + /* Creating new full log. */ free(lf->full_log); os_strdup(tmp_str, lf->full_log); lf->log = lf->full_log; - + /* Rule that generated. */ lf->generated_rule = rule_pointer; diff --git a/src/analysisd/decoders/plugins/pf_decoder.c b/src/analysisd/decoders/plugins/pf_decoder.c index 3eb6fc6..8680ece 100644 --- a/src/analysisd/decoders/plugins/pf_decoder.c +++ b/src/analysisd/decoders/plugins/pf_decoder.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/decoders/plugins/pf_decoder.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -27,7 +28,7 @@ void *PF_Decoder_Init() } -/* OpenBSD PF decoder +/* OpenBSD PF decoder * Will extract the action,srcip,dstip,protocol,srcport,dstport * * Examples: @@ -37,7 +38,7 @@ void *PF_Decoder_Init() * Mar 30 15:54:22.174412 rule 3/(match) pass out on xl0: 192.168.2.10.1514 > 192.168.2.190.1030: udp 89 * Mar 30 17:47:40.390143 rule 2/(match) pass in on lo0: 127.0.0.1 > 127.0.0.1: icmp: echo reply * Mar 30 17:47:41.400075 rule 3/(match) pass out on lo0: 127.0.0.1 > 127.0.0.1: icmp: echo request - */ + */ void *PF_Decoder_Exec(Eventinfo *lf) { int port_count = 0; @@ -48,13 +49,13 @@ void *PF_Decoder_Exec(Eventinfo *lf) /* tmp_str should be: Mar 30 15:54:22.171929 rule 3/(match) pass out .. */ tmp_str = strchr(lf->log, ')'); - + /* Didn't match */ if(!tmp_str) { return(NULL); } - + /* Going to the action entry */ tmp_str++; if(*tmp_str != ' ') @@ -82,7 +83,7 @@ void *PF_Decoder_Exec(Eventinfo *lf) return(NULL); } - + /* Jumping to the src ip */ tmp_str = strchr(tmp_str, ':'); if(!tmp_str) @@ -97,32 +98,32 @@ void *PF_Decoder_Exec(Eventinfo *lf) tmp_str++; - + /* tmp_str should be: 192.168.2.10.1514 > .. */ aux_str = strchr(tmp_str, ' '); if(!aux_str) return(NULL); - - + + /* Setting aux_str to 0 for strdup */ *aux_str = '\0'; - + os_strdup(tmp_str, lf->srcip); - + /* Aux str has a valid pointer to lf->log now */ *aux_str = ' '; aux_str++; - - - + + + /* Setting the source port if present */ tmp_str = lf->srcip; while(*tmp_str != '\0') { if(*tmp_str == '.') port_count++; - - + + /* Found port */ if(port_count == 4) { @@ -131,7 +132,7 @@ void *PF_Decoder_Exec(Eventinfo *lf) os_strdup(tmp_str, lf->srcport); break; } - + tmp_str++; } @@ -151,14 +152,14 @@ void *PF_Decoder_Exec(Eventinfo *lf) tmp_str = strchr(aux_str, ':'); if(!tmp_str) return(NULL); - - + + /* Setting aux_str to 0 for strdup */ *tmp_str = '\0'; - + os_strdup(aux_str, lf->dstip); - - + + /* tmp str has a valid pointer to lf->log now */ *tmp_str = ':'; tmp_str++; @@ -171,8 +172,8 @@ void *PF_Decoder_Exec(Eventinfo *lf) { if(*aux_str == '.') port_count++; - - + + /* Found port */ if(port_count == 4) { @@ -181,7 +182,7 @@ void *PF_Decoder_Exec(Eventinfo *lf) os_strdup(aux_str, lf->dstport); break; } - + aux_str++; } @@ -206,10 +207,10 @@ void *PF_Decoder_Exec(Eventinfo *lf) { os_strdup("TCP", lf->protocol); } - + break; } - + return(NULL); } diff --git a/src/analysisd/decoders/plugins/sonicwall_decoder.c b/src/analysisd/decoders/plugins/sonicwall_decoder.c index 56c41a4..42e854a 100644 --- a/src/analysisd/decoders/plugins/sonicwall_decoder.c +++ b/src/analysisd/decoders/plugins/sonicwall_decoder.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/decoders/plugins/sonicwall_decoder.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -31,7 +32,7 @@ /** Global variables -- not thread safe. If we ever multi thread * analysisd, these will need to be changed. - */ + */ OSRegex *__sonic_regex_prid = NULL; OSRegex *__sonic_regex_sdip = NULL; OSRegex *__sonic_regex_prox = NULL; @@ -89,13 +90,13 @@ void *SonicWall_Decoder_Init() -/* SonicWall decoder +/* SonicWall decoder * Will extract the id, severity, action, srcip, dstip, protocol,srcport,dstport * severity will be extracted as status. * Examples: * Jan 3 13:45:36 192.168.5.1 id=firewall sn=000SERIAL time="2007-01-03 14:48:06" fw=1.1.1.1 pri=6 c=262144 m=98 msg="Connection Opened" n=23419 src=2.2.2.2:36701:WAN dst=1.1.1.1:50000:WAN proto=tcp/50000 * Jan 3 13:45:36 192.168.5.1 id=firewall sn=000SERIAL time="2007-01-03 14:48:07" fw=1.1.1.1 pri=1 c=32 m=30 msg="Administrator login denied due to bad credentials" n=7 src=2.2.2.2:36701:WAN dst=1.1.1.1:50000:WAN - */ + */ void *SonicWall_Decoder_Exec(Eventinfo *lf) { int i = 0; @@ -106,9 +107,9 @@ void *SonicWall_Decoder_Exec(Eventinfo *lf) /* Zeroing category */ category[0] = '\0'; lf->decoder_info->type = SYSLOG; - - - + + + /** We first run our regex to extract the severity, cat and id. **/ if(!(tmp_str = OSRegex_Execute(lf->log, __sonic_regex_prid))) { @@ -131,7 +132,7 @@ void *SonicWall_Decoder_Exec(Eventinfo *lf) /* Clearing all substrings */ __sonic_regex_prid->sub_strings[0] = NULL; __sonic_regex_prid->sub_strings[2] = NULL; - + free(__sonic_regex_prid->sub_strings[1]); __sonic_regex_prid->sub_strings[1] = NULL; } @@ -156,9 +157,9 @@ void *SonicWall_Decoder_Exec(Eventinfo *lf) { return(NULL); } - if(__sonic_regex_sdip->sub_strings[0] && - __sonic_regex_sdip->sub_strings[1] && - __sonic_regex_sdip->sub_strings[2] && + if(__sonic_regex_sdip->sub_strings[0] && + __sonic_regex_sdip->sub_strings[1] && + __sonic_regex_sdip->sub_strings[2] && __sonic_regex_sdip->sub_strings[3]) { /* Setting all the values */ @@ -186,7 +187,7 @@ void *SonicWall_Decoder_Exec(Eventinfo *lf) i = 0; tmp_str += 6; - + /* Allocating memory for the protocol */ os_calloc(8, sizeof(char), proto); @@ -222,7 +223,7 @@ void *SonicWall_Decoder_Exec(Eventinfo *lf) - + /** Setting the category/action based on the id. **/ /* IDS event */ @@ -230,16 +231,16 @@ void *SonicWall_Decoder_Exec(Eventinfo *lf) { lf->decoder_info->type = IDS; } - + /* Firewall connection opened */ else if((strcmp(lf->id, "98") == 0) || - (strcmp(lf->id, "597") == 0) || - (strcmp(lf->id, "598") == 0)) + (strcmp(lf->id, "597") == 0) || + (strcmp(lf->id, "598") == 0)) { lf->decoder_info->type = FIREWALL; - os_strdup("pass", lf->action); + os_strdup("pass", lf->action); } - + /* Firewall connection dropped */ else if((strcmp(lf->id, "38") == 0) || (strcmp(lf->id, "36") == 0) || @@ -248,16 +249,16 @@ void *SonicWall_Decoder_Exec(Eventinfo *lf) (strcmp(lf->id, "37") == 0)) { lf->decoder_info->type = FIREWALL; - os_strdup("drop", lf->action); + os_strdup("drop", lf->action); } - + /* Firewall connection closed */ else if(strcmp(lf->id, "537") == 0) { lf->decoder_info->type = FIREWALL; os_strdup("close", lf->action); } - + /* Proxy msg */ else if(strcmp(lf->id, "97") == 0) { @@ -269,7 +270,7 @@ void *SonicWall_Decoder_Exec(Eventinfo *lf) { return(NULL); } - + /* We first run our regex to extract the severity and id. */ if(!OSRegex_Execute(tmp_str, __sonic_regex_prox)) @@ -289,18 +290,18 @@ void *SonicWall_Decoder_Exec(Eventinfo *lf) { return(NULL); } - + /* Getting HTTP page */ - if(__sonic_regex_prox->sub_strings[1] && + if(__sonic_regex_prox->sub_strings[1] && __sonic_regex_prox->sub_strings[2]) { char *final_url; int url_size = strlen(__sonic_regex_prox->sub_strings[1]) + strlen(__sonic_regex_prox->sub_strings[2]) + 2; - + os_calloc(url_size +1, sizeof(char), final_url); - snprintf(final_url, url_size, "%s%s", + snprintf(final_url, url_size, "%s%s", __sonic_regex_prox->sub_strings[1], __sonic_regex_prox->sub_strings[2]); @@ -323,7 +324,7 @@ void *SonicWall_Decoder_Exec(Eventinfo *lf) return(NULL); } - + return(NULL); } diff --git a/src/analysisd/decoders/plugins/symantecws_decoder.c b/src/analysisd/decoders/plugins/symantecws_decoder.c index f958f2e..5ee3ecc 100644 --- a/src/analysisd/decoders/plugins/symantecws_decoder.c +++ b/src/analysisd/decoders/plugins/symantecws_decoder.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/decoders/plugins/symantecws_decoder.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -26,25 +27,25 @@ void *SymantecWS_Decoder_Init() } -/* Symantec Web Security decoder +/* Symantec Web Security decoder * Will extract the action, srcip, id, url and username. * - * Examples (also online at + * Examples (also online at * http://www.ossec.net/wiki/index.php/Symantec_WebSecurity ). * 20070717,73613,1=5,11=10.1.1.3,10=userc,3=1,2=1 * 20070717,73614,1=5,11=1.2.3.4,1106=News,60=http://news.bbc.co.uk/,10=userX,1000=212.58.240.42,2=27 - */ + */ void *SymantecWS_Decoder_Exec(Eventinfo *lf) { int count = 0; char buf_str[OS_SIZE_1024 +1]; char *tmp_str = NULL; - + /* Initializing buffer */ buf_str[0] = '\0'; buf_str[OS_SIZE_1024] = '\0'; - - + + /* Removing date and time */ if(!(tmp_str = strchr(lf->log, ','))) { @@ -55,8 +56,8 @@ void *SymantecWS_Decoder_Exec(Eventinfo *lf) return(NULL); } tmp_str++; - - + + /* Getting all the values */ while(tmp_str != NULL) { @@ -65,9 +66,9 @@ void *SymantecWS_Decoder_Exec(Eventinfo *lf) { count = 0; tmp_str+=3; - while(*tmp_str != '\0' && count < 128 && *tmp_str != ',') + while(*tmp_str != '\0' && count < 128 && *tmp_str != ',') { - buf_str[count] = *tmp_str; + buf_str[count] = *tmp_str; count++; tmp_str++; } buf_str[count] = '\0'; @@ -77,15 +78,15 @@ void *SymantecWS_Decoder_Exec(Eventinfo *lf) os_strdup(buf_str, lf->dstuser); } } - + /* Checking the ip address */ else if(strncmp(tmp_str, "11=", 3) == 0) { count = 0; tmp_str+=3; - while(*tmp_str != '\0' && count < 128 && *tmp_str != ',') + while(*tmp_str != '\0' && count < 128 && *tmp_str != ',') { - buf_str[count] = *tmp_str; + buf_str[count] = *tmp_str; count++; tmp_str++; } buf_str[count] = '\0'; @@ -102,9 +103,9 @@ void *SymantecWS_Decoder_Exec(Eventinfo *lf) { count = 0; tmp_str+=3; - while(*tmp_str != '\0' && count < OS_SIZE_1024 && *tmp_str != ',') + while(*tmp_str != '\0' && count < OS_SIZE_1024 && *tmp_str != ',') { - buf_str[count] = *tmp_str; + buf_str[count] = *tmp_str; count++; tmp_str++; } buf_str[count] = '\0'; @@ -142,7 +143,7 @@ void *SymantecWS_Decoder_Exec(Eventinfo *lf) tmp_str++; } } - + return(NULL); } diff --git a/src/analysisd/decoders/rootcheck.c b/src/analysisd/decoders/rootcheck.c index 0fc7e04..b72a677 100755 --- a/src/analysisd/decoders/rootcheck.c +++ b/src/analysisd/decoders/rootcheck.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/decoders/rootcheck.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -41,7 +42,7 @@ void RootcheckInit() int i = 0; rk_err = 0; - + for(;ifts = 0; debug1("%s: RootcheckInit completed.", ARGV0); - + return; } @@ -79,8 +80,8 @@ FILE *RK_File(char *agent, int *agent_id) *agent_id = i; return(rk_agent_fps[i]); } - - i++; + + i++; } /* If here, our agent wasn't found */ @@ -89,7 +90,7 @@ FILE *RK_File(char *agent, int *agent_id) if(rk_agent_ips[i] != NULL) { snprintf(rk_buf,OS_SIZE_1024, "%s/%s", ROOTCHECK_DIR,agent); - + /* r+ to read and write. Do not truncate */ rk_agent_fps[i] = fopen(rk_buf,"r+"); if(!rk_agent_fps[i]) @@ -105,7 +106,7 @@ FILE *RK_File(char *agent, int *agent_id) if(!rk_agent_fps[i]) { merror(FOPEN_ERROR, ARGV0, rk_buf); - + free(rk_agent_ips[i]); rk_agent_ips[i] = NULL; @@ -163,7 +164,7 @@ int DecodeRootcheck(Eventinfo *lf) merror("%s: Error handling rootcheck database (fgetpos).",ARGV0); return(0); } - + /* Reads the file and search for a possible * entry @@ -186,14 +187,14 @@ int DecodeRootcheck(Eventinfo *lf) tmpstr = strchr(rk_buf, '\n'); if(tmpstr) { - *tmpstr = '\0'; + *tmpstr = '\0'; } - + /* Old format without the time stampts */ if(rk_buf[0] != '!') { - /* Cannot use strncmp to avoid errors with crafted files */ + /* Cannot use strncmp to avoid errors with crafted files */ if(strcmp(lf->log, rk_buf) == 0) { rootcheck_dec->fts = 0; @@ -206,14 +207,14 @@ int DecodeRootcheck(Eventinfo *lf) { /* Going past time: !1183431603!1183431603 (last, first saw) */ tmpstr = rk_buf + 23; - + /* Matches, we need to upgrade last time saw */ if(strcmp(lf->log, tmpstr) == 0) { fsetpos(fp, &fp_pos); fprintf(fp, "!%d", lf->time); rootcheck_dec->fts = 0; - lf->decoder_info = rootcheck_dec; + lf->decoder_info = rootcheck_dec; return(1); } } @@ -224,9 +225,9 @@ int DecodeRootcheck(Eventinfo *lf) merror("%s: Error handling rootcheck database (fgetpos3).",ARGV0); return(0); } - } + } + - /* Adding the new entry at the end of the file */ fseek(fp, 0, SEEK_END); fprintf(fp,"!%d!%d %s\n",lf->time, lf->time, lf->log); @@ -235,7 +236,7 @@ int DecodeRootcheck(Eventinfo *lf) rootcheck_dec->fts = 0; rootcheck_dec->fts |= FTS_DONE; lf->decoder_info = rootcheck_dec; - return(1); + return(1); } diff --git a/src/analysisd/decoders/syscheck.c b/src/analysisd/decoders/syscheck.c index 840ed9d..8618813 100755 --- a/src/analysisd/decoders/syscheck.c +++ b/src/analysisd/decoders/syscheck.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/decoders/syscheck.c, 2012/02/07 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -44,7 +45,7 @@ typedef struct __sdb int id3; int idn; int idd; - + /* Syscheck rule */ OSDecoderInfo *syscheck_dec; @@ -52,7 +53,7 @@ typedef struct __sdb /* File search variables */ fpos_t init_pos; - + }_sdb; /* syscheck db information */ @@ -69,7 +70,7 @@ void SyscheckInit() int i = 0; sdb.db_err = 0; - + for(;i <= MAX_AGENTS;i++) { sdb.agent_ips[i] = NULL; @@ -80,7 +81,7 @@ void SyscheckInit() /* Clearing db memory */ memset(sdb.buf, '\0', OS_MAXSTR +1); memset(sdb.comment, '\0', OS_MAXSTR +1); - + memset(sdb.size, '\0', OS_FLSIZE +1); memset(sdb.perm, '\0', OS_FLSIZE +1); memset(sdb.owner, '\0', OS_FLSIZE +1); @@ -95,13 +96,13 @@ void SyscheckInit() sdb.syscheck_dec->name = SYSCHECK_MOD; sdb.syscheck_dec->type = OSSEC_RL; sdb.syscheck_dec->fts = 0; - + sdb.id1 = getDecoderfromlist(SYSCHECK_MOD); sdb.id2 = getDecoderfromlist(SYSCHECK_MOD2); sdb.id3 = getDecoderfromlist(SYSCHECK_MOD3); sdb.idn = getDecoderfromlist(SYSCHECK_NEW); sdb.idd = getDecoderfromlist(SYSCHECK_DEL); - + debug1("%s: SyscheckInit completed.", ARGV0); return; } @@ -115,7 +116,7 @@ void SyscheckInit() void __setcompleted(char *agent) { FILE *fp; - + /* Getting agent file */ snprintf(sdb.buf, OS_FLSIZE , "%s/.%s.cpt", SYSCHECK_DIR, agent); @@ -153,7 +154,7 @@ void DB_SetCompleted(Eventinfo *lf) int i = 0; /* Finding file pointer */ - while(sdb.agent_ips[i] != NULL) + while(sdb.agent_ips[i] != NULL && i < MAX_AGENTS) { if(strcmp(sdb.agent_ips[i], lf->location) == 0) { @@ -162,7 +163,7 @@ void DB_SetCompleted(Eventinfo *lf) { return; } - + __setcompleted(lf->location); @@ -184,7 +185,7 @@ FILE *DB_File(char *agent, int *agent_id) int i = 0; /* Finding file pointer */ - while(sdb.agent_ips[i] != NULL) + while(sdb.agent_ips[i] != NULL && i < MAX_AGENTS) { if(strcmp(sdb.agent_ips[i], agent) == 0) { @@ -193,18 +194,24 @@ FILE *DB_File(char *agent, int *agent_id) *agent_id = i; return(sdb.agent_fps[i]); } - - i++; + + i++; } /* If here, our agent wasn't found */ + if (i == MAX_AGENTS) + { + merror("%s: Unable to open integrity file. Increase MAX_AGENTS.",ARGV0); + return(NULL); + } + os_strdup(agent, sdb.agent_ips[i]); /* Getting agent file */ snprintf(sdb.buf, OS_FLSIZE , "%s/%s", SYSCHECK_DIR,agent); - - + + /* r+ to read and write. Do not truncate */ sdb.agent_fps[i] = fopen(sdb.buf,"r+"); if(!sdb.agent_fps[i]) @@ -217,8 +224,8 @@ FILE *DB_File(char *agent, int *agent_id) sdb.agent_fps[i] = fopen(sdb.buf, "r+"); } } - - /* Checking again */ + + /* Checking again */ if(!sdb.agent_fps[i]) { merror("%s: Unable to open '%s'",ARGV0, sdb.buf); @@ -232,12 +239,12 @@ FILE *DB_File(char *agent, int *agent_id) /* Returning the opened pointer (the beginning of it) */ fseek(sdb.agent_fps[i],0, SEEK_SET); *agent_id = i; - - + + /* Getting if the agent was completed */ if(__iscompleted(agent)) { - sdb.agent_cp[i][0] = '1'; + sdb.agent_cp[i][0] = '1'; } return(sdb.agent_fps[i]); @@ -252,10 +259,10 @@ int DB_Search(char *f_name, char *c_sum, Eventinfo *lf) int p = 0; int sn_size; int agent_id; - + char *saved_sum; char *saved_name; - + FILE *fp; @@ -278,8 +285,8 @@ int DB_Search(char *f_name, char *c_sum, Eventinfo *lf) merror("%s: Error handling integrity database (fgetpos).",ARGV0); return(0); } - - + + /* Looping the file */ while(fgets(sdb.buf, OS_MAXSTR, fp) != NULL) { @@ -291,7 +298,7 @@ int DB_Search(char *f_name, char *c_sum, Eventinfo *lf) } - /* Getting name */ + /* Getting name */ saved_name = strchr(sdb.buf, ' '); if(saved_name == NULL) { @@ -301,8 +308,8 @@ int DB_Search(char *f_name, char *c_sum, Eventinfo *lf) } *saved_name = '\0'; saved_name++; - - + + /* New format - with a timestamp */ if(*saved_name == '!') { @@ -331,7 +338,7 @@ int DB_Search(char *f_name, char *c_sum, Eventinfo *lf) fgetpos(fp, &sdb.init_pos); continue; } - + saved_sum = sdb.buf; @@ -355,10 +362,10 @@ int DB_Search(char *f_name, char *c_sum, Eventinfo *lf) if(saved_sum[-2] == '!') { p++; - if(saved_sum[-1] == '!') + if(saved_sum[-1] == '!') p++; else if(saved_sum[-1] == '?') - p+=2; + p+=2; } } @@ -418,7 +425,7 @@ int DB_Search(char *f_name, char *c_sum, Eventinfo *lf) "File '%.756s' was deleted. Unable to retrieve " "checksum.", f_name); } - + /* If file was re-added, do not compare changes */ else if(saved_sum[0] == '-' && saved_sum[1] == '1') { @@ -427,10 +434,10 @@ int DB_Search(char *f_name, char *c_sum, Eventinfo *lf) "File '%.756s' was re-added.", f_name); } - else + else { int oldperm = 0, newperm = 0; - + /* Providing more info about the file change */ char *oldsize = NULL, *newsize = NULL; char *olduid = NULL, *newuid = NULL; @@ -544,16 +551,16 @@ int DB_Search(char *f_name, char *c_sum, Eventinfo *lf) "to '%c%c%c%c%c%c%c%c%c'\n", (oldperm & S_IRUSR)? 'r' : '-', (oldperm & S_IWUSR)? 'w' : '-', - + (oldperm & S_ISUID)? 's' : (oldperm & S_IXUSR)? 'x' : '-', - + (oldperm & S_IRGRP)? 'r' : '-', (oldperm & S_IWGRP)? 'w' : '-', (oldperm & S_ISGID)? 's' : (oldperm & S_IXGRP)? 'x' : '-', - + (oldperm & S_IROTH)? 'r' : '-', (oldperm & S_IWOTH)? 'w' : '-', @@ -568,10 +575,10 @@ int DB_Search(char *f_name, char *c_sum, Eventinfo *lf) (newperm & S_ISUID)? 's' : (newperm & S_IXUSR)? 'x' : '-', - + (newperm & S_IRGRP)? 'r' : '-', (newperm & S_IWGRP)? 'w' : '-', - + (newperm & S_ISGID)? 's' : (newperm & S_IXGRP)? 'x' : '-', @@ -603,7 +610,7 @@ int DB_Search(char *f_name, char *c_sum, Eventinfo *lf) os_strdup(olduid, lf->owner_before); os_strdup(newuid, lf->owner_after); #endif - } + } /* group ownership message */ if(!newgid || !oldgid || strcmp(newgid, oldgid) == 0) @@ -657,7 +664,7 @@ int DB_Search(char *f_name, char *c_sum, Eventinfo *lf) #endif - /* Provide information about the file */ + /* Provide information about the file */ snprintf(sdb.comment, OS_MAXSTR, "Integrity checksum changed for: " "'%.756s'\n" "%s" @@ -667,7 +674,7 @@ int DB_Search(char *f_name, char *c_sum, Eventinfo *lf) "%s" "%s" "%s%s", - f_name, + f_name, sdb.size, sdb.perm, sdb.owner, @@ -686,21 +693,22 @@ int DB_Search(char *f_name, char *c_sum, Eventinfo *lf) lf->log = lf->full_log; lf->data = NULL; - + /* Setting decoder */ lf->decoder_info = sdb.syscheck_dec; - - return(1); + + return(1); } /* continuiing... */ /* If we reach here, this file is not present on our database */ fseek(fp, 0, SEEK_END); - + fprintf(fp,"+++%s !%d %s\n", c_sum, lf->time, f_name); + fflush(fp); /* Alert if configured to notify on new files */ if((Config.syscheck_alert_new == 1) && (DB_IsCompleted(agent_id))) @@ -711,7 +719,7 @@ int DB_Search(char *f_name, char *c_sum, Eventinfo *lf) snprintf(sdb.comment, OS_MAXSTR, "New file '%.756s' " "added to the file system.", f_name); - + /* Creating a new log message */ free(lf->full_log); @@ -739,10 +747,10 @@ int DecodeSyscheck(Eventinfo *lf) { char *c_sum; char *f_name; - - + + /* Every syscheck message must be in the following format: - * checksum filename + * checksum filename */ f_name = strchr(lf->log, ' '); if(f_name == NULL) @@ -755,7 +763,7 @@ int DecodeSyscheck(Eventinfo *lf) DB_SetCompleted(lf); return(0); } - + merror(SK_INV_MSG, ARGV0); return(0); } @@ -777,14 +785,14 @@ int DecodeSyscheck(Eventinfo *lf) { lf->data = NULL; } - - + + /* Checking if file is supposed to be ignored */ if(Config.syscheck_ignore) { char **ff_ig = Config.syscheck_ignore; - + while(*ff_ig) { if(strncasecmp(*ff_ig, f_name, strlen(*ff_ig)) == 0) @@ -792,16 +800,16 @@ int DecodeSyscheck(Eventinfo *lf) lf->data = NULL; return(0); } - + ff_ig++; } } - - + + /* Checksum is at the beginning of the log */ c_sum = lf->log; - - + + /* Searching for file changes */ return(DB_Search(f_name, c_sum, lf)); } diff --git a/src/analysisd/dodiff.c b/src/analysisd/dodiff.c index c17de31..2fba506 100755 --- a/src/analysisd/dodiff.c +++ b/src/analysisd/dodiff.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/dodiff.c, 2012/07/23 dcid Exp $ + */ /* Copyright (C) 2010 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -34,7 +35,7 @@ static int _add2last(char *str, int strsize, char *file) dirrule = strrchr(file, '/'); if(!dirrule) { - merror("%s: ERROR: Invalid file name to diff: %s", + merror("%s: ERROR: Invalid file name to diff: %s", ARGV0, file); return(0); } @@ -99,6 +100,7 @@ int doDiff(RuleInfo *currently_rule, Eventinfo *lf) currently_rule->last_events[0] = NULL; + if(lf->hostname[0] == '(') { htpt = strchr(lf->hostname, ')'); @@ -106,8 +108,8 @@ int doDiff(RuleInfo *currently_rule, Eventinfo *lf) { *htpt = '\0'; } - snprintf(flastfile, OS_SIZE_2048, "%s/%s/%d/%s", DIFF_DIR, lf->hostname+1, - currently_rule->sigid, DIFF_LAST_FILE); + snprintf(flastfile, OS_SIZE_2048, "%s/%s/%d/%s", DIFF_DIR, lf->hostname+1, + currently_rule->sigid, DIFF_LAST_FILE); if(htpt) { @@ -117,7 +119,7 @@ int doDiff(RuleInfo *currently_rule, Eventinfo *lf) } else { - snprintf(flastfile, OS_SIZE_2048, "%s/%s/%d/%s", DIFF_DIR, lf->hostname, + snprintf(flastfile, OS_SIZE_2048, "%s/%s/%d/%s", DIFF_DIR, lf->hostname, currently_rule->sigid, DIFF_LAST_FILE); } @@ -133,7 +135,6 @@ int doDiff(RuleInfo *currently_rule, Eventinfo *lf) date_of_change = File_DateofChange(flastfile); if(date_of_change <= 0) { - merror("last file: %s",flastfile); if(!_add2last(lf->log, lf->size, flastfile)) { merror("%s: ERROR: unable to create last file: %s", ARGV0, flastfile); @@ -181,8 +182,8 @@ int doDiff(RuleInfo *currently_rule, Eventinfo *lf) { *htpt = '\0'; } - snprintf(fdifffile, OS_SIZE_2048, "%s/%s/%d/state.%d", DIFF_DIR, lf->hostname+1, - currently_rule->sigid, date_of_change); + snprintf(fdifffile, OS_SIZE_2048, "%s/%s/%d/state.%d", DIFF_DIR, lf->hostname+1, + currently_rule->sigid, date_of_change); if(htpt) { @@ -192,7 +193,7 @@ int doDiff(RuleInfo *currently_rule, Eventinfo *lf) } else { - snprintf(fdifffile, OS_SIZE_2048, "%s/%s/%d/state.%d", DIFF_DIR, lf->hostname, + snprintf(fdifffile, OS_SIZE_2048, "%s/%s/%d/state.%d", DIFF_DIR, lf->hostname, currently_rule->sigid, date_of_change); } diff --git a/src/analysisd/eventinfo.c b/src/analysisd/eventinfo.c index 9cfa45c..b35fd40 100755 --- a/src/analysisd/eventinfo.c +++ b/src/analysisd/eventinfo.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/eventinfo.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -16,7 +17,7 @@ /* Part of the OSSEC. * Available at http://www.ossec.net */ - + #include "config.h" @@ -33,8 +34,8 @@ Eventinfo *Search_LastSids(Eventinfo *my_lf, RuleInfo *currently_rule) Eventinfo *lf; Eventinfo *first_lf; OSListNode *lf_node; - - + + /* Setting frequency to 0 */ currently_rule->__frequency = 0; @@ -52,12 +53,12 @@ Eventinfo *Search_LastSids(Eventinfo *my_lf, RuleInfo *currently_rule) return(NULL); } first_lf = (Eventinfo *)lf_node->data; - + do { lf = (Eventinfo *)lf_node->data; - + /* If time is outside the timeframe, return */ if((c_time - lf->time) > currently_rule->timeframe) { @@ -154,19 +155,20 @@ Eventinfo *Search_LastSids(Eventinfo *my_lf, RuleInfo *currently_rule) /* Checking if the number of matches worked */ - if(currently_rule->__frequency < currently_rule->frequency) + if(currently_rule->__frequency <= 10) { - if(currently_rule->__frequency <= 10) - { - currently_rule->last_events[currently_rule->__frequency] - = lf->full_log; - currently_rule->last_events[currently_rule->__frequency+1] - = NULL; - } + currently_rule->last_events[currently_rule->__frequency] + = lf->full_log; + currently_rule->last_events[currently_rule->__frequency+1] + = NULL; + } + if(currently_rule->__frequency < currently_rule->frequency) + { currently_rule->__frequency++; continue; } + currently_rule->__frequency++; /* If reached here, we matched */ @@ -342,16 +344,16 @@ Eventinfo *Search_LastGroups(Eventinfo *my_lf, RuleInfo *currently_rule) } -/* Search LastEvents. +/* Search LastEvents. * Will look if any of the last events (inside the timeframe) - * match the specified rule. + * match the specified rule. */ Eventinfo *Search_LastEvents(Eventinfo *my_lf, RuleInfo *currently_rule) { EventNode *eventnode_pt; Eventinfo *lf; Eventinfo *first_lf; - + merror("XXXX : remove me!"); @@ -363,17 +365,17 @@ Eventinfo *Search_LastEvents(Eventinfo *my_lf, RuleInfo *currently_rule) /* Nothing found */ return(NULL); } - + /* Setting frequency to 0 */ currently_rule->__frequency = 0; first_lf = (Eventinfo *)eventnode_pt->event; - - + + /* Searching all previous events */ do { lf = eventnode_pt->event; - + /* If time is outside the timeframe, return */ if((c_time - lf->time) > currently_rule->timeframe) { @@ -381,22 +383,22 @@ Eventinfo *Search_LastEvents(Eventinfo *my_lf, RuleInfo *currently_rule) } - /* We avoid multiple triggers for the same rule + /* We avoid multiple triggers for the same rule * or rules with a lower level. */ else if(lf->matched >= currently_rule->level) { return(NULL); } - - + + /* The category must be the same */ else if(lf->decoder_info->type != my_lf->decoder_info->type) { - continue; + continue; } - - + + /* If regex does not match, go to next */ if(currently_rule->if_matched_regex) { @@ -412,27 +414,27 @@ Eventinfo *Search_LastEvents(Eventinfo *my_lf, RuleInfo *currently_rule) { if((!lf->dstuser)||(!my_lf->dstuser)) continue; - + if(strcmp(lf->dstuser,my_lf->dstuser) != 0) continue; } - + /* Checking for same id */ if(currently_rule->context_opts & SAME_ID) { if((!lf->id) || (!my_lf->id)) continue; - + if(strcmp(lf->id,my_lf->id) != 0) - continue; + continue; } - + /* Checking for repetitions from same src_ip */ if(currently_rule->context_opts & SAME_SRCIP) { if((!lf->srcip)||(!my_lf->srcip)) continue; - + if(strcmp(lf->srcip,my_lf->srcip) != 0) continue; } @@ -451,33 +453,33 @@ Eventinfo *Search_LastEvents(Eventinfo *my_lf, RuleInfo *currently_rule) } } - - /* Checking if the number of matches worked */ + + /* Checking if the number of matches worked */ if(currently_rule->__frequency < currently_rule->frequency) { if(currently_rule->__frequency <= 10) { - currently_rule->last_events[currently_rule->__frequency] + currently_rule->last_events[currently_rule->__frequency] = lf->full_log; - currently_rule->last_events[currently_rule->__frequency+1] + currently_rule->last_events[currently_rule->__frequency+1] = NULL; } - + currently_rule->__frequency++; continue; } - - + + /* If reached here, we matched */ my_lf->matched = currently_rule->level; lf->matched = currently_rule->level; first_lf->matched = currently_rule->level; - - return(lf); - + + return(lf); + }while((eventnode_pt = eventnode_pt->next) != NULL); - + return(NULL); } @@ -508,7 +510,7 @@ void Zero_Eventinfo(Eventinfo *lf) lf->time = 0; lf->matched = 0; - + lf->year = 0; lf->mon[3] = '\0'; lf->hour[9] = '\0'; @@ -520,18 +522,18 @@ void Zero_Eventinfo(Eventinfo *lf) #ifdef PRELUDE lf->filename = NULL; - lf->perm_before = 0; - lf->perm_after = 0; - lf->md5_before = NULL; - lf->md5_after = NULL; - lf->sha1_before = NULL; - lf->sha1_after = NULL; - lf->size_before = NULL; - lf->size_after = NULL; - lf->owner_before = NULL; - lf->owner_after = NULL; - lf->gowner_before = NULL; - lf->gowner_after = NULL; + lf->perm_before = 0; + lf->perm_after = 0; + lf->md5_before = NULL; + lf->md5_after = NULL; + lf->sha1_before = NULL; + lf->sha1_after = NULL; + lf->size_before = NULL; + lf->size_after = NULL; + lf->owner_before = NULL; + lf->owner_after = NULL; + lf->gowner_before = NULL; + lf->gowner_after = NULL; #endif return; @@ -545,11 +547,11 @@ void Free_Eventinfo(Eventinfo *lf) merror("%s: Trying to free NULL event. Inconsistent..",ARGV0); return; } - + if(lf->full_log) - free(lf->full_log); + free(lf->full_log); if(lf->location) - free(lf->location); + free(lf->location); if(lf->srcip) free(lf->srcip); @@ -562,13 +564,13 @@ void Free_Eventinfo(Eventinfo *lf) if(lf->protocol) free(lf->protocol); if(lf->action) - free(lf->action); + free(lf->action); if(lf->status) free(lf->status); if(lf->srcuser) free(lf->srcuser); if(lf->dstuser) - free(lf->dstuser); + free(lf->dstuser); if(lf->id) free(lf->id); if(lf->command) @@ -577,39 +579,39 @@ void Free_Eventinfo(Eventinfo *lf) free(lf->url); if(lf->data) - free(lf->data); + free(lf->data); if(lf->systemname) - free(lf->systemname); + free(lf->systemname); #ifdef PRELUDE if(lf->filename) free(lf->filename); if (lf->md5_before) - free(lf->md5_before); + free(lf->md5_before); if (lf->md5_after) - free(lf->md5_after); + free(lf->md5_after); if (lf->sha1_before) - free(lf->sha1_before); + free(lf->sha1_before); if (lf->sha1_after) - free(lf->sha1_after); + free(lf->sha1_after); if (lf->size_before) - free(lf->size_before); + free(lf->size_before); if (lf->size_after) - free(lf->size_after); + free(lf->size_after); if (lf->owner_before) - free(lf->owner_before); + free(lf->owner_before); if (lf->owner_after) - free(lf->owner_after); + free(lf->owner_after); if (lf->gowner_before) - free(lf->gowner_before); + free(lf->gowner_before); if (lf->gowner_after) - free(lf->gowner_after); + free(lf->gowner_after); #endif /* Freeing node to delete */ if(lf->sid_node_to_delete) { - OSList_DeleteThisNode(lf->generated_rule->sid_prev_matched, + OSList_DeleteThisNode(lf->generated_rule->sid_prev_matched, lf->sid_node_to_delete); } else if(lf->generated_rule && lf->generated_rule->group_prev_matched) @@ -620,16 +622,16 @@ void Free_Eventinfo(Eventinfo *lf) { OSList_DeleteOldestNode(lf->generated_rule->group_prev_matched[i]); i++; - } + } } - + /* We dont need to free: * fts * comment */ free(lf); - lf = NULL; - + lf = NULL; + return; } diff --git a/src/analysisd/eventinfo.h b/src/analysisd/eventinfo.h index 3129630..fb5b4b6 100755 --- a/src/analysisd/eventinfo.h +++ b/src/analysisd/eventinfo.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/eventinfo.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -63,7 +64,7 @@ typedef struct _Eventinfo /* Other internal variables */ short int matched; - + int time; int day; int year; diff --git a/src/analysisd/eventinfo_list.c b/src/analysisd/eventinfo_list.c index 282212d..a2d096f 100755 --- a/src/analysisd/eventinfo_list.c +++ b/src/analysisd/eventinfo_list.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/eventinfo_list.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,12 +9,12 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ -#include "shared.h" +#include "shared.h" #include "eventinfo.h" @@ -43,46 +44,46 @@ EventNode *OS_GetLastEvent() { EventNode *eventnode_pt = eventnode; - return(eventnode_pt); + return(eventnode_pt); } /* Add an event to the list -- always to the begining */ void OS_AddEvent(Eventinfo *lf) { EventNode *tmp_node = eventnode; - + if(tmp_node) { EventNode *new_node; new_node = (EventNode *)calloc(1,sizeof(EventNode)); - + if(new_node == NULL) { ErrorExit(MEM_ERROR,ARGV0); } - /* Always adding to the beginning of the list + /* Always adding to the beginning of the list * The new node will become the first node and * new_node->next will be the previous first node */ new_node->next = tmp_node; new_node->prev = NULL; tmp_node->prev = new_node; - + eventnode = new_node; /* Adding the event to the node */ new_node->event = lf; _memoryused++; - + /* Need to remove the last nodes */ if(_memoryused > _memorymaxsize) { int i = 0; EventNode *oldlast; - - /* Remove at least the last 10 events + + /* Remove at least the last 10 events * or the events that will not match anymore * (higher than max frequency) */ @@ -101,7 +102,7 @@ void OS_AddEvent(Eventinfo *lf) } } } - + else { /* Adding first node */ @@ -114,8 +115,8 @@ void OS_AddEvent(Eventinfo *lf) eventnode->prev = NULL; eventnode->next = NULL; eventnode->event = lf; - - lastnode = eventnode; + + lastnode = eventnode; } return; diff --git a/src/analysisd/fts.c b/src/analysisd/fts.c index 2f155bf..9ab65c6 100755 --- a/src/analysisd/fts.c +++ b/src/analysisd/fts.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/fts.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,12 +9,12 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ -/* First time seen functions +/* First time seen functions */ @@ -38,8 +39,8 @@ int FTS_Init() char _line[OS_FLSIZE + 1]; _line[OS_FLSIZE] = '\0'; - - + + fts_list = OSList_Create(); if(!fts_list) { @@ -59,7 +60,7 @@ int FTS_Init() merror(LIST_ERROR, ARGV0); return(0); } - + /* Getting default list size */ fts_list_size = getDefine_Int("analysisd", @@ -70,7 +71,7 @@ int FTS_Init() fts_minsize_for_str = getDefine_Int("analysisd", "fts_min_size_for_str", 6, 128); - + if(!OSList_SetMaxSize(fts_list, fts_list_size)) { merror(LIST_SIZE_ERROR, ARGV0); @@ -86,7 +87,14 @@ int FTS_Init() fp_list = fopen(FTS_QUEUE, "w+"); if(fp_list) fclose(fp_list); - + + chmod(FTS_QUEUE, 0640); + + int uid = Privsep_GetUser(USER); + int gid = Privsep_GetGroup(GROUPGLOBAL); + if(uid>=0 && gid>=0) + chown(FTS_QUEUE, uid, gid); + fp_list = fopen(FTS_QUEUE, "r+"); if(!fp_list) { @@ -118,7 +126,7 @@ int FTS_Init() } } - + /* Creating ignore list */ fp_ignore = fopen(IG_QUEUE, "r+"); if(!fp_ignore) @@ -127,7 +135,14 @@ int FTS_Init() fp_ignore = fopen(IG_QUEUE, "w+"); if(fp_ignore) fclose(fp_ignore); - + + chmod(IG_QUEUE, 0640); + + int uid = Privsep_GetUser(USER); + int gid = Privsep_GetGroup(GROUPGLOBAL); + if(uid>=0 && gid>=0) + chown(IG_QUEUE, uid, gid); + fp_ignore = fopen(IG_QUEUE, "r+"); if(!fp_ignore) { @@ -137,7 +152,7 @@ int FTS_Init() } debug1("%s: DEBUG: FTSInit completed.", ARGV0); - + return(1); } @@ -145,12 +160,12 @@ int FTS_Init() */ void AddtoIGnore(Eventinfo *lf) { - fseek(fp_ignore, 0, SEEK_END); + fseek(fp_ignore, 0, SEEK_END); #ifdef TESTRULE return; #endif - + /* Assigning the values to the FTS */ fprintf(fp_ignore, "%s %s %s %s %s %s %s %s\n", (lf->decoder_info->name && (lf->generated_rule->ignore & FTS_NAME))? @@ -163,9 +178,9 @@ void AddtoIGnore(Eventinfo *lf) (lf->dstip && (lf->generated_rule->ignore & FTS_DSTIP))? lf->dstip:"", (lf->data && (lf->generated_rule->ignore & FTS_DATA))? - lf->data:"", + lf->data:"", (lf->systemname && (lf->generated_rule->ignore & FTS_SYSTEMNAME))? - lf->systemname:"", + lf->systemname:"", (lf->generated_rule->ignore & FTS_LOCATION)?lf->location:""); fflush(fp_ignore); @@ -200,7 +215,7 @@ int IGnore(Eventinfo *lf) (lf->data && (lf->generated_rule->ignore & FTS_DATA))? lf->data:"", (lf->systemname && (lf->generated_rule->ignore & FTS_SYSTEMNAME))? - lf->systemname:"", + lf->systemname:"", (lf->generated_rule->ckignore & FTS_LOCATION)?lf->location:""); _fline[OS_FLSIZE] = '\0'; @@ -225,13 +240,13 @@ int IGnore(Eventinfo *lf) /* FTS v0.1 * Check if the word "msg" is present on the "queue". * If it is not, write it there. - */ + */ int FTS(Eventinfo *lf) { int number_of_matches = 0; char _line[OS_FLSIZE + 1]; - + char *line_for_list = NULL; OSListNode *fts_node; @@ -256,9 +271,9 @@ int FTS(Eventinfo *lf) if(OSHash_Get(fts_store, _line)) { return(0); - } + } + - /* Checking if from the last FTS events, we had * at least 3 "similars" before. If yes, we just * ignore it. @@ -268,7 +283,7 @@ int FTS(Eventinfo *lf) fts_node = OSList_GetLastNode(fts_list); while(fts_node) { - if(OS_StrHowClosedMatch((char *)fts_node->data, _line) > + if(OS_StrHowClosedMatch((char *)fts_node->data, _line) > fts_minsize_for_str) { number_of_matches++; @@ -287,8 +302,8 @@ int FTS(Eventinfo *lf) os_strdup(_line, line_for_list); OSList_AddData(fts_list, line_for_list); } - - + + /* Storing new entry */ if(line_for_list == NULL) { @@ -300,12 +315,12 @@ int FTS(Eventinfo *lf) return(0); } - + #ifdef TESTRULE return(1); #endif - - + + /* Saving to fts fp */ fseek(fp_list, 0, SEEK_END); fprintf(fp_list,"%s\n", _line); diff --git a/src/analysisd/fts.h b/src/analysisd/fts.h index 67daee8..1b10210 100755 --- a/src/analysisd/fts.h +++ b/src/analysisd/fts.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/fts.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. diff --git a/src/analysisd/lists.c b/src/analysisd/lists.c index 4c0b2c4..9d907dc 100644 --- a/src/analysisd/lists.c +++ b/src/analysisd/lists.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/lists.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 3) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -25,7 +26,7 @@ void Lists_OP_CreateLists() { OS_CreateListsList(); - return; + return; } int Lists_OP_LoadList(char * listfile) @@ -33,13 +34,13 @@ int Lists_OP_LoadList(char * listfile) /* XXX Jeremy: I hate this. I think I'm missing something dumb here */ char *holder; char a_filename[OS_MAXSTR]; - a_filename[OS_MAXSTR - 2] = '\0'; char b_filename[OS_MAXSTR]; + ListNode *tmp_listnode_pt = NULL; + + a_filename[OS_MAXSTR - 2] = '\0'; b_filename[OS_MAXSTR - 2] = '\0'; - ListNode *tmp_listnode_pt = NULL; tmp_listnode_pt = (ListNode *)calloc(1,sizeof(ListNode)); - debug1("crated new listnode for %s\n", listfile); if (tmp_listnode_pt == NULL) ErrorExit(MEM_ERROR,ARGV0); snprintf(a_filename, OS_MAXSTR-1, "%s", listfile); diff --git a/src/analysisd/lists.h b/src/analysisd/lists.h index a17cbe7..3668899 100644 --- a/src/analysisd/lists.h +++ b/src/analysisd/lists.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/lists.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. diff --git a/src/analysisd/lists_list.c b/src/analysisd/lists_list.c index 1078e55..55394db 100644 --- a/src/analysisd/lists_list.c +++ b/src/analysisd/lists_list.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/lists_list.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -9,7 +10,7 @@ * Foundation */ - + #include "shared.h" #include "rules.h" #include "cdb/cdb.h" @@ -22,7 +23,7 @@ ListNode *global_listnode; ListRule *global_listrule; -/* +/* */ ListNode *_OS_AddList(ListNode *new_listnode); @@ -40,14 +41,14 @@ void OS_CreateListsList() ListNode *OS_GetFirstList() { ListNode *listnode_pt = global_listnode; - - return(listnode_pt); + + return(listnode_pt); } ListRule *OS_GetFirstListRule() { - ListRule *listrule_pt = global_listrule; - return listrule_pt; + ListRule *listrule_pt = global_listrule; + return listrule_pt; } void OS_ListLoadRules() @@ -66,19 +67,19 @@ void OS_ListLoadRules() ListRule *_OS_AddListRule(ListRule *new_listrule) { - + if(global_listrule == NULL) { global_listrule = new_listrule; - } - else + } + else { ListRule *last_list_rule = global_listrule; while(last_list_rule->next != NULL) { - last_list_rule = last_list_rule->next; + last_list_rule = last_list_rule->next; } - last_list_rule->next = new_listrule; + last_list_rule->next = new_listrule; } return(global_listrule); } @@ -103,7 +104,7 @@ ListNode *_OS_AddList(ListNode *new_listnode) last_list_node = last_list_node->next; } last_list_node->next = new_listnode; - + } return(global_listnode); } @@ -122,7 +123,7 @@ ListNode *_OS_FindList(ListNode *_listnode, char *listname) do { if (strcmp(last_list_node->txt_filename, listname) == 0 || - strcmp(last_list_node->cdb_filename, listname) == 0) + strcmp(last_list_node->cdb_filename, listname) == 0) { /* Found first match returning */ return(last_list_node); @@ -132,7 +133,7 @@ ListNode *_OS_FindList(ListNode *_listnode, char *listname) } return(NULL); } - + ListNode *OS_FindList(char *listname) { ListNode *matched = NULL; @@ -140,9 +141,9 @@ ListNode *OS_FindList(char *listname) return matched; } -ListRule *OS_AddListRule(ListRule *first_rule_list, - int lookup_type, - int field, +ListRule *OS_AddListRule(ListRule *first_rule_list, + int lookup_type, + int field, char *listname, OSMatch *matcher) { @@ -151,7 +152,7 @@ ListRule *OS_AddListRule(ListRule *first_rule_list, new_rulelist_pt->field = field; new_rulelist_pt->next = NULL; new_rulelist_pt->matcher = matcher; - new_rulelist_pt->lookup_type = lookup_type; + new_rulelist_pt->lookup_type = lookup_type; new_rulelist_pt->filename = listname; if((new_rulelist_pt->db = OS_FindList(listname)) == NULL) new_rulelist_pt->loaded = 0; @@ -211,11 +212,11 @@ int OS_DBSearchKeyValue(ListRule *lrule, char *key) cdb_read(&lrule->db->cdb, val, vlen, vpos); result = OSMatch_Execute(val, vlen, lrule->matcher); free(val); - return result; + return result; } else { return 0; } - } + } return 0; } @@ -227,7 +228,7 @@ int OS_DBSeachKey(ListRule *lrule, char *key) { if(_OS_CDBOpen(lrule->db) == -1) return -1; if( cdb_find(&lrule->db->cdb, key, strlen(key)) > 0 ) return 1; - } + } return 0; } @@ -239,12 +240,12 @@ int OS_DBSeachKeyAddress(ListRule *lrule, char *key) { if(_OS_CDBOpen(lrule->db) == -1) return -1; //snprintf(_ip,128,"%s",key); - //XXX Breka apart string on the . boundtrys a loop over to longest match. + //XXX Breka apart string on the . boundtrys a loop over to longest match. if( cdb_find(&lrule->db->cdb, key, strlen(key)) > 0 ) { return 1; } - else + else { char *tmpkey; os_strdup(key, tmpkey); @@ -255,19 +256,19 @@ int OS_DBSeachKeyAddress(ListRule *lrule, char *key) if( cdb_find(&lrule->db->cdb, tmpkey, strlen(tmpkey)) > 0 ) { free(tmpkey); return 1; - } + } } tmpkey[strlen(tmpkey) - 1] = '\0'; } free(tmpkey); } - } + } return 0; } int OS_DBSearch(ListRule *lrule, char *key) { - //XXX - god damn hack!!! Jeremy Rossi + //XXX - god damn hack!!! Jeremy Rossi if (lrule->loaded == 0) { lrule->db = OS_FindList(lrule->filename); @@ -279,7 +280,7 @@ int OS_DBSearch(ListRule *lrule, char *key) //debug1("LR_STRING_MATCH"); if(OS_DBSeachKey(lrule, key) == 1) return 1; - else + else return 0; break; case LR_STRING_NOT_MATCH: @@ -305,10 +306,10 @@ int OS_DBSearch(ListRule *lrule, char *key) else return 0; break; - case LR_ADDRESS_MATCH_VALUE: + case LR_ADDRESS_MATCH_VALUE: //debug1("LR_ADDRESS_MATCH_VALUE"); - // XXX TODO - return 0; + // XXX TODO + return 0; break; default: debug1("lists_list.c::OS_DBSearch should never hit default"); diff --git a/src/analysisd/lists_make.c b/src/analysisd/lists_make.c index 3448916..f8fb1ab 100644 --- a/src/analysisd/lists_make.c +++ b/src/analysisd/lists_make.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/lists_make.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -46,7 +47,7 @@ void Lists_OP_MakeCDB(char *txt_filename, char *cdb_filename, int force) str[OS_MAXSTR]= '\0'; char tmp_filename[OS_MAXSTR]; - tmp_filename[OS_MAXSTR - 2] = '\0'; + tmp_filename[OS_MAXSTR - 2] = '\0'; snprintf(tmp_filename, OS_MAXSTR - 2, "%s.tmp", txt_filename); /* @@ -68,20 +69,20 @@ void Lists_OP_MakeCDB(char *txt_filename, char *cdb_filename, int force) } while((fgets(str, OS_MAXSTR-1,txt_fd)) != NULL) { - /* Removing new lines or carriage returns. */ - tmp_str = strchr(str, '\r'); - if(tmp_str) - *tmp_str = '\0'; - tmp_str = strchr(str, '\n'); - if(tmp_str) - *tmp_str = '\0'; + /* Removing new lines or carriage returns. */ + tmp_str = strchr(str, '\r'); + if(tmp_str) + *tmp_str = '\0'; + tmp_str = strchr(str, '\n'); + if(tmp_str) + *tmp_str = '\0'; if((val = strchr(str, ':'))) { *val = '\0'; val++; } else - { + { continue; } key = str; diff --git a/src/analysisd/lists_make.h b/src/analysisd/lists_make.h index 4a22e4d..1d5977e 100644 --- a/src/analysisd/lists_make.h +++ b/src/analysisd/lists_make.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/lists_make.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. diff --git a/src/analysisd/makelists.c b/src/analysisd/makelists.c index 9299592..a5afd77 100644 --- a/src/analysisd/makelists.c +++ b/src/analysisd/makelists.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/makelists.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2010 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -16,13 +17,13 @@ /* Part of the OSSEC * Available at http://www.ossec.net */ - + /* ossec-analysisd. * Responsible for correlation and log decoding. */ -#ifdef ARGV0 - #undef ARGV0 +#ifdef ARGV0 + #undef ARGV0 #define ARGV0 "ossec-testrule" #endif @@ -143,7 +144,7 @@ int main(int argc, char **argv) /* Found user */ debug1(FOUND_USER, ARGV0); - + /* Reading configuration file */ if(GlobalConf(cfg) < 0) { @@ -151,7 +152,7 @@ int main(int argc, char **argv) } debug1(READ_CONFIG, ARGV0); - + /* Setting the group */ if(Privsep_SetGroup(gid) < 0) ErrorExit(SETGID_ERROR,ARGV0,group); @@ -161,8 +162,8 @@ int main(int argc, char **argv) ErrorExit(CHROOT_ERROR,ARGV0,dir); nowChroot(); - - + + /* Createing the lists for use in rules */ Lists_OP_CreateLists(); diff --git a/src/analysisd/picviz.c b/src/analysisd/picviz.c index 960bcad..a98ff1b 100644 --- a/src/analysisd/picviz.c +++ b/src/analysisd/picviz.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/picviz.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Sebastien Tricaud * Copyright (C) 2009 Trend Micro Inc. @@ -27,7 +28,7 @@ void OS_PicvizOpen(char *socket) if(!picviz_fp) { merror("%s: Unable to open picviz socket file '%s'.", - ARGV0, socket); + ARGV0, socket); } } diff --git a/src/analysisd/picviz.h b/src/analysisd/picviz.h index 2e71f84..6b2f338 100644 --- a/src/analysisd/picviz.h +++ b/src/analysisd/picviz.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/picviz.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Sebastien Tricaud * Copyright (C) 2009 Trend Micro Inc. diff --git a/src/analysisd/prelude.c b/src/analysisd/prelude.c index 1dfcf2c..711c57a 100644 --- a/src/analysisd/prelude.c +++ b/src/analysisd/prelude.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/prelude.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -40,7 +41,7 @@ char *(ossec2prelude_sev[])={"info","info","info","info", "low","low","low","low", "medium", "medium", "medium", "medium", "high", "high", "high", "high", "high"}; - + /* Prelude client */ static prelude_client_t *prelude_client; @@ -58,7 +59,7 @@ void prelude_idmef_debug(idmef_message_t *idmef) -static int +static int add_idmef_object(idmef_message_t *msg, const char *object, const char *value) { int ret = 0; @@ -78,16 +79,16 @@ add_idmef_object(idmef_message_t *msg, const char *object, const char *value) } ret = idmef_value_new_from_path(&val, path, value); - if(ret < 0) + if(ret < 0) { idmef_path_destroy(path); return(-1); } ret = idmef_path_set(path, msg, val); - if(ret < 0) + if(ret < 0) { - merror("%s: OSSEC2Prelude: IDMEF: Cannot add object '%s': %s.", + merror("%s: OSSEC2Prelude: IDMEF: Cannot add object '%s': %s.", ARGV0, object, prelude_strerror(ret)); } @@ -143,16 +144,16 @@ void prelude_start(char *profile, int argc, char **argv) ret = prelude_init(&argc, argv); - if (ret < 0) + if (ret < 0) { merror("%s: %s: Unable to initialize the Prelude library: %s.", ARGV0, prelude_strsource(ret), prelude_strerror(ret)); return; } - ret = prelude_client_new(&prelude_client, + ret = prelude_client_new(&prelude_client, profile!=NULL?profile:DEFAULT_ANALYZER_NAME); - if (!prelude_client) + if (!prelude_client) { merror("%s: %s: Unable to create a prelude client object: %s.", ARGV0, prelude_strsource(ret), prelude_strerror(ret)); @@ -162,25 +163,25 @@ void prelude_start(char *profile, int argc, char **argv) ret = setup_analyzer(prelude_client_get_analyzer(prelude_client)); - if(ret < 0) + if(ret < 0) { merror("%s: %s: Unable to setup analyzer: %s", ARGV0, prelude_strsource(ret), prelude_strerror(ret)); - prelude_client_destroy(prelude_client, + prelude_client_destroy(prelude_client, PRELUDE_CLIENT_EXIT_STATUS_FAILURE); return; } - ret = prelude_client_set_flags(prelude_client, - prelude_client_get_flags(prelude_client) + ret = prelude_client_set_flags(prelude_client, + prelude_client_get_flags(prelude_client) | PRELUDE_CLIENT_FLAGS_ASYNC_TIMER); if(ret < 0) { merror("%s: %s: Unable to set prelude client flags: %s.", - ARGV0, prelude_strsource(ret), prelude_strerror(ret)); + ARGV0, prelude_strsource(ret), prelude_strerror(ret)); } @@ -192,12 +193,12 @@ void prelude_start(char *profile, int argc, char **argv) ret = prelude_client_start(prelude_client); - if (ret < 0) + if (ret < 0) { merror("%s: %s: Unable to initialize prelude client: %s.", ARGV0, prelude_strsource(ret), prelude_strerror(ret)); - prelude_client_destroy(prelude_client, + prelude_client_destroy(prelude_client, PRELUDE_CLIENT_EXIT_STATUS_FAILURE); return; @@ -208,13 +209,13 @@ void prelude_start(char *profile, int argc, char **argv) } -void FileAccess_PreludeLog(idmef_message_t *idmef, - int filenum, - char *filename, - char *md5, - char *sha1, - char *owner, - char *gowner, +void FileAccess_PreludeLog(idmef_message_t *idmef, + int filenum, + char *filename, + char *md5, + char *sha1, + char *owner, + char *gowner, int perm) { int _checksum_counter = 0; @@ -237,7 +238,7 @@ void FileAccess_PreludeLog(idmef_message_t *idmef, return; } - + /* Add the hashs */ if (md5) { snprintf(_prelude_section,128,"alert.target(0).file(%d).checksum(%d).algorithm",filenum, _checksum_counter); @@ -261,7 +262,7 @@ void FileAccess_PreludeLog(idmef_message_t *idmef, add_idmef_object(idmef, _prelude_section,owner); snprintf(_prelude_section,128,"alert.target(0).file(%d).File_Access(%d).user_id.type",filenum,FILE_USER); add_idmef_object(idmef, _prelude_section, "user-privs"); - } + } /*add the group owner */ if (gowner) { debug1("%s: DEBUG: gowner = %s.", ARGV0, gowner); @@ -338,7 +339,7 @@ void OS_PreludeLog(Eventinfo *lf) idmef_message_t *idmef; RuleInfoDetail *last_info_detail; - + /* Generate prelude alert */ ret = idmef_message_new(&idmef); if ( ret < 0 ) { @@ -346,14 +347,14 @@ void OS_PreludeLog(Eventinfo *lf) return; } - - add_idmef_object(idmef, "alert.assessment.impact.description", + + add_idmef_object(idmef, "alert.assessment.impact.description", lf->generated_rule->comment); - add_idmef_object(idmef, "alert.assessment.impact.severity", - (lf->generated_rule->level > 15) ? "high": + add_idmef_object(idmef, "alert.assessment.impact.severity", + (lf->generated_rule->level > 15) ? "high": ossec2prelude_sev[lf->generated_rule->level]); - + add_idmef_object(idmef, "alert.assessment.impact.completion", "succeeded"); if (lf->action) @@ -379,7 +380,7 @@ void OS_PreludeLog(Eventinfo *lf) case 'T': snprintf(_prelude_data,256,"CLOSED: %s", lf->action); break; - /* allow, accept, */ + /* allow, accept, */ case 'a': case 'A': /* pass/permitted */ @@ -387,7 +388,7 @@ void OS_PreludeLog(Eventinfo *lf) case 'P': /* open */ case 'o': - case 'O': + case 'O': snprintf(_prelude_data,256,"ALLOW: %s", lf->action); break; default: @@ -405,7 +406,7 @@ void OS_PreludeLog(Eventinfo *lf) /* Begin Classification Infomations */ { - add_idmef_object(idmef, "alert.classification.text", + add_idmef_object(idmef, "alert.classification.text", lf->generated_rule->comment); @@ -428,7 +429,7 @@ void OS_PreludeLog(Eventinfo *lf) } /* Rule sid is used to create a link to the rule on the OSSEC wiki */ - if(lf->generated_rule->sigid) + if(lf->generated_rule->sigid) { snprintf(_prelude_section,128,"alert.classification.reference(%d).origin", classification_counter); @@ -447,17 +448,17 @@ void OS_PreludeLog(Eventinfo *lf) classification_counter); snprintf(_prelude_data, 256,"http://www.ossec.net/wiki/Rule:%d", lf->generated_rule->sigid); - add_idmef_object(idmef, _prelude_section, _prelude_data); + add_idmef_object(idmef, _prelude_section, _prelude_data); classification_counter++; } /* Extended Info Details */ - for (last_info_detail = lf->generated_rule->info_details; - last_info_detail != NULL; + for (last_info_detail = lf->generated_rule->info_details; + last_info_detail != NULL; last_info_detail = last_info_detail->next) { - if (last_info_detail->type == RULEINFODETAIL_LINK) + if (last_info_detail->type == RULEINFODETAIL_LINK) { snprintf(_prelude_section,128,"alert.classification.reference(%d).origin", classification_counter); @@ -469,16 +470,16 @@ void OS_PreludeLog(Eventinfo *lf) add_idmef_object(idmef, _prelude_section, _prelude_data); snprintf(_prelude_section,128,"alert.classification.reference(%d).url", classification_counter); - add_idmef_object(idmef, _prelude_section, last_info_detail->data); + add_idmef_object(idmef, _prelude_section, last_info_detail->data); classification_counter++; - } + } else if(last_info_detail->type == RULEINFODETAIL_TEXT) { snprintf(_prelude_section,128,"alert.classification.reference(%d).origin", classification_counter); add_idmef_object(idmef, _prelude_section, "vendor-specific"); - + snprintf(_prelude_section,128,"alert.classification.reference(%d).name", classification_counter); snprintf(_prelude_data,256,"Rule:%d info",lf->generated_rule->sigid); @@ -493,7 +494,7 @@ void OS_PreludeLog(Eventinfo *lf) { snprintf(_prelude_section,128,"alert.classification.reference(%d).origin", classification_counter); - switch(last_info_detail->type) + switch(last_info_detail->type) { case RULEINFODETAIL_CVE: add_idmef_object(idmef, _prelude_section, "cve"); @@ -515,11 +516,11 @@ void OS_PreludeLog(Eventinfo *lf) } - /* Break ok the list of groups on the "," boundry + /* Break ok the list of groups on the "," boundry * For each section create a prelude reference classification - * that points back to the the OSSEC wiki for more infomation. + * that points back to the the OSSEC wiki for more infomation. */ - if(lf->generated_rule->group) + if(lf->generated_rule->group) { char *copy_group; char new_generated_rule_group[256]; @@ -544,7 +545,7 @@ void OS_PreludeLog(Eventinfo *lf) classification_counter); snprintf(_prelude_data,256,"http://www.ossec.net/wiki/Group:%s", copy_group); - add_idmef_object(idmef, _prelude_section, _prelude_data); + add_idmef_object(idmef, _prelude_section, _prelude_data); classification_counter++; copy_group = strtok(NULL, ","); @@ -555,10 +556,10 @@ void OS_PreludeLog(Eventinfo *lf) /* Begin Node infomation block */ - { + { /* Setting source info. */ add_idmef_object(idmef, "alert.source(0).Spoofed", "no"); - add_idmef_object(idmef, "alert.source(0).Node.Address(0).address", + add_idmef_object(idmef, "alert.source(0).Node.Address(0).address", lf->srcip); add_idmef_object(idmef, "alert.source(0).Service.port", lf->srcport); @@ -566,15 +567,15 @@ void OS_PreludeLog(Eventinfo *lf) { add_idmef_object(idmef, "alert.source(0).User.UserId(0).name", lf->srcuser); } - + /* Setting target */ add_idmef_object(idmef, "alert.target(0).Service.name", lf->program_name); add_idmef_object(idmef, "alert.target(0).Spoofed", "no"); - if(lf->dstip) + if(lf->dstip) { - add_idmef_object(idmef, "alert.target(0).Node.Address(0).address", + add_idmef_object(idmef, "alert.target(0).Node.Address(0).address", lf->dstip); } else @@ -595,7 +596,7 @@ void OS_PreludeLog(Eventinfo *lf) { *tmp_str = '\0'; } - add_idmef_object(idmef, "alert.target(0).Node.Address(0).address", + add_idmef_object(idmef, "alert.target(0).Node.Address(0).address", new_prelude_target); } add_idmef_object(idmef, "alert.target(0).Service.name", lf->hostname); @@ -607,14 +608,14 @@ void OS_PreludeLog(Eventinfo *lf) add_idmef_object(idmef, "alert.target(0).User.UserId(0).name", lf->dstuser); } } /* end Node infomation block */ - + /* Setting source file. */ add_idmef_object(idmef, "alert.additional_data(0).type", "string"); add_idmef_object(idmef, "alert.additional_data(0).meaning", "Source file"); add_idmef_object(idmef, "alert.additional_data(0).data", lf->location); additional_data_counter++; - + /* Setting full log. */ add_idmef_object(idmef, "alert.additional_data(1).type", "string"); diff --git a/src/analysisd/rules.c b/src/analysisd/rules.c index 8ce5f8d..d018cef 100755 --- a/src/analysisd/rules.c +++ b/src/analysisd/rules.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/rules.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -29,11 +30,11 @@ /* Internal functions */ -int getattributes(char **attributes, +int getattributes(char **attributes, char **values, - int *id, int *level, + int *id, int *level, int *maxsize, int *timeframe, - int *frequency, int *accuracy, + int *frequency, int *accuracy, int *noalert, int *ignore_time, int *overwrite); @@ -60,15 +61,15 @@ void Rules_OP_CreateRules() /* Rules_OP_ReadRules, v0.3, 2005/03/21 * Read the log rules. * v0.3: Fixed many memory problems. - */ + */ int Rules_OP_ReadRules(char * rulefile) { OS_XML xml; XML_NODE node = NULL; - /* XML variables */ + /* XML variables */ /* These are the available options for the rule configuration */ - + char *xml_group = "group"; char *xml_rule = "rule"; @@ -83,7 +84,7 @@ int Rules_OP_ReadRules(char * rulefile) char *xml_comment = "description"; char *xml_ignore = "ignore"; char *xml_check_if_ignored = "check_if_ignored"; - + char *xml_srcip = "srcip"; char *xml_srcport = "srcport"; char *xml_dstip = "dstip"; @@ -107,17 +108,17 @@ int Rules_OP_ReadRules(char * rulefile) char *xml_match_key_value = "match_key_value"; char *xml_address_key = "address_match_key"; char *xml_not_address_key = "not_address_match_key"; - char *xml_address_key_value = "address_match_key_value"; + char *xml_address_key_value = "address_match_key_value"; char *xml_if_sid = "if_sid"; char *xml_if_group = "if_group"; char *xml_if_level = "if_level"; char *xml_fts = "if_fts"; - + char *xml_if_matched_regex = "if_matched_regex"; char *xml_if_matched_group = "if_matched_group"; char *xml_if_matched_sid = "if_matched_sid"; - + char *xml_same_source_ip = "same_source_ip"; char *xml_same_src_port = "same_src_port"; char *xml_same_dst_port = "same_dst_port"; @@ -127,16 +128,16 @@ int Rules_OP_ReadRules(char * rulefile) char *xml_dodiff = "check_diff"; char *xml_different_url = "different_url"; - + char *xml_notsame_source_ip = "not_same_source_ip"; char *xml_notsame_user = "not_same_user"; char *xml_notsame_agent = "not_same_agent"; char *xml_notsame_id = "not_same_id"; char *xml_options = "options"; - + char *rulepath; - + int i; int default_timeframe = 360; @@ -159,11 +160,11 @@ int Rules_OP_ReadRules(char * rulefile) debug1("%s is the rulefile", rulefile); debug1("Not modifing the rule path"); } - - - i = 0; - - /* Reading the XML */ + + + i = 0; + + /* Reading the XML */ if(OS_ReadXML(rulepath,&xml) < 0) { merror(XML_ERROR, ARGV0, rulepath, xml.err, xml.err_line); @@ -174,9 +175,9 @@ int Rules_OP_ReadRules(char * rulefile) /* Debug wrapper */ debug2("%s: DEBUG: read xml for rule.", ARGV0); - - + + /* Applying any variable found */ if(OS_ApplyVariables(&xml) != 0) { @@ -187,7 +188,7 @@ int Rules_OP_ReadRules(char * rulefile) /* Debug wrapper */ debug2("%s: DEBUG: XML Variables applied.", ARGV0); - + /* Getting the root elements */ node = OS_GetElementsbyNode(&xml,NULL); @@ -195,7 +196,7 @@ int Rules_OP_ReadRules(char * rulefile) { merror(CONFIG_ERROR, ARGV0, rulepath); OS_ClearXML(&xml); - return(-1); + return(-1); } @@ -242,7 +243,7 @@ int Rules_OP_ReadRules(char * rulefile) } - /* Getting the rules now */ + /* Getting the rules now */ i=0; while(node[i]) { @@ -250,7 +251,7 @@ int Rules_OP_ReadRules(char * rulefile) int j = 0; - /* Getting all rules for a global group */ + /* Getting all rules for a global group */ rule = OS_GetElementsbyNode(&xml,node[i]); if(rule == NULL) { @@ -263,7 +264,7 @@ int Rules_OP_ReadRules(char * rulefile) while(rule[j]) { RuleInfo *config_ruleinfo = NULL; - + /* Checking if the rule element is correct */ if((!rule[j]->element)|| @@ -285,17 +286,17 @@ int Rules_OP_ReadRules(char * rulefile) return(-1); } - + /* Attribute block */ { int id = -1,level = -1,maxsize = 0,timeframe = 0; int frequency = 0, accuracy = 1, noalert = 0, ignore_time = 0; int overwrite = 0; - + /* Getting default time frame */ timeframe = default_timeframe; - + if(getattributes(rule[j]->attributes,rule[j]->values, &id,&level,&maxsize,&timeframe, &frequency,&accuracy,&noalert, @@ -305,7 +306,7 @@ int Rules_OP_ReadRules(char * rulefile) OS_ClearXML(&xml); return(-1); } - + if((id == -1) || (level == -1)) { merror("%s: No rule id or level specified for " @@ -316,17 +317,17 @@ int Rules_OP_ReadRules(char * rulefile) /* Allocating memory and initializing structure */ config_ruleinfo = zerorulemember(id, level, maxsize, - frequency,timeframe, + frequency,timeframe, noalert, ignore_time, overwrite); - + /* If rule is 0, set it to level 99 to have high priority. - * set it to 0 again later + * set it to 0 again later */ if(config_ruleinfo->level == 0) config_ruleinfo->level = 99; - + /* Each level now is going to be multiplied by 100. * If the accuracy is set to 0 we don't multiply, * so it will be at the end of the list. We will @@ -344,7 +345,7 @@ int Rules_OP_ReadRules(char * rulefile) config_ruleinfo->alert_opts |= DO_EXTRAINFO; } } - + } /* end attributes/memory allocation block */ @@ -353,7 +354,7 @@ int Rules_OP_ReadRules(char * rulefile) * be fine */ os_strdup(node[i]->values[0], config_ruleinfo->group); - + /* Rule elements block */ { @@ -374,7 +375,7 @@ int Rules_OP_ReadRules(char * rulefile) char *hostname = NULL; char *extra_data = NULL; char *program_name = NULL; - + XML_NODE rule_opt = NULL; rule_opt = OS_GetElementsbyNode(&xml,rule[j]); if(rule_opt == NULL) @@ -384,9 +385,9 @@ int Rules_OP_ReadRules(char * rulefile) "other problems for the system. Exiting.", ARGV0, config_ruleinfo->sigid); OS_ClearXML(&xml); - return(-1); + return(-1); } - + while(rule_opt[k]) { if((!rule_opt[k]->element)||(!rule_opt[k]->content)) @@ -405,15 +406,15 @@ int Rules_OP_ReadRules(char * rulefile) } else if(strcasecmp(rule_opt[k]->element, xml_decoded)==0) { - config_ruleinfo->decoded_as = + config_ruleinfo->decoded_as = getDecoderfromlist(rule_opt[k]->content); - + if(config_ruleinfo->decoded_as == 0) { merror("%s: Invalid decoder name: '%s'.", ARGV0, rule_opt[k]->content); OS_ClearXML(&xml); - return(-1); + return(-1); } } else if(strcasecmp(rule_opt[k]->element,xml_cve)==0) @@ -426,7 +427,7 @@ int Rules_OP_ReadRules(char * rulefile) else { for (last_info_detail = config_ruleinfo->info_details; - last_info_detail->next != NULL; + last_info_detail->next != NULL; last_info_detail = last_info_detail->next) { count_info_detail++; @@ -453,13 +454,13 @@ int Rules_OP_ReadRules(char * rulefile) if(config_ruleinfo->info_details == NULL) { - config_ruleinfo->info_details = zeroinfodetails(info_type, + config_ruleinfo->info_details = zeroinfodetails(info_type, rule_opt[k]->content); } else { for (last_info_detail = config_ruleinfo->info_details; - last_info_detail->next != NULL; + last_info_detail->next != NULL; last_info_detail = last_info_detail->next) { count_info_detail++; } @@ -477,7 +478,7 @@ int Rules_OP_ReadRules(char * rulefile) } else if(strcasecmp(rule_opt[k]->element,xml_day_time)==0) { - config_ruleinfo->day_time = + config_ruleinfo->day_time = OS_IsValidTime(rule_opt[k]->content); if(!config_ruleinfo->day_time) { @@ -492,9 +493,9 @@ int Rules_OP_ReadRules(char * rulefile) } else if(strcasecmp(rule_opt[k]->element,xml_week_day)==0) { - config_ruleinfo->week_day = + config_ruleinfo->week_day = OS_IsValidDay(rule_opt[k]->content); - + if(!config_ruleinfo->week_day) { merror(INVALID_CONFIG, ARGV0, @@ -520,7 +521,7 @@ int Rules_OP_ReadRules(char * rulefile) { *newline = ' '; } - + config_ruleinfo->comment= loadmemory(config_ruleinfo->comment, rule_opt[k]->content); @@ -528,27 +529,27 @@ int Rules_OP_ReadRules(char * rulefile) else if(strcasecmp(rule_opt[k]->element,xml_srcip)==0) { int ip_s = 0; - + /* Getting size of source ip list */ - while(config_ruleinfo->srcip && + while(config_ruleinfo->srcip && config_ruleinfo->srcip[ip_s]) { ip_s++; } - - config_ruleinfo->srcip = + + config_ruleinfo->srcip = realloc(config_ruleinfo->srcip, (ip_s + 2) * sizeof(os_ip *)); - - + + /* Allocating memory for the individual entries */ - os_calloc(1, sizeof(os_ip), + os_calloc(1, sizeof(os_ip), config_ruleinfo->srcip[ip_s]); config_ruleinfo->srcip[ip_s +1] = NULL; - - + + /* Checking if the ip is valid */ - if(!OS_IsValidIP(rule_opt[k]->content, + if(!OS_IsValidIP(rule_opt[k]->content, config_ruleinfo->srcip[ip_s])) { merror(INVALID_IP, ARGV0, rule_opt[k]->content); @@ -628,7 +629,7 @@ int Rules_OP_ReadRules(char * rulefile) status = loadmemory(status, rule_opt[k]->content); - + if(!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) config_ruleinfo->alert_opts |= DO_EXTRAINFO; } @@ -637,7 +638,7 @@ int Rules_OP_ReadRules(char * rulefile) hostname = loadmemory(hostname, rule_opt[k]->content); - + if(!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) config_ruleinfo->alert_opts |= DO_EXTRAINFO; } @@ -659,7 +660,7 @@ int Rules_OP_ReadRules(char * rulefile) } else if(strcasecmp(rule_opt[k]->element,xml_action)==0) { - config_ruleinfo->action = + config_ruleinfo->action = loadmemory(config_ruleinfo->action, rule_opt[k]->content); } @@ -688,12 +689,12 @@ int Rules_OP_ReadRules(char * rulefile) lookup_type = LR_ADDRESS_NOT_MATCH; else if(strcasecmp(rule_opt[k]->values[list_att_num],xml_address_key_value)==0) lookup_type = LR_ADDRESS_MATCH_VALUE; - else + else { - merror(INVALID_CONFIG, ARGV0, - rule_opt[k]->element, + merror(INVALID_CONFIG, ARGV0, + rule_opt[k]->element, rule_opt[k]->content); - merror("%s: List match lookup=\"%s\" is not valid.", + merror("%s: List match lookup=\"%s\" is not valid.", ARGV0,rule_opt[k]->values[list_att_num]); return(-1); } @@ -722,12 +723,12 @@ int Rules_OP_ReadRules(char * rulefile) rule_type = RULE_STATUS; else if (strcasecmp(rule_opt[k]->values[list_att_num],xml_action)==0) rule_type = RULE_ACTION; - else + else { - merror(INVALID_CONFIG, ARGV0, - rule_opt[k]->element, + merror(INVALID_CONFIG, ARGV0, + rule_opt[k]->element, rule_opt[k]->content); - merror("%s: List match field=\"%s\" is not valid.", + merror("%s: List match field=\"%s\" is not valid.", ARGV0,rule_opt[k]->values[list_att_num]); return(-1); } @@ -737,12 +738,12 @@ int Rules_OP_ReadRules(char * rulefile) os_calloc(1, sizeof(OSMatch), matcher); if(!OSMatch_Compile(rule_opt[k]->values[list_att_num], matcher, 0)) { - merror(INVALID_CONFIG, ARGV0, - rule_opt[k]->element, + merror(INVALID_CONFIG, ARGV0, + rule_opt[k]->element, rule_opt[k]->content); - merror(REGEX_COMPILE, - ARGV0, - rule_opt[k]->values[list_att_num], + merror(REGEX_COMPILE, + ARGV0, + rule_opt[k]->values[list_att_num], matcher->error); return(-1); } @@ -751,7 +752,7 @@ int Rules_OP_ReadRules(char * rulefile) { merror("%s:List feild=\"%s\" is not valid",ARGV0, rule_opt[k]->values[list_att_num]); - merror(INVALID_CONFIG, ARGV0, + merror(INVALID_CONFIG, ARGV0, rule_opt[k]->element, rule_opt[k]->content); return(-1); } @@ -760,15 +761,15 @@ int Rules_OP_ReadRules(char * rulefile) if(rule_type == 0) { merror("%s:List requires the field=\"\" Attrubute",ARGV0); - merror(INVALID_CONFIG, ARGV0, + merror(INVALID_CONFIG, ARGV0, rule_opt[k]->element, rule_opt[k]->content); return(-1); } /* Wow it's all ready - this seams too complex to get to this point */ config_ruleinfo->lists = OS_AddListRule(config_ruleinfo->lists, - lookup_type, - rule_type, + lookup_type, + rule_type, rule_opt[k]->content, matcher); if (config_ruleinfo->lists == NULL) @@ -781,12 +782,12 @@ int Rules_OP_ReadRules(char * rulefile) { merror("%s:List must have a correctly formatted feild attribute", ARGV0); - merror(INVALID_CONFIG, - ARGV0, - rule_opt[k]->element, + merror(INVALID_CONFIG, + ARGV0, + rule_opt[k]->element, rule_opt[k]->content); return(-1); - } + } /* xml_list eval is done */ } else if(strcasecmp(rule_opt[k]->element,xml_url)==0) @@ -801,7 +802,7 @@ int Rules_OP_ReadRules(char * rulefile) while(compiled_rules_name[it_id]) { - if(strcmp(compiled_rules_name[it_id], + if(strcmp(compiled_rules_name[it_id], rule_opt[k]->content) == 0) break; it_id++; @@ -810,9 +811,9 @@ int Rules_OP_ReadRules(char * rulefile) /* checking if the name is valid. */ if(!compiled_rules_name[it_id]) { - merror("%s: ERROR: Compiled rule not found: '%s'", - ARGV0, rule_opt[k]->content); - merror(INVALID_CONFIG, ARGV0, + merror("%s: ERROR: Compiled rule not found: '%s'", + ARGV0, rule_opt[k]->content); + merror(INVALID_CONFIG, ARGV0, rule_opt[k]->element, rule_opt[k]->content); return(-1); @@ -870,9 +871,9 @@ int Rules_OP_ReadRules(char * rulefile) { if(!OS_StrIsNum(rule_opt[k]->content)) { - merror(INVALID_CONFIG, ARGV0, + merror(INVALID_CONFIG, ARGV0, "if_level", - rule_opt[k]->content); + rule_opt[k]->content); return(-1); } @@ -913,7 +914,7 @@ int Rules_OP_ReadRules(char * rulefile) rule_opt[k]->content); return(-1); } - config_ruleinfo->if_matched_sid = + config_ruleinfo->if_matched_sid = atoi(rule_opt[k]->content); } @@ -926,14 +927,14 @@ int Rules_OP_ReadRules(char * rulefile) xml_same_src_port)==0) { config_ruleinfo->context_opts|= SAME_SRCPORT; - + if(!(config_ruleinfo->alert_opts & SAME_EXTRAINFO)) config_ruleinfo->alert_opts |= SAME_EXTRAINFO; } else if(strcasecmp(rule_opt[k]->element, xml_dodiff)==0) { - config_ruleinfo->context++; + config_ruleinfo->context = 1; config_ruleinfo->context_opts|= SAME_DODIFF; if(!(config_ruleinfo->alert_opts & DO_EXTRAINFO)) config_ruleinfo->alert_opts |= DO_EXTRAINFO; @@ -942,7 +943,7 @@ int Rules_OP_ReadRules(char * rulefile) xml_same_dst_port) == 0) { config_ruleinfo->context_opts|= SAME_DSTPORT; - + if(!(config_ruleinfo->alert_opts & SAME_EXTRAINFO)) config_ruleinfo->alert_opts |= SAME_EXTRAINFO; } @@ -959,7 +960,7 @@ int Rules_OP_ReadRules(char * rulefile) xml_different_url) == 0) { config_ruleinfo->context_opts|= DIFFERENT_URL; - + if(!(config_ruleinfo->alert_opts & SAME_EXTRAINFO)) config_ruleinfo->alert_opts |= SAME_EXTRAINFO; } @@ -976,7 +977,7 @@ int Rules_OP_ReadRules(char * rulefile) xml_same_user)==0) { config_ruleinfo->context_opts|= SAME_USER; - + if(!(config_ruleinfo->alert_opts & SAME_EXTRAINFO)) config_ruleinfo->alert_opts |= SAME_EXTRAINFO; } @@ -1000,7 +1001,7 @@ int Rules_OP_ReadRules(char * rulefile) else if(strcasecmp(rule_opt[k]->element, xml_options) == 0) { - if(strcmp("alert_by_email", + if(strcmp("alert_by_email", rule_opt[k]->content) == 0) { if(!(config_ruleinfo->alert_opts & DO_MAILALERT)) @@ -1016,7 +1017,7 @@ int Rules_OP_ReadRules(char * rulefile) config_ruleinfo->alert_opts&=0xfff-DO_MAILALERT; } } - else if(strcmp("log_alert", + else if(strcmp("log_alert", rule_opt[k]->content) == 0) { if(!(config_ruleinfo->alert_opts & DO_LOGALERT)) @@ -1039,7 +1040,7 @@ int Rules_OP_ReadRules(char * rulefile) } } else - { + { merror(XML_VALUEERR, ARGV0, xml_options, rule_opt[k]->content); @@ -1048,7 +1049,7 @@ int Rules_OP_ReadRules(char * rulefile) config_ruleinfo->sigid); OS_ClearXML(&xml); return(-1); - } + } } else if(strcasecmp(rule_opt[k]->element, xml_ignore) == 0) @@ -1084,7 +1085,7 @@ int Rules_OP_ReadRules(char * rulefile) } if(!config_ruleinfo->ignore) { - merror("%s: Wrong ignore option: '%s'", + merror("%s: Wrong ignore option: '%s'", ARGV0, rule_opt[k]->content); return(-1); @@ -1124,7 +1125,7 @@ int Rules_OP_ReadRules(char * rulefile) } if(!config_ruleinfo->ckignore) { - merror("%s: Wrong check_if_ignored option: '%s'", + merror("%s: Wrong check_if_ignored option: '%s'", ARGV0, rule_opt[k]->content); return(-1); @@ -1143,7 +1144,7 @@ int Rules_OP_ReadRules(char * rulefile) /* Checking for a valid use of frequency */ - if((config_ruleinfo->context_opts || + if((config_ruleinfo->context_opts || config_ruleinfo->frequency) && !config_ruleinfo->context) { @@ -1153,42 +1154,42 @@ int Rules_OP_ReadRules(char * rulefile) OS_ClearXML(&xml); return(-1); } - + /* If if_matched_group we must have a if_sid or if_group */ if(if_matched_group) { if(!config_ruleinfo->if_sid && !config_ruleinfo->if_group) { - os_strdup(if_matched_group, - config_ruleinfo->if_group); + os_strdup(if_matched_group, + config_ruleinfo->if_group); } } /* If_matched_sid, we need to get the if_sid */ - if(config_ruleinfo->if_matched_sid && + if(config_ruleinfo->if_matched_sid && !config_ruleinfo->if_sid && !config_ruleinfo->if_group) { os_calloc(16, sizeof(char), config_ruleinfo->if_sid); - snprintf(config_ruleinfo->if_sid, 15, "%d", + snprintf(config_ruleinfo->if_sid, 15, "%d", config_ruleinfo->if_matched_sid); } - + /* Checking the regexes */ if(regex) { os_calloc(1, sizeof(OSRegex), config_ruleinfo->regex); if(!OSRegex_Compile(regex, config_ruleinfo->regex, 0)) { - merror(REGEX_COMPILE, ARGV0, regex, + merror(REGEX_COMPILE, ARGV0, regex, config_ruleinfo->regex->error); return(-1); } free(regex); regex = NULL; } - + /* Adding in match */ if(match) { @@ -1202,14 +1203,14 @@ int Rules_OP_ReadRules(char * rulefile) free(match); match = NULL; } - + /* Adding in id */ if(id) { os_calloc(1, sizeof(OSMatch), config_ruleinfo->id); if(!OSMatch_Compile(id, config_ruleinfo->id, 0)) { - merror(REGEX_COMPILE, ARGV0, id, + merror(REGEX_COMPILE, ARGV0, id, config_ruleinfo->id->error); return(-1); } @@ -1223,7 +1224,7 @@ int Rules_OP_ReadRules(char * rulefile) os_calloc(1, sizeof(OSMatch), config_ruleinfo->srcport); if(!OSMatch_Compile(srcport, config_ruleinfo->srcport, 0)) { - merror(REGEX_COMPILE, ARGV0, srcport, + merror(REGEX_COMPILE, ARGV0, srcport, config_ruleinfo->id->error); return(-1); } @@ -1237,7 +1238,7 @@ int Rules_OP_ReadRules(char * rulefile) os_calloc(1, sizeof(OSMatch), config_ruleinfo->dstport); if(!OSMatch_Compile(dstport, config_ruleinfo->dstport, 0)) { - merror(REGEX_COMPILE, ARGV0, dstport, + merror(REGEX_COMPILE, ARGV0, dstport, config_ruleinfo->id->error); return(-1); } @@ -1277,7 +1278,7 @@ int Rules_OP_ReadRules(char * rulefile) if(extra_data) { os_calloc(1, sizeof(OSMatch), config_ruleinfo->extra_data); - if(!OSMatch_Compile(extra_data, + if(!OSMatch_Compile(extra_data, config_ruleinfo->extra_data, 0)) { merror(REGEX_COMPILE, ARGV0, extra_data, @@ -1302,7 +1303,7 @@ int Rules_OP_ReadRules(char * rulefile) free(program_name); program_name = NULL; } - + /* Adding in user */ if(user) { @@ -1316,28 +1317,28 @@ int Rules_OP_ReadRules(char * rulefile) free(user); user = NULL; } - + /* Adding in url */ if(url) { os_calloc(1, sizeof(OSMatch), config_ruleinfo->url); if(!OSMatch_Compile(url, config_ruleinfo->url, 0)) { - merror(REGEX_COMPILE, ARGV0, url, + merror(REGEX_COMPILE, ARGV0, url, config_ruleinfo->url->error); return(-1); } free(url); url = NULL; } - + /* Adding matched_group */ if(if_matched_group) { - os_calloc(1, sizeof(OSMatch), + os_calloc(1, sizeof(OSMatch), config_ruleinfo->if_matched_group); - - if(!OSMatch_Compile(if_matched_group, + + if(!OSMatch_Compile(if_matched_group, config_ruleinfo->if_matched_group, 0)) { @@ -1348,16 +1349,16 @@ int Rules_OP_ReadRules(char * rulefile) free(if_matched_group); if_matched_group = NULL; } - + /* Adding matched_regex */ if(if_matched_regex) { - os_calloc(1, sizeof(OSRegex), + os_calloc(1, sizeof(OSRegex), config_ruleinfo->if_matched_regex); - if(!OSRegex_Compile(if_matched_regex, + if(!OSRegex_Compile(if_matched_regex, config_ruleinfo->if_matched_regex, 0)) { - merror(REGEX_COMPILE, ARGV0, if_matched_regex, + merror(REGEX_COMPILE, ARGV0, if_matched_regex, config_ruleinfo->if_matched_regex->error); return(-1); } @@ -1377,9 +1378,9 @@ int Rules_OP_ReadRules(char * rulefile) if(config_ruleinfo->context) { int ii = 0; - os_calloc(MAX_LAST_EVENTS + 1, sizeof(char *), + os_calloc(MAX_LAST_EVENTS + 1, sizeof(char *), config_ruleinfo->last_events); - + /* Zeroing each entry */ for(;ii<=MAX_LAST_EVENTS;ii++) { @@ -1387,19 +1388,19 @@ int Rules_OP_ReadRules(char * rulefile) } } - + /* Adding the rule to the rules list. * Only the template rules are supposed * to be at the top level. All others * will be a "child" of someone. */ if(config_ruleinfo->sigid < 10) - { + { OS_AddRule(config_ruleinfo); } else if(config_ruleinfo->alert_opts & DO_OVERWRITE) { - if(!OS_AddRuleInfo(NULL, config_ruleinfo, + if(!OS_AddRuleInfo(NULL, config_ruleinfo, config_ruleinfo->sigid)) { merror("%s: Overwrite rule '%d' not found.", @@ -1423,13 +1424,13 @@ int Rules_OP_ReadRules(char * rulefile) /* Setting the event_search pointer */ if(config_ruleinfo->if_matched_sid) { - config_ruleinfo->event_search = + config_ruleinfo->event_search = (void *)Search_LastSids; - + /* Marking rules that match this id */ - OS_MarkID(NULL, config_ruleinfo); + OS_MarkID(NULL, config_ruleinfo); } - + /* Marking the rules that match if_matched_group */ else if(config_ruleinfo->if_matched_group) { @@ -1444,19 +1445,19 @@ int Rules_OP_ReadRules(char * rulefile) OS_MarkGroup(NULL, config_ruleinfo); /* Setting function pointer */ - config_ruleinfo->event_search = + config_ruleinfo->event_search = (void *)Search_LastGroups; } else if(config_ruleinfo->context) { - if((config_ruleinfo->context == 1) && + if((config_ruleinfo->context == 1) && (config_ruleinfo->context_opts & SAME_DODIFF)) { config_ruleinfo->context = 0; } else { - config_ruleinfo->event_search = + config_ruleinfo->event_search = (void *)Search_LastEvents; } } @@ -1464,7 +1465,7 @@ int Rules_OP_ReadRules(char * rulefile) } /* while(rule[j]) */ OS_ClearNode(rule); i++; - + } /* while (node[i]) */ /* Cleaning global node */ @@ -1529,25 +1530,25 @@ char *loadmemory(char *at, char *str) int strsize = strlen(str); int atsize = strlen(at); int finalsize = atsize+strsize+1; - + if((atsize > OS_SIZE_2048) || (strsize > OS_SIZE_2048)) { merror(SIZE_ERROR,ARGV0,str); return(NULL); } - + at = realloc(at, (finalsize)*sizeof(char)); - + if(at == NULL) { merror(MEM_ERROR,ARGV0); return(NULL); } - + strncat(at,str,strsize); - + at[finalsize-1]='\0'; - + return(at); } return(NULL); @@ -1571,19 +1572,19 @@ RuleInfoDetail *zeroinfodetails(int type, char *data) os_strdup(data, info_details_pt->data); info_details_pt->next = NULL; - + return(info_details_pt); } -RuleInfo *zerorulemember(int id, int level, +RuleInfo *zerorulemember(int id, int level, int maxsize, int frequency, - int timeframe, int noalert, + int timeframe, int noalert, int ignore_time, int overwrite) { RuleInfo *ruleinfo_pt = NULL; - + /* Allocation memory for structure */ ruleinfo_pt = (RuleInfo *)calloc(1,sizeof(RuleInfo)); @@ -1591,17 +1592,17 @@ RuleInfo *zerorulemember(int id, int level, { ErrorExit(MEM_ERROR,ARGV0); } - + /* Default values */ ruleinfo_pt->level = level; /* Default category is syslog */ ruleinfo_pt->category = SYSLOG; - ruleinfo_pt->ar = NULL; - + ruleinfo_pt->ar = NULL; + ruleinfo_pt->context = 0; - + ruleinfo_pt->sigid = id; ruleinfo_pt->firedtimes = 0; ruleinfo_pt->maxsize = maxsize; @@ -1613,11 +1614,11 @@ RuleInfo *zerorulemember(int id, int level, ruleinfo_pt->ignore_time = ignore_time; ruleinfo_pt->timeframe = timeframe; ruleinfo_pt->time_ignored = 0; - - ruleinfo_pt->context_opts = 0; - ruleinfo_pt->alert_opts = 0; - ruleinfo_pt->ignore = 0; - ruleinfo_pt->ckignore = 0; + + ruleinfo_pt->context_opts = 0; + ruleinfo_pt->alert_opts = 0; + ruleinfo_pt->ignore = 0; + ruleinfo_pt->ckignore = 0; if(noalert) { @@ -1625,7 +1626,7 @@ RuleInfo *zerorulemember(int id, int level, } if(Config.mailbylevel <= level) ruleinfo_pt->alert_opts |= DO_MAILALERT; - if(Config.logbylevel <= level) + if(Config.logbylevel <= level) ruleinfo_pt->alert_opts |= DO_LOGALERT; /* Overwriting a rule */ @@ -1646,16 +1647,16 @@ RuleInfo *zerorulemember(int id, int level, ruleinfo_pt->info = NULL; ruleinfo_pt->cve = NULL; ruleinfo_pt->info_details = NULL; - + ruleinfo_pt->if_sid = NULL; ruleinfo_pt->if_group = NULL; ruleinfo_pt->if_level = NULL; - + ruleinfo_pt->if_matched_regex = NULL; ruleinfo_pt->if_matched_group = NULL; ruleinfo_pt->if_matched_sid = 0; - - ruleinfo_pt->user = NULL; + + ruleinfo_pt->user = NULL; ruleinfo_pt->srcip = NULL; ruleinfo_pt->srcport = NULL; ruleinfo_pt->dstip = NULL; @@ -1666,7 +1667,7 @@ RuleInfo *zerorulemember(int id, int level, ruleinfo_pt->hostname = NULL; ruleinfo_pt->program_name = NULL; ruleinfo_pt->action = NULL; - + /* Zeroing last matched events */ ruleinfo_pt->__frequency = 0; ruleinfo_pt->last_events = NULL; @@ -1674,10 +1675,10 @@ RuleInfo *zerorulemember(int id, int level, /* zeroing the list of previous matches */ ruleinfo_pt->sid_prev_matched = NULL; ruleinfo_pt->group_prev_matched = NULL; - + ruleinfo_pt->sid_search = NULL; ruleinfo_pt->group_search = NULL; - + ruleinfo_pt->event_search = NULL; ruleinfo_pt->compiled_rule = NULL; ruleinfo_pt->lists = NULL; @@ -1696,7 +1697,7 @@ int get_info_attributes(char **attributes, char **values) { if (!values[k]) { - merror("rules_op: Entry info type \"%s\" does not have a value", + merror("rules_op: Entry info type \"%s\" does not have a value", attributes[k]); return (-1); } @@ -1705,7 +1706,7 @@ int get_info_attributes(char **attributes, char **values) if(strcmp(values[k], "text") == 0) { return(RULEINFODETAIL_TEXT); - } + } else if(strcmp(values[k], "link") == 0) { return(RULEINFODETAIL_LINK); @@ -1725,13 +1726,13 @@ int get_info_attributes(char **attributes, char **values) /* Get the attributes */ int getattributes(char **attributes, char **values, - int *id, int *level, + int *id, int *level, int *maxsize, int *timeframe, - int *frequency, int *accuracy, + int *frequency, int *accuracy, int *noalert, int *ignore_time, int *overwrite) { int k=0; - + char *xml_id = "id"; char *xml_level = "level"; char *xml_maxsize = "maxsize"; @@ -1741,8 +1742,8 @@ int getattributes(char **attributes, char **values, char *xml_noalert = "noalert"; char *xml_ignore_time = "ignore"; char *xml_overwrite = "overwrite"; - - + + /* Getting attributes */ while(attributes[k]) { @@ -1839,7 +1840,7 @@ int getattributes(char **attributes, char **values, merror("rules_op: Invalid accuracy: %s. " "Must be integer" , values[k]); - return(-1); + return(-1); } } /* Rule ignore_time */ @@ -1854,7 +1855,7 @@ int getattributes(char **attributes, char **values, merror("rules_op: Invalid ignore_time: %s. " "Must be integer" , values[k]); - return(-1); + return(-1); } } /* Rule noalert */ @@ -1900,22 +1901,22 @@ void Rule_AddAR(RuleInfo *rule_config) int rule_ar_size = 0; int mark_to_ar = 0; int rule_real_level = 0; - + OSListNode *my_ars_node; - - - /* Setting the correctly levels + + + /* Setting the correctly levels * We play internally with the rules, to set * the priorities... Rules with 0 of accuracy, * receive a low level and go down in the list */ if(rule_config->level == 9900) rule_real_level = 0; - + else if(rule_config->level >= 100) rule_real_level = rule_config->level/100; - - + + /* No AR for ignored rules */ if(rule_real_level == 0) { @@ -1932,7 +1933,7 @@ void Rule_AddAR(RuleInfo *rule_config) { return; } - + /* Looping on all AR */ my_ars_node = OSList_GetFirstNode(active_responses); while(my_ars_node) @@ -1951,7 +1952,7 @@ void Rule_AddAR(RuleInfo *rule_config) mark_to_ar = 1; } } - + /* Checking if group matches */ if(my_ar->rules_group) { @@ -1960,7 +1961,7 @@ void Rule_AddAR(RuleInfo *rule_config) mark_to_ar = 1; } } - + /* Checking if rule id matches */ if(my_ar->rules_id) { @@ -1983,13 +1984,13 @@ void Rule_AddAR(RuleInfo *rule_config) else if(isdigit((int)*str_pt)) { r_id = atoi(str_pt); - + /* mark to ar if id matches */ if(r_id == rule_config->sigid) { mark_to_ar = 1; } - + str_pt = strchr(str_pt, ','); if(str_pt) { @@ -2014,9 +2015,9 @@ void Rule_AddAR(RuleInfo *rule_config) } } } /* eof of rules_id */ - - - /* Bind AR to the rule */ + + + /* Bind AR to the rule */ if(mark_to_ar == 1) { rule_ar_size++; @@ -2024,12 +2025,12 @@ void Rule_AddAR(RuleInfo *rule_config) rule_config->ar = realloc(rule_config->ar, (rule_ar_size + 1) *sizeof(active_response *)); - + /* Always set the last node to NULL */ rule_config->ar[rule_ar_size - 1] = my_ar; - rule_config->ar[rule_ar_size] = NULL; + rule_config->ar[rule_ar_size] = NULL; } - + my_ars_node = OSList_GetNextNode(active_responses); } @@ -2040,9 +2041,9 @@ void Rule_AddAR(RuleInfo *rule_config) /* print rule */ void printRuleinfo(RuleInfo *rule, int node) { - debug1("%d : rule:%d, level %d, timeout: %d", + debug1("%d : rule:%d, level %d, timeout: %d", node, - rule->sigid, + rule->sigid, rule->level, rule->ignore_time); } @@ -2059,8 +2060,8 @@ int AddHash_Rule(RuleNode *node) snprintf(_id_key, 14, "%d", node->ruleinfo->sigid); os_strdup(_id_key, id_key); - - + + /* Adding key to hash. */ OSHash_Add(Config.g_rules_hash, id_key, node->ruleinfo); if(node->child) @@ -2089,10 +2090,10 @@ int _setlevels(RuleNode *node, int nnode) node->ruleinfo->level/=100; l_size++; - + /* Rule information */ printRuleinfo(node->ruleinfo, nnode); - + if(node->child) { int chl_size = 0; diff --git a/src/analysisd/rules.h b/src/analysisd/rules.h index 0f77df4..03204cf 100755 --- a/src/analysisd/rules.h +++ b/src/analysisd/rules.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/rules.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -94,7 +95,7 @@ typedef struct _RuleInfo int __frequency; char **last_events; - + /* Not an option in the rule */ u_int16_t alert_opts; @@ -104,7 +105,7 @@ typedef struct _RuleInfo /* category */ u_int8_t category; - + /* Decoded as */ u_int16_t decoded_as; @@ -126,7 +127,7 @@ typedef struct _RuleInfo /* Function pointer to the event_search. */ void *(*event_search)(void *lf, void *rule); - + char *group; OSMatch *match; @@ -148,13 +149,13 @@ typedef struct _RuleInfo OSMatch *program_name; OSMatch *extra_data; char *action; - + char *comment; /* description in the xml */ char *info; char *cve; RuleInfoDetail *info_details; ListRule *lists; - + char *if_sid; char *if_level; char *if_group; @@ -162,7 +163,7 @@ typedef struct _RuleInfo OSRegex *if_matched_regex; OSMatch *if_matched_group; int if_matched_sid; - + void *(*compiled_rule)(void *lf); active_response **ar; @@ -183,11 +184,11 @@ RuleInfoDetail *zeroinfodetails(int type, char *data); int get_info_attributes(char **attributes, char **values); /* RuleInfo functions */ -RuleInfo *zerorulemember(int id, +RuleInfo *zerorulemember(int id, int level, - int maxsize, + int maxsize, int frequency, - int timeframe, + int timeframe, int noalert, int ignore_time, int overwrite); @@ -221,10 +222,10 @@ RuleNode *OS_GetFirstRule(); /** Defition of the internal rule IDS ** ** These SIGIDs cannot be used ** ** **/ - + #define STATS_MODULE 11 #define FTS_MODULE 12 -#define SYSCHECK_MODULE 13 +#define SYSCHECK_MODULE 13 #define HOSTINFO_MODULE 15 diff --git a/src/analysisd/rules_list.c b/src/analysisd/rules_list.c index c8613fa..3e4a335 100755 --- a/src/analysisd/rules_list.c +++ b/src/analysisd/rules_list.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/rules_list.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -9,7 +10,7 @@ * Foundation */ - + #include "shared.h" #include "rules.h" @@ -33,17 +34,17 @@ void OS_CreateRuleList() RuleNode *OS_GetFirstRule() { RuleNode *rulenode_pt = rulenode; - - return(rulenode_pt); + + return(rulenode_pt); } /* Search all rules, including childs */ -int _AddtoRule(int sid, int level, int none, char *group, +int _AddtoRule(int sid, int level, int none, char *group, RuleNode *r_node, RuleInfo *read_rule) { int r_code = 0; - + /* If we don't have the first node, start from * the beginning of the list */ @@ -56,14 +57,14 @@ int _AddtoRule(int sid, int level, int none, char *group, { /* Checking if the sigid matches */ if(sid) - { + { if(r_node->ruleinfo->sigid == sid) { - /* Assign the category of this rule to the child + /* Assign the category of this rule to the child * as they must match */ read_rule->category = r_node->ruleinfo->category; - + /* If no context for rule, check if the parent has * and use it. @@ -72,17 +73,17 @@ int _AddtoRule(int sid, int level, int none, char *group, { read_rule->last_events = r_node->ruleinfo->last_events; } - + r_node->child= _OS_AddRule(r_node->child, read_rule); return(1); } } - + /* Checking if the group matches */ else if(group) { - if(OS_WordMatch(group, r_node->ruleinfo->group) && + if(OS_WordMatch(group, r_node->ruleinfo->group) && (r_node->ruleinfo->sigid != read_rule->sigid)) { /* If no context for rule, check if the parent has @@ -103,7 +104,7 @@ int _AddtoRule(int sid, int level, int none, char *group, /* Checking if the level matches */ else if(level) { - if((r_node->ruleinfo->level >= level) && + if((r_node->ruleinfo->level >= level) && (r_node->ruleinfo->sigid != read_rule->sigid)) { r_node->child= @@ -111,10 +112,10 @@ int _AddtoRule(int sid, int level, int none, char *group, r_code = 1; } } - - + + /* If we are not searching for the sid/group, the category must - * be the same. + * be the same. */ else if(read_rule->category != r_node->ruleinfo->category) { @@ -122,7 +123,7 @@ int _AddtoRule(int sid, int level, int none, char *group, continue; } - + /* If none of them is set, add for the category */ else { @@ -144,8 +145,8 @@ int _AddtoRule(int sid, int level, int none, char *group, r_node = r_node->next; } - - return(r_code); + + return(r_code); } @@ -158,14 +159,14 @@ int OS_AddChild(RuleInfo *read_rule) return(1); } - /* Adding for if_sid */ + /* Adding for if_sid */ if(read_rule->if_sid) { int val = 0; char *sid; - + sid = read_rule->if_sid; - + /* Loop to read all the rules (comma or space separated */ do { @@ -217,7 +218,7 @@ int OS_AddChild(RuleInfo *read_rule) } } - /* Adding for if_group */ + /* Adding for if_group */ else if(read_rule->if_group) { if(!_AddtoRule(0, 0, 0, read_rule->if_group, NULL, read_rule)) @@ -226,7 +227,7 @@ int OS_AddChild(RuleInfo *read_rule) "found. Invalid 'if_group'.", read_rule->if_group); } } - + /* Just add based on the category */ else { @@ -247,14 +248,14 @@ int OS_AddChild(RuleInfo *read_rule) RuleNode *_OS_AddRule(RuleNode *_rulenode, RuleInfo *read_rule) { RuleNode *tmp_rulenode = _rulenode; - + if(tmp_rulenode != NULL) { int middle_insertion = 0; RuleNode *prev_rulenode = NULL; RuleNode *new_rulenode = NULL; - + while(tmp_rulenode != NULL) { if(read_rule->level > tmp_rulenode->ruleinfo->level) @@ -265,7 +266,7 @@ RuleNode *_OS_AddRule(RuleNode *_rulenode, RuleInfo *read_rule) prev_rulenode = tmp_rulenode; tmp_rulenode = tmp_rulenode->next; } - + new_rulenode = (RuleNode *)calloc(1,sizeof(RuleNode)); if(!new_rulenode) @@ -283,21 +284,21 @@ RuleNode *_OS_AddRule(RuleNode *_rulenode, RuleInfo *read_rule) { prev_rulenode->next = new_rulenode; } - + new_rulenode->next = tmp_rulenode; new_rulenode->ruleinfo = read_rule; new_rulenode->child = NULL; } - + else { prev_rulenode->next = new_rulenode; prev_rulenode->next->ruleinfo = read_rule; - prev_rulenode->next->next = NULL; - prev_rulenode->next->child = NULL; + prev_rulenode->next->next = NULL; + prev_rulenode->next->child = NULL; } } - + else { _rulenode = (RuleNode *)calloc(1,sizeof(RuleNode)); @@ -375,6 +376,10 @@ int OS_AddRuleInfo(RuleNode *r_node, RuleInfo *newrule, int sid) r_node->ruleinfo->decoded_as = newrule->decoded_as; r_node->ruleinfo->ar = newrule->ar; r_node->ruleinfo->compiled_rule = newrule->compiled_rule; + if((newrule->context_opts & SAME_DODIFF) && r_node->ruleinfo->last_events == NULL) + { + r_node->ruleinfo->last_events = newrule->last_events; + } return(1); } @@ -449,7 +454,7 @@ int OS_MarkGroup(RuleNode *r_node, RuleInfo *orig_rule) while(r_node) { - if(OSMatch_Execute(r_node->ruleinfo->group, + if(OSMatch_Execute(r_node->ruleinfo->group, strlen(r_node->ruleinfo->group), orig_rule->if_matched_group)) { @@ -461,18 +466,18 @@ int OS_MarkGroup(RuleNode *r_node, RuleInfo *orig_rule) rule_g++; } } - - os_realloc(r_node->ruleinfo->group_prev_matched, + + os_realloc(r_node->ruleinfo->group_prev_matched, (rule_g + 2)*sizeof(OSList *), - r_node->ruleinfo->group_prev_matched); - + r_node->ruleinfo->group_prev_matched); + r_node->ruleinfo->group_prev_matched[rule_g] = NULL; r_node->ruleinfo->group_prev_matched[rule_g +1] = NULL; - + /* Setting the size */ r_node->ruleinfo->group_prev_matched_sz = rule_g +1; - - r_node->ruleinfo->group_prev_matched[rule_g] = + + r_node->ruleinfo->group_prev_matched[rule_g] = orig_rule->group_search; } diff --git a/src/analysisd/stats.c b/src/analysisd/stats.c index 2e2420a..764b5ed 100755 --- a/src/analysisd/stats.c +++ b/src/analysisd/stats.c @@ -1,5 +1,6 @@ -/* @(#) $Id$ */ - +/* @(#) $Id: ./src/analysisd/stats.c, 2011/09/08 dcid Exp $ + */ + /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * @@ -28,7 +29,7 @@ char *(weekdays[])={"Sunday","Monday","Tuesday","Wednesday","Thursday", "Friday","Saturday"}; char *(l_month[])={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug", "Sep","Oct","Nov","Dec"}; - + /* Global vars */ @@ -62,7 +63,7 @@ void print_totals() char logfile[OS_FLSIZE +1]; FILE *flog; - + /* Creating the path for the logs */ snprintf(logfile, OS_FLSIZE,"%s/%d/", STATSAVED, prev_year); if(IsDir(logfile) == -1) @@ -96,7 +97,7 @@ void print_totals() merror(FOPEN_ERROR, ARGV0, logfile); return; } - + /* Printing the hourly stats */ for(i=0;i<=23;i++) { @@ -104,7 +105,7 @@ void print_totals() totals+=_CHour[i]; } fprintf(flog,"Total events for day:%d\n", totals); - + fclose(flog); } @@ -112,7 +113,7 @@ void print_totals() /* gethour: v0.2 * Return the parameter (event_number + 20 % of it) * If event_number < mindiff, return mindiff - * If event_number > maxdiff, return maxdiff + * If event_number > maxdiff, return maxdiff */ int gethour(int event_number) { @@ -121,12 +122,12 @@ int gethour(int event_number) event_diff = (event_number * percent_diff)/100; event_diff++; - + if(event_diff < mindiff) return(event_number + mindiff); else if(event_diff > maxdiff) return(event_number + maxdiff); - + return(event_number + event_diff); } @@ -136,24 +137,24 @@ void Update_Hour() { int i,j; int inter; - - + + /* Print total number of logs received per hour */ print_totals(); - - + + /* Hourly update */ _RHour[24]++; inter = _RHour[24]; if(inter > 7) inter = 7; - + for(i=0;i<=24;i++) { char _hourly[128]; /* _hourly file */ - + FILE *fp; - + if(i != 24) { /* If saved hourly = 0, just copy the current hourly rate */ @@ -170,7 +171,7 @@ void Update_Hour() { _RHour[i]=(((3*_CHour[i])+(inter*_RHour[i]))/(inter+3))+25; } - + else { /* The average is going to be the number of interactions + @@ -179,7 +180,7 @@ void Update_Hour() } } } - + snprintf(_hourly,128,"%s/%d",STATQUEUE,i); fp = fopen(_hourly, "w"); if(fp) @@ -192,7 +193,7 @@ void Update_Hour() { merror(FOPEN_ERROR, "logstats", _hourly); } - + _CHour[i] = 0; /* Zeroing the currently hour */ } @@ -206,7 +207,7 @@ void Update_Hour() inter = _CWHour[i][24]; if(inter > 7) inter = 7; - + for(j=0;j<=24;j++) { if(j != 24) @@ -229,7 +230,7 @@ void Update_Hour() } } } - + snprintf(_weekly,128,"%s/%d/%d",STATWQUEUE,i,j); fp = fopen(_weekly, "w"); if(fp) @@ -241,9 +242,9 @@ void Update_Hour() { merror(FOPEN_ERROR, "logstats", _weekly); } - + _CWHour[i][j] = 0; - } + } } _daily_errors = 0; @@ -286,8 +287,8 @@ int Check_Hour(Eventinfo *lf) " between %d:00 and %d:00 is %d. We " "reached %d.",__crt_hour,__crt_hour+1, _RHour[__crt_hour],_CHour[__crt_hour]); - - + + _fired = 1; _daily_errors++; return(1); @@ -299,13 +300,13 @@ int Check_Hour(Eventinfo *lf) /* We need to have at least 3 days of stats */ if(_RWHour[__crt_wday][24] <= 2) return(0); - + /* checking for the hour during a specific day of the week */ if(_RWHour[__crt_wday][__crt_hour] != 0) { if(_CWHour[__crt_wday][__crt_hour] > _RWHour[__crt_wday][__crt_hour]) { - if(_CWHour[__crt_wday][__crt_hour] > + if(_CWHour[__crt_wday][__crt_hour] > gethour(_RWHour[__crt_wday][__crt_hour])) { snprintf(__stats_comment, 191, @@ -315,8 +316,8 @@ int Check_Hour(Eventinfo *lf) weekdays[__crt_wday], _RWHour[__crt_wday][__crt_hour], _CWHour[__crt_wday][__crt_hour]); - - + + _fired = 1; _daily_errors++; return(1); @@ -354,7 +355,7 @@ int Start_Hour() maxdiff = getDefine_Int("analysisd", "stats_maxdiff", 10, 99999); - + mindiff = getDefine_Int("analysisd", "stats_mindiff", 10, 99999); @@ -371,22 +372,22 @@ int Start_Hour() _lastmsg = NULL; _prevlast = NULL; _pprevlast = NULL; - - + + /* They should not be null */ os_strdup(" ", _lastmsg); os_strdup(" ", _prevlast); os_strdup(" ", _pprevlast); - - - /* Creating the stat queue directories */ + + + /* Creating the stat queue directories */ if(IsDir(STATWQUEUE) == -1) if(mkdir(STATWQUEUE,0770) == -1) { merror("%s: logstat: Unable to create stat queue: %s", ARGV0, STATWQUEUE); return(-1); - } + } if(IsDir(STATQUEUE) == -1) if(mkdir(STATQUEUE,0770) == -1) @@ -394,7 +395,7 @@ int Start_Hour() merror("%s: logstat: Unable to create stat queue: %s", ARGV0, STATQUEUE); return(-1); - } + } /* Creating store dir */ if(IsDir(STATSAVED) == -1) @@ -414,7 +415,7 @@ int Start_Hour() _CHour[i]=0; if(File_DateofChange(_hourly) < 0) _RHour[i] = 0; - + else { FILE *fp; @@ -427,7 +428,7 @@ int Start_Hour() _RHour[i] = 0; if(_RHour[i] < 0) - _RHour[i] = 0; + _RHour[i] = 0; fclose(fp); } } @@ -464,7 +465,7 @@ int Start_Hour() _RWHour[i][j] = 0; if(_RWHour[i][j] < 0) - _RWHour[i][j] = 0; + _RWHour[i][j] = 0; fclose(fp); } } @@ -496,7 +497,7 @@ int LastMsg_Stats(char *log) /* LastMsg_Change: v0.3: 2006/03/21 * v0.3: 2006/03/21: Some performance fixes. - * v0.2: 2005/03/17 + * v0.2: 2005/03/17 * If the message is not repeated, rearrange the last * received messages */ @@ -504,12 +505,12 @@ void LastMsg_Change(char *log) { /* Removing the last one */ free(_pprevlast); - + /* Moving the second to third and the last to second */ _pprevlast = _prevlast; - + _prevlast = _lastmsg; - + os_strdup(log, _lastmsg); return; diff --git a/src/analysisd/testrule.c b/src/analysisd/testrule.c index c36d8ec..d2f5b25 100755 --- a/src/analysisd/testrule.c +++ b/src/analysisd/testrule.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/analysisd/testrule.c, 2012/07/23 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -16,7 +17,7 @@ /* Part of the OSSEC * Available at http://www.ossec.net */ - + /* ossec-analysisd. * Responsible for correlation and log decoding. @@ -92,6 +93,28 @@ int ReadDecodeXML(char *file); int SetDecodeXML(); +void logtest_help(const char *prog) +{ + print_out(" "); + print_out("%s %s - %s (%s)", __name, __version, __author, __contact); + print_out("%s", __site); + print_out(" "); + print_out(" %s: -[Vatfdh] [-U ut_str] [-u user] [-g group] [-c config] [-D dir]", prog); + print_out(" -V Version and license message"); + print_out(" -a Alerts output"); + print_out(" -t Test configuration"); + print_out(" -v Verbose (full) output/rule debugging"); + print_out(" -d Execute in debug mode"); + print_out(" -h This help message"); + print_out(" -U Unit test. Refer to contrib/ossec-testing/runtests.py"); + print_out(" -u Run as 'user'"); + print_out(" -g Run as 'group'"); + print_out(" -c Read the 'config' file"); + print_out(" -D Chroot to 'dir'"); + print_out(" "); + exit(1); +} + /** int main(int argc, char **argv) @@ -100,7 +123,7 @@ int main(int argc, char **argv) { int t_config = 0; int c = 0, m_queue = 0; - char *ut_str = NULL; + char *ut_str = NULL; char *dir = DEFAULTDIR; char *user = USER; @@ -120,7 +143,7 @@ int main(int argc, char **argv) active_responses = NULL; memset(prev_month, '\0', 4); - while((c = getopt(argc, argv, "VatfdhU:u:g:D:c:")) != -1){ + while((c = getopt(argc, argv, "VatvdhU:u:g:D:c:")) != -1){ switch(c){ case 'V': print_version(); @@ -129,7 +152,7 @@ int main(int argc, char **argv) t_config = 1; break; case 'h': - help(ARGV0); + logtest_help(ARGV0); break; case 'd': nowDebug(); @@ -153,6 +176,7 @@ int main(int argc, char **argv) if(!optarg) ErrorExit("%s: -D needs an argument",ARGV0); dir = optarg; + break; case 'c': if(!optarg) ErrorExit("%s: -c needs an argument",ARGV0); @@ -160,12 +184,12 @@ int main(int argc, char **argv) break; case 'a': alert_only = 1; - break; - case 'f': - full_output = 1; + break; + case 'v': + full_output = 1; break; default: - help(ARGV0); + logtest_help(ARGV0); break; } @@ -181,14 +205,14 @@ int main(int argc, char **argv) } debug1(READ_CONFIG, ARGV0); - - + + /* Getting servers hostname */ memset(__shost, '\0', 512); if(gethostname(__shost, 512 -1) != 0) { - strncpy(__shost, OSSEC_SERVER, 512 -1); + strncpy(__shost, OSSEC_SERVER, 512 -1); } else { @@ -199,7 +223,7 @@ int main(int argc, char **argv) if(_ltmp) *_ltmp = '\0'; } - + if(chdir(dir) != 0) @@ -207,18 +231,18 @@ int main(int argc, char **argv) /* - * Anonymous Section: Load rules, decoders, and lists + * Anonymous Section: Load rules, decoders, and lists * * As lists require two pass loading of rules that make use of list lookups - * are created with blank database structs, and need to be filled in after - * completion of all rules and lists. + * are created with blank database structs, and need to be filled in after + * completion of all rules and lists. */ { { /* Lad decders */ /* Initializing the decoders list */ OS_CreateOSDecoderList(); - if(!Config.decoders) + if(!Config.decoders) { /* Legacy loading */ /* Reading decoders */ if(!ReadDecodeXML("etc/decoder.xml")) @@ -248,9 +272,9 @@ int main(int argc, char **argv) verbose("%s: INFO: Reading decoder file %s.", ARGV0, *decodersfiles); if(!ReadDecodeXML(*decodersfiles)) ErrorExit(CONFIG_ERROR, ARGV0, *decodersfiles); - - free(*decodersfiles); - decodersfiles++; + + free(*decodersfiles); + decodersfiles++; } } @@ -259,14 +283,14 @@ int main(int argc, char **argv) } { /* Load Lists */ /* Initializing the lists of list struct */ - Lists_OP_CreateLists(); + Lists_OP_CreateLists(); /* Load each list into list struct */ { char **listfiles; listfiles = Config.lists; while(listfiles && *listfiles) { - verbose("%s: INFO: Reading loading the lists file: '%s'", ARGV0, *listfiles); + verbose("%s: INFO: Reading the lists file: '%s'", ARGV0, *listfiles); if(Lists_OP_LoadList(*listfiles) < 0) ErrorExit(LISTS_ERROR, ARGV0, *listfiles); free(*listfiles); @@ -289,31 +313,31 @@ int main(int argc, char **argv) debug1("%s: INFO: Reading rules file: '%s'", ARGV0, *rulesfiles); if(Rules_OP_ReadRules(*rulesfiles) < 0) ErrorExit(RULES_ERROR, ARGV0, *rulesfiles); - - free(*rulesfiles); - rulesfiles++; + + free(*rulesfiles); + rulesfiles++; } free(Config.includes); Config.includes = NULL; } - + /* Find all rules with that require list lookups and attache the - * the correct list struct to the rule. This keeps rules from having to + * the correct list struct to the rule. This keeps rules from having to * search thought the list of lists for the correct file during rule evaluation. */ OS_ListLoadRules(); } } - + /* Fixing the levels/accuracy */ { int total_rules; RuleNode *tmp_node = OS_GetFirstRule(); total_rules = _setlevels(tmp_node, 0); - debug1("%s: INFO: Total rules enabled: '%d'", ARGV0, total_rules); + debug1("%s: INFO: Total rules enabled: '%d'", ARGV0, total_rules); } @@ -334,7 +358,7 @@ int main(int argc, char **argv) exit(0); } - + /* Start up message */ verbose(STARTUP_MSG, ARGV0, getpid()); @@ -344,7 +368,7 @@ int main(int argc, char **argv) exit(0); - + } @@ -360,12 +384,12 @@ void OS_ReadMSG(int m_queue, char *ut_str) int exit_code = 0; char *ut_alertlevel = NULL; char *ut_rulelevel = NULL; - char *ut_decoder_name = NULL; + char *ut_decoder_name = NULL; if(ut_str) { /* XXX Break apart string */ - ut_rulelevel = ut_str; + ut_rulelevel = ut_str; ut_alertlevel = strchr(ut_rulelevel, ':'); if(!ut_alertlevel) { @@ -375,7 +399,7 @@ void OS_ReadMSG(int m_queue, char *ut_str) else { *ut_alertlevel = '\0'; - ut_alertlevel++; + ut_alertlevel++; } ut_decoder_name = strchr(ut_alertlevel, ':'); if(!ut_decoder_name) @@ -407,7 +431,7 @@ void OS_ReadMSG(int m_queue, char *ut_str) { ErrorExit(FTS_LIST_ERROR, ARGV0); } - + __crt_ftell = 1; @@ -418,17 +442,17 @@ void OS_ReadMSG(int m_queue, char *ut_str) /* Doing some cleanup */ memset(msg, '\0', OS_MAXSTR +1); - + if(!alert_only) print_out("%s: Type one log per line.\n", ARGV0); - - + + /* Daemon loop */ while(1) { lf = (Eventinfo *)calloc(1,sizeof(Eventinfo)); - + /* This shouldn't happen .. */ if(lf == NULL) { @@ -438,9 +462,9 @@ void OS_ReadMSG(int m_queue, char *ut_str) /* Fixing the msg. */ snprintf(msg, 15, "1:stdin:"); - - - + + + /* Receive message from queue */ if(fgets(msg +8, OS_MAXSTR, stdin)) { @@ -460,10 +484,10 @@ void OS_ReadMSG(int m_queue, char *ut_str) { continue; } - - + + if(!alert_only)print_out("\n"); - + /* Default values for the log info */ Zero_Eventinfo(lf); @@ -492,17 +516,17 @@ void OS_ReadMSG(int m_queue, char *ut_str) /* Decoding event. */ DecodeEvent(lf); - + /* Looping all the rules */ rulenode_pt = OS_GetFirstRule(); - if(!rulenode_pt) + if(!rulenode_pt) { ErrorExit("%s: Rules in an inconsistent state. Exiting.", ARGV0); } - + #ifdef TESTRULE if(full_output && !alert_only) print_out("\n**Rule debugging:"); @@ -521,9 +545,9 @@ void OS_ReadMSG(int m_queue, char *ut_str) /* We go ahead in here and process the alert. */ currently_rule = lf->generated_rule; } - + /* The categories must match */ - else if(rulenode_pt->ruleinfo->category != + else if(rulenode_pt->ruleinfo->category != lf->decoder_info->type) { continue; @@ -531,7 +555,7 @@ void OS_ReadMSG(int m_queue, char *ut_str) /* Checking each rule. */ - else if((currently_rule = OS_CheckIfRuleMatch(lf, rulenode_pt)) + else if((currently_rule = OS_CheckIfRuleMatch(lf, rulenode_pt)) == NULL) { continue; @@ -545,13 +569,13 @@ void OS_ReadMSG(int m_queue, char *ut_str) print_out(" Rule id: '%d'", currently_rule->sigid); print_out(" Level: '%d'", currently_rule->level); print_out(" Description: '%s'",currently_rule->comment); - for (last_info_detail = currently_rule->info_details; last_info_detail != NULL; last_info_detail = last_info_detail->next) + for (last_info_detail = currently_rule->info_details; last_info_detail != NULL; last_info_detail = last_info_detail->next) { print_out(" Info - %s: '%s'", ruleinfodetail_text[last_info_detail->type], last_info_detail->data); } } #endif - + /* Ignore level 0 */ @@ -561,7 +585,7 @@ void OS_ReadMSG(int m_queue, char *ut_str) } - /* Checking ignore time */ + /* Checking ignore time */ if(currently_rule->ignore_time) { if(currently_rule->time_ignored == 0) @@ -572,7 +596,7 @@ void OS_ReadMSG(int m_queue, char *ut_str) * is less than the time it should be ignored, * leave (do not alert again). */ - else if((lf->time - currently_rule->time_ignored) + else if((lf->time - currently_rule->time_ignored) < currently_rule->ignore_time) { break; @@ -586,7 +610,7 @@ void OS_ReadMSG(int m_queue, char *ut_str) /* Pointer to the rule that generated it */ lf->generated_rule = currently_rule; - + /* Checking if we should ignore it */ if(currently_rule->ckignore && IGnore(lf)) { @@ -594,7 +618,7 @@ void OS_ReadMSG(int m_queue, char *ut_str) lf->generated_rule = NULL; break; } - + /* Checking if we need to add to ignore list */ if(currently_rule->ignore) { @@ -626,19 +650,19 @@ void OS_ReadMSG(int m_queue, char *ut_str) } else { - lf->sid_node_to_delete = + lf->sid_node_to_delete = currently_rule->sid_prev_matched->last_node; } } /* Group list */ else if(currently_rule->group_prev_matched) { - i = 0; - + i = 0; + while(i < currently_rule->group_prev_matched_sz) { if(!OSList_AddData( - currently_rule->group_prev_matched[i], + currently_rule->group_prev_matched[i], lf)) { merror("%s: Unable to add data to grp list.",ARGV0); @@ -646,7 +670,7 @@ void OS_ReadMSG(int m_queue, char *ut_str) i++; } } - + OS_AddEvent(lf); break; @@ -659,7 +683,7 @@ void OS_ReadMSG(int m_queue, char *ut_str) char holder[1024]; holder[1] = '\0'; exit_code = 3; - if(strcasecmp(ut_decoder_name, lf->decoder_info->name) == 0) + if(lf->decoder_info->name != NULL && strcasecmp(ut_decoder_name, lf->decoder_info->name) == 0) { exit_code--; snprintf(holder, 1023, "%d", currently_rule->sigid); @@ -678,7 +702,7 @@ void OS_ReadMSG(int m_queue, char *ut_str) /* Only clear the memory if the eventinfo was not - * added to the stateful memory + * added to the stateful memory * -- message is free inside clean event -- */ if(lf->generated_rule == NULL) @@ -687,7 +711,7 @@ void OS_ReadMSG(int m_queue, char *ut_str) } else { - exit(exit_code); + exit(exit_code); } } exit(exit_code); diff --git a/src/client-agent/agentd.c b/src/client-agent/agentd.c index bcb2686..6439250 100755 --- a/src/client-agent/agentd.c +++ b/src/client-agent/agentd.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/client-agent/agentd.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -28,30 +29,30 @@ void AgentdStart(char *dir, int uid, int gid, char *user, char *group) { int rc = 0; int pid = 0; - int maxfd = 0; + int maxfd = 0; fd_set fdset; - + struct timeval fdtimeout; - + /* Going daemon */ pid = getpid(); available_server = 0; nowDaemon(); goDaemon(); - + /* Setting group ID */ if(Privsep_SetGroup(gid) < 0) ErrorExit(SETGID_ERROR, ARGV0, group); - + /* chrooting */ if(Privsep_Chroot(dir) < 0) ErrorExit(CHROOT_ERROR, ARGV0, dir); - + nowChroot(); @@ -68,7 +69,7 @@ void AgentdStart(char *dir, int uid, int gid, char *user, char *group) maxfd = logr->m_queue; logr->sock = -1; - + /* Creating PID file */ @@ -78,23 +79,28 @@ void AgentdStart(char *dir, int uid, int gid, char *user, char *group) /* Reading the private keys */ verbose(ENC_READ, ARGV0); - + OS_ReadKeys(&keys); OS_StartCounter(&keys); + + /* cmoraes : changed the following call to os_write_agent_info(keys.keyentries[0]->name, NULL, keys.keyentries[0]->id); + */ + os_write_agent_info(keys.keyentries[0]->name, NULL, keys.keyentries[0]->id, + logr->profile); /* Start up message */ verbose(STARTUP_MSG, ARGV0, (int)getpid()); - + /* Initial random numbers */ #ifdef __OpenBSD__ srandomdev(); #else srandom( time(0) + getpid()+ pid + getppid()); #endif - + random(); @@ -112,7 +118,7 @@ void AgentdStart(char *dir, int uid, int gid, char *user, char *group) { ErrorExit(UNABLE_CONN, ARGV0); } - + /* Setting max fd for select */ if(logr->sock > maxfd) @@ -138,7 +144,7 @@ void AgentdStart(char *dir, int uid, int gid, char *user, char *group) os_setwait(); start_agent(1); - + os_delwait(); @@ -146,15 +152,15 @@ void AgentdStart(char *dir, int uid, int gid, char *user, char *group) intcheck_file(OSSECCONF, dir); intcheck_file(OSSEC_DEFINES, dir); - + /* Sending first notification */ run_notify(); - - + + /* Maxfd must be higher socket +1 */ maxfd++; - - + + /* monitor loop */ while(1) { @@ -166,28 +172,28 @@ void AgentdStart(char *dir, int uid, int gid, char *user, char *group) fdtimeout.tv_sec = 120; fdtimeout.tv_usec = 0; - + /* Wait for 120 seconds at a maximum for any descriptor */ rc = select(maxfd, &fdset, NULL, NULL, &fdtimeout); if(rc == -1) { ErrorExit(SELECT_ERROR, ARGV0); } - - + + else if(rc == 0) { continue; - } + } + - /* For the receiver */ if(FD_ISSET(logr->sock, &fdset)) { receive_msg(); } - + /* For the forwarder */ if(FD_ISSET(logr->m_queue, &fdset)) { diff --git a/src/client-agent/agentd.h b/src/client-agent/agentd.h index dfd220c..87b5c92 100755 --- a/src/client-agent/agentd.h +++ b/src/client-agent/agentd.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/client-agent/agentd.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -39,7 +40,7 @@ void *receive_msg(); /* Receiver messages for Windows */ void *receiver_thread(void *none); -/* intcheck_file: +/* intcheck_file: * Sends integrity checking information about a file to the server. */ int intcheck_file(char *file_name, char *dir); @@ -63,7 +64,7 @@ void run_notify(); /*** Global variables ***/ /* Global variables. Only modified - * during startup. + * during startup. */ #include "shared.h" diff --git a/src/client-agent/config.c b/src/client-agent/config.c index 312eb70..7d6d151 100755 --- a/src/client-agent/config.c +++ b/src/client-agent/config.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/client-agent/config.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -25,7 +26,7 @@ /* ClientConf v0.2, 2005/03/03 * Read the config file (for the remote client) * v0.2: New OS_XML - */ + */ int ClientConf(char *cfgfile) { int modules = 0; @@ -34,6 +35,7 @@ int ClientConf(char *cfgfile) logr->lip = NULL; logr->rip_id = 0; logr->execdq = 0; + logr->profile = NULL; /*cmoraes*/ modules|= CCLIENT; diff --git a/src/client-agent/event-forward.c b/src/client-agent/event-forward.c index 5e1f920..b6a69fb 100755 --- a/src/client-agent/event-forward.c +++ b/src/client-agent/event-forward.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/client-agent/event-forward.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. diff --git a/src/client-agent/intcheck_op.c b/src/client-agent/intcheck_op.c index 8137d53..a7025c6 100755 --- a/src/client-agent/intcheck_op.c +++ b/src/client-agent/intcheck_op.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/client-agent/intcheck_op.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -42,7 +43,7 @@ int intcheck_file(char *file_name, char *dir) if(lstat(file_name, &statbuf) < 0) #endif { - snprintf(newsum, 911,"%c:%s:-1 %s%s", SYSCHECK_MQ, SYSCHECK, + snprintf(newsum, 911,"%c:%s:-1 %s%s", SYSCHECK_MQ, SYSCHECK, dir, file_name); send_msg(0, newsum); @@ -70,7 +71,7 @@ int intcheck_file(char *file_name, char *dir) } } - + snprintf(newsum,911,"%c:%s:%d:%d:%d:%d:%s:%s %s%s", SYSCHECK_MQ, SYSCHECK, (int)statbuf.st_size, diff --git a/src/client-agent/main.c b/src/client-agent/main.c index b78cd09..bda8ced 100755 --- a/src/client-agent/main.c +++ b/src/client-agent/main.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/client-agent/main.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -35,15 +36,15 @@ int main(int argc, char **argv) { int c = 0; int test_config = 0; - + char *dir = DEFAULTDIR; char *user = USER; char *group = GROUPGLOBAL; - + int uid = 0; int gid = 0; - + /* Setting the name */ OS_SetName(ARGV0); @@ -70,7 +71,7 @@ int main(int argc, char **argv) group = optarg; break; case 't': - test_config = 1; + test_config = 1; break; case 'D': if(!optarg) @@ -88,7 +89,7 @@ int main(int argc, char **argv) ErrorExit(MEM_ERROR, ARGV0); } - + /* Reading config */ if(ClientConf(DEFAULTCPATH) < 0) { @@ -98,7 +99,7 @@ int main(int argc, char **argv) if(!logr->rip) { merror(AG_INV_IP, ARGV0); - ErrorExit(CLIENT_ERROR,ARGV0); + ErrorExit(CLIENT_ERROR,ARGV0); } @@ -108,7 +109,7 @@ int main(int argc, char **argv) ErrorExit(AG_NOKEYS_EXIT, ARGV0); } - + /* Check if the user/group given are valid */ uid = Privsep_GetUser(user); gid = Privsep_GetGroup(group); @@ -131,7 +132,7 @@ int main(int argc, char **argv) /* Agentd Start */ AgentdStart(dir, uid, gid, user, group); - + return(0); } diff --git a/src/client-agent/notify.c b/src/client-agent/notify.c index 39c332c..e698380 100755 --- a/src/client-agent/notify.c +++ b/src/client-agent/notify.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/client-agent/notify.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -19,6 +20,20 @@ time_t g_saved_time = 0; +char *rand_keepalive_str2(char *dst, int size) +{ + static const char text[] = "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789" + "!@#$%^&*()_+-=;'[],./?"; + int i, len = rand() % (size - 1); + for ( i = 0; i < len; ++i ) + { + dst[i] = text[rand() % (sizeof text - 1)]; + } + dst[i] = '\0'; + return dst; +} /* getfiles: Return the name of the files in a directory */ @@ -27,9 +42,9 @@ char *getsharedfiles() int m_size = 512; char *ret; - + os_md5 md5sum; - + if(OS_MD5_File(SHAREDCFG_FILE, md5sum) != 0) { @@ -49,7 +64,7 @@ char *getsharedfiles() snprintf(ret, m_size, "%s merged.mg\n", md5sum); - + return(ret); } @@ -59,9 +74,14 @@ char *getsharedfiles() /* run_notify: Send periodically notification to server */ void run_notify() { + char keep_alive_random[1024]; char tmp_msg[OS_SIZE_1024 +1]; char *uname; char *shared_files; + os_md5 md5sum; + + + keep_alive_random[0] = '\0'; time_t curr_time; @@ -93,14 +113,14 @@ void run_notify() return; } g_saved_time = curr_time; - + debug1("%s: DEBUG: Sending agent notification.", ARGV0); /* Send the message. - * Message is going to be the - * uname\n checksum file\n checksum file\n - */ + * Message is going to be the + * uname\n checksum file\n checksum file\n + */ /* Getting uname */ uname = getuname(); @@ -124,23 +144,20 @@ void run_notify() } } + rand_keepalive_str2(keep_alive_random, 700); + /* creating message */ - if(File_DateofChange(AGENTCONFIGINT) > 0) + if((File_DateofChange(AGENTCONFIGINT) > 0 ) && + (OS_MD5_File(AGENTCONFIGINT, md5sum) == 0)) { - os_md5 md5sum; - if(OS_MD5_File(AGENTCONFIGINT, md5sum) != 0) - { - snprintf(tmp_msg, OS_SIZE_1024, "#!-%s\n%s",uname, shared_files); - } - else - { - snprintf(tmp_msg, OS_SIZE_1024, "#!-%s / %s\n%s",uname, md5sum, shared_files); - } + snprintf(tmp_msg, OS_SIZE_1024, "#!-%s / %s\n%s\n%s", + uname, md5sum, shared_files, keep_alive_random); } else { - snprintf(tmp_msg, OS_SIZE_1024, "#!-%s\n%s",uname, shared_files); + snprintf(tmp_msg, OS_SIZE_1024, "#!-%s\n%s\n%s", + uname, shared_files, keep_alive_random); } diff --git a/src/client-agent/receiver-win.c b/src/client-agent/receiver-win.c index 73456df..33395e4 100755 --- a/src/client-agent/receiver-win.c +++ b/src/client-agent/receiver-win.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/client-agent/receiver-win.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -19,36 +20,36 @@ -/* receiver_thread: +/* receiver_thread: * Receive events from the server. */ void *receiver_thread(void *none) { int recv_b; - + char file[OS_SIZE_1024 +1]; char buffer[OS_MAXSTR +1]; - + char cleartext[OS_MAXSTR + 1]; char *tmp_msg; - + char file_sum[34]; fd_set fdset; struct timeval selecttime; - + FILE *fp; /* Setting FP to null, before starting */ fp = NULL; - + memset(cleartext, '\0', OS_MAXSTR +1); memset(buffer, '\0', OS_MAXSTR +1); memset(file, '\0', OS_SIZE_1024 +1); memset(file_sum, '\0', 34); - - + + while(1) { /* sock must be set. */ @@ -60,13 +61,13 @@ void *receiver_thread(void *none) FD_ZERO(&fdset); FD_SET(logr->sock, &fdset); - + /* Wait for 30 seconds. */ selecttime.tv_sec = 30; selecttime.tv_usec = 0; - + /* Wait for 120 seconds at a maximum for any descriptor */ recv_b = select(0, &fdset, NULL, NULL, &selecttime); if(recv_b == -1) @@ -80,7 +81,7 @@ void *receiver_thread(void *none) continue; } - /* Read until no more messages are available */ + /* Read until no more messages are available */ while((recv_b = recv(logr->sock,buffer,OS_SIZE_1024, 0))>0) { /* Id of zero -- only one key allowed */ @@ -97,27 +98,27 @@ void *receiver_thread(void *none) { /* This is the only thread that modifies it */ available_server = (int)time(NULL); - + /* Run timeout commands. */ if(logr->execdq >= 0) WinTimeoutRun(available_server); - + /* If it is an active response message */ if(strncmp(tmp_msg, EXECD_HEADER, strlen(EXECD_HEADER)) == 0) { tmp_msg+=strlen(EXECD_HEADER); - + /* Run on windows. */ if(logr->execdq >= 0) { WinExecdRun(tmp_msg); } - - + + continue; - } + } /* Restart syscheck. */ @@ -127,7 +128,7 @@ void *receiver_thread(void *none) continue; } - + /* Ack from server */ else if(strcmp(tmp_msg, HC_ACK) == 0) { @@ -142,7 +143,7 @@ void *receiver_thread(void *none) } /* File update message */ - if(strncmp(tmp_msg, FILE_UPDATE_HEADER, + if(strncmp(tmp_msg, FILE_UPDATE_HEADER, strlen(FILE_UPDATE_HEADER)) == 0) { char *validate_file; @@ -160,7 +161,7 @@ void *receiver_thread(void *none) /* copying the file sum */ strncpy(file_sum, tmp_msg, 33); - + /* Setting tmp_msg to the beginning of the file name */ validate_file++; tmp_msg = validate_file; @@ -177,10 +178,10 @@ void *receiver_thread(void *none) } if(tmp_msg[0] == '.') - tmp_msg[0] = '-'; + tmp_msg[0] = '-'; - - snprintf(file, OS_SIZE_1024, "%s/%s", + + snprintf(file, OS_SIZE_1024, "%s/%s", SHAREDCFG_DIR, tmp_msg); @@ -191,7 +192,7 @@ void *receiver_thread(void *none) } } - else if(strncmp(tmp_msg, FILE_CLOSE_HEADER, + else if(strncmp(tmp_msg, FILE_CLOSE_HEADER, strlen(FILE_CLOSE_HEADER)) == 0) { /* no error */ @@ -203,7 +204,7 @@ void *receiver_thread(void *none) fclose(fp); fp = NULL; } - + if(file[0] == '\0') { /* nada */ @@ -220,7 +221,7 @@ void *receiver_thread(void *none) if(strcmp(currently_md5, file_sum) != 0) { debug1("%s: Failed md5 for: %s -- deleting.", - ARGV0, file); + ARGV0, file); unlink(file); } else @@ -263,10 +264,10 @@ void *receiver_thread(void *none) merror("%s: WARN: Unknown message received. No action defined.", ARGV0); } - } + } } - + /* Cleaning up */ if(fp) { @@ -274,7 +275,7 @@ void *receiver_thread(void *none) if(file[0] != '\0') unlink(file); } - + return(NULL); } diff --git a/src/client-agent/receiver.c b/src/client-agent/receiver.c index b9ab116..1a35484 100755 --- a/src/client-agent/receiver.c +++ b/src/client-agent/receiver.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/client-agent/receiver.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -29,7 +30,7 @@ char file_sum[34] = ""; char file[OS_SIZE_1024 +1] = ""; -/* receive_msg: +/* receive_msg: * Receive events from the server. */ void *receive_msg() @@ -47,7 +48,7 @@ void *receive_msg() - /* Read until no more messages are available */ + /* Read until no more messages are available */ while((recv_b = recv(logr->sock, buffer, OS_SIZE_1024, MSG_DONTWAIT)) > 0) { buffer[recv_b] = '\0'; @@ -83,7 +84,7 @@ void *receive_msg() { if(OS_SendUnix(logr->execdq, tmp_msg, 0) < 0) { - merror("%s: Error communicating with execd", + merror("%s: Error communicating with execd", ARGV0); } } @@ -101,7 +102,7 @@ void *receive_msg() continue; - } + } /* Restart syscheck. */ @@ -128,7 +129,7 @@ void *receive_msg() /* File update message */ - if(strncmp(tmp_msg, FILE_UPDATE_HEADER, + if(strncmp(tmp_msg, FILE_UPDATE_HEADER, strlen(FILE_UPDATE_HEADER)) == 0) { char *validate_file; @@ -164,10 +165,10 @@ void *receive_msg() } if(tmp_msg[0] == '.') - tmp_msg[0] = '-'; + tmp_msg[0] = '-'; - snprintf(file, OS_SIZE_1024, "%s/%s", + snprintf(file, OS_SIZE_1024, "%s/%s", SHAREDCFG_DIR, tmp_msg); @@ -179,7 +180,7 @@ void *receive_msg() } } - else if(strncmp(tmp_msg, FILE_CLOSE_HEADER, + else if(strncmp(tmp_msg, FILE_CLOSE_HEADER, strlen(FILE_CLOSE_HEADER)) == 0) { /* no error */ @@ -208,7 +209,7 @@ void *receive_msg() if(strcmp(currently_md5, file_sum) != 0) { debug1("%s: ERROR: Failed md5 for: %s -- deleting.", - ARGV0, file); + ARGV0, file); unlink(file); } else @@ -252,7 +253,7 @@ void *receive_msg() merror("%s: WARN: Unknown message received. No action defined.", ARGV0); } - } + } return(NULL); diff --git a/src/client-agent/sendmsg.c b/src/client-agent/sendmsg.c index 438e848..f92a457 100755 --- a/src/client-agent/sendmsg.c +++ b/src/client-agent/sendmsg.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/client-agent/sendmsg.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -14,7 +15,7 @@ #include "agentd.h" #include "os_net/os_net.h" - + /* Sends a message to the server */ int send_msg(int agentid, char *msg) diff --git a/src/client-agent/start_agent.c b/src/client-agent/start_agent.c index c27dc2e..3327d9d 100755 --- a/src/client-agent/start_agent.c +++ b/src/client-agent/start_agent.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/client-agent/start_agent.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -44,15 +45,15 @@ int connect_server(int initial_id) if(logr->rip[1]) { - verbose("%s: INFO: Closing connection to server (%s:%d).", + verbose("%s: INFO: Closing connection to server (%s:%d).", ARGV0, logr->rip[rc], logr->port); } - + } - - + + while(logr->rip[rc]) { char *tmp_str; @@ -63,7 +64,7 @@ int connect_server(int initial_id) { char *f_ip; *tmp_str = '\0'; - + f_ip = OS_GetHost(logr->rip[rc], 5); if(f_ip) { @@ -71,7 +72,7 @@ int connect_server(int initial_id) ip_str[127] = '\0'; snprintf(ip_str, 127, "%s/%s", logr->rip[rc], f_ip); - + free(f_ip); free(logr->rip[rc]); @@ -81,7 +82,7 @@ int connect_server(int initial_id) } else { - merror("%s: WARN: Unable to get hostname for '%s'.", + merror("%s: WARN: Unable to get hostname for '%s'.", ARGV0, logr->rip[rc]); *tmp_str = '/'; tmp_str++; @@ -91,13 +92,24 @@ int connect_server(int initial_id) { tmp_str = logr->rip[rc]; } - - + + verbose("%s: INFO: Trying to connect to server (%s:%d).", ARGV0, logr->rip[rc], logr->port); - logr->sock = OS_ConnectUDP(logr->port, tmp_str); + /* IPv6 address: */ + if(strchr(tmp_str,':') != NULL) + { + verbose("%s: INFO: Using IPv6 for: %s .", ARGV0, tmp_str); + logr->sock = OS_ConnectUDP(logr->port, tmp_str, 1); + } + else + { + verbose("%s: INFO: Using IPv4 for: %s .", ARGV0, tmp_str); + logr->sock = OS_ConnectUDP(logr->port, tmp_str, 0); + } + if(logr->sock < 0) { logr->sock = -1; @@ -107,11 +119,11 @@ int connect_server(int initial_id) if(logr->rip[rc] == NULL) { attempts += 10; - + /* Only log that if we have more than 1 server configured. */ if(logr->rip[1]) merror("%s: ERROR: Unable to connect to any server.",ARGV0); - + sleep(attempts); rc = 0; } @@ -120,12 +132,12 @@ int connect_server(int initial_id) { /* Setting socket non-blocking on HPUX */ #ifdef HPUX - fcntl(logr->sock, O_NONBLOCK); + //fcntl(logr->sock, O_NONBLOCK); #endif #ifdef WIN32 int bmode = 1; - + /* Setting socket to non-blocking */ ioctlsocket(logr->sock, FIONBIO, (u_long FAR*) &bmode); #endif @@ -152,7 +164,7 @@ void start_agent(int is_startup) char buffer[OS_MAXSTR +1]; char cleartext[OS_MAXSTR +1]; char fmsg[OS_MAXSTR +1]; - + memset(msg, '\0', OS_MAXSTR +2); memset(buffer, '\0', OS_MAXSTR +1); @@ -164,15 +176,15 @@ void start_agent(int is_startup) #ifdef ONEWAY return; #endif - - + + /* Sending start message and waiting for the ack */ while(1) { /* Sending start up message */ send_msg(0, msg); attempts = 0; - + /* Read until our reply comes back */ while(((recv_b = recv(logr->sock, buffer, OS_MAXSTR, @@ -191,10 +203,10 @@ void start_agent(int is_startup) { send_msg(0, msg); } - + continue; } - + /* Id of zero -- only one key allowed */ tmp_msg = ReadSecMSG(&keys, buffer, cleartext, 0, recv_b -1); if(tmp_msg == NULL) @@ -212,16 +224,16 @@ void start_agent(int is_startup) { available_server = time(0); - verbose(AG_CONNECTED, ARGV0, logr->rip[logr->rip_id], + verbose(AG_CONNECTED, ARGV0, logr->rip[logr->rip_id], logr->port); - + if(is_startup) { /* Send log message about start up */ - snprintf(msg, OS_MAXSTR, OS_AG_STARTED, + snprintf(msg, OS_MAXSTR, OS_AG_STARTED, keys.keyentries[0]->name, keys.keyentries[0]->ip->ip); - snprintf(fmsg, OS_MAXSTR, "%c:%s:%s", LOCALFILE_MQ, + snprintf(fmsg, OS_MAXSTR, "%c:%s:%s", LOCALFILE_MQ, "ossec", msg); send_msg(0, fmsg); } @@ -257,11 +269,11 @@ void start_agent(int is_startup) { sleep(g_attempts); g_attempts+=(attempts * 3); - + connect_server(0); } } - + return; } diff --git a/src/config/active-response.c b/src/config/active-response.c index 20e0cf6..72e470b 100755 --- a/src/config/active-response.c +++ b/src/config/active-response.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/config/active-response.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -9,7 +10,7 @@ * Foundation */ - + #include "shared.h" #include "os_xml/os_xml.h" #include "os_regex/os_regex.h" @@ -26,6 +27,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) int i = 0; int r_ar = 0; int l_ar = 0; + int rpt = 0; /* Xml options */ @@ -37,6 +39,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) char *xml_ar_level = "level"; char *xml_ar_timeout = "timeout"; char *xml_ar_disabled = "disabled"; + char *xml_ar_repeated = "repeated_offenders"; char *tmp_location; @@ -52,7 +55,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) merror(FOPEN_ERROR, ARGV0, DEFAULTARPATH); return(-1); } - chmod(DEFAULTARPATH, 0444); + chmod(DEFAULTARPATH, 0440); /* Allocating for the active-response */ @@ -77,7 +80,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) - /* Searching for the commands */ + /* Searching for the commands */ while(node[i]) { if(!node[i]->element) @@ -92,12 +95,12 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) } /* Command */ - if(strcmp(node[i]->element, xml_ar_command) == 0) + if(strcmp(node[i]->element, xml_ar_command) == 0) { tmp_ar->command = strdup(node[i]->content); } /* Target */ - else if(strcmp(node[i]->element, xml_ar_location) == 0) + else if(strcmp(node[i]->element, xml_ar_location) == 0) { tmp_location = strdup(node[i]->content); } @@ -121,7 +124,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); return(OS_INVALID); } - + tmp_ar->level = atoi(node[i]->content); /* Making sure the level is valid */ @@ -151,13 +154,18 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) return(OS_INVALID); } } + else if(strcmp(node[i]->element, xml_ar_repeated) == 0) + { + /* Nothing - we deal with it on execd. */ + rpt = 1; + } else { merror(XML_INVELEM, ARGV0, node[i]->element); return(OS_INVALID); } i++; - } + } /* Checking if ar is disabled */ if(ar_flag == -1) @@ -169,6 +177,11 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) /* Command and location must be there */ if(!tmp_ar->command || !tmp_location) { + if(rpt == 1) + { + fclose(fp); + return(0); + } merror(AR_MISS, ARGV0); return(-1); } @@ -201,14 +214,14 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) } /* If we didn't set any value for the location */ - if(tmp_ar->location == 0) + if(tmp_ar->location == 0) { merror(AR_INV_LOC, ARGV0, tmp_location); return(-1); } - /* cleaning tmp_location */ + /* cleaning tmp_location */ free(tmp_location); tmp_location = NULL; @@ -261,13 +274,13 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) { ErrorExit(MEM_ERROR, ARGV0); } - snprintf(tmp_ar->name, OS_FLSIZE, "%s%d", + snprintf(tmp_ar->name, OS_FLSIZE, "%s%d", tmp_ar->ar_cmd->name, - tmp_ar->timeout); + tmp_ar->timeout); /* Adding to shared file */ - fprintf(fp, "%s - %s - %d\n", + fprintf(fp, "%s - %s - %d\n", tmp_ar->name, tmp_ar->ar_cmd->executable, tmp_ar->timeout); @@ -301,7 +314,7 @@ int ReadActiveResponses(XML_NODE node, void *d1, void *d2) { ar_flag|= LOCAL_AR; } - + /* Closing shared file for active response */ fclose(fp); @@ -342,7 +355,7 @@ int ReadActiveCommands(XML_NODE node, void *d1, void *d2) tmp_command->timeout_allowed = 0; - /* Searching for the commands */ + /* Searching for the commands */ while(node[i]) { if(!node[i]->element) @@ -355,11 +368,11 @@ int ReadActiveCommands(XML_NODE node, void *d1, void *d2) merror(XML_VALUENULL, ARGV0, node[i]->element); return(OS_INVALID); } - if(strcmp(node[i]->element, command_name) == 0) + if(strcmp(node[i]->element, command_name) == 0) { tmp_command->name = strdup(node[i]->content); } - else if(strcmp(node[i]->element, command_expect) == 0) + else if(strcmp(node[i]->element, command_expect) == 0) { tmp_str = strdup(node[i]->content); } @@ -395,10 +408,13 @@ int ReadActiveCommands(XML_NODE node, void *d1, void *d2) /* Getting the expect */ - if(OS_Regex("user", tmp_str)) - tmp_command->expect |= USERNAME; - if(OS_Regex("srcip", tmp_str)) - tmp_command->expect |= SRCIP; + if(strlen(tmp_str) >= 4) + { + if(OS_Regex("user", tmp_str)) + tmp_command->expect |= USERNAME; + if(OS_Regex("srcip", tmp_str)) + tmp_command->expect |= SRCIP; + } free(tmp_str); tmp_str = NULL; diff --git a/src/config/active-response.h b/src/config/active-response.h index 0e821ab..c9ca703 100755 --- a/src/config/active-response.h +++ b/src/config/active-response.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/config/active-response.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -9,7 +10,7 @@ * Foundation */ - + #ifndef _CAR__H #define _CAR__H @@ -19,7 +20,7 @@ typedef struct _ar_command { int expect; int timeout_allowed; - + char *name; char *executable; }ar_command; @@ -36,7 +37,7 @@ typedef struct _ar char *agent_id; char *rules_id; char *rules_group; - + ar_command *ar_cmd; }active_response; diff --git a/src/config/agentlessd-config.c b/src/config/agentlessd-config.c index e0c76da..6694126 100644 --- a/src/config/agentlessd-config.c +++ b/src/config/agentlessd-config.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/config/agentlessd-config.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -33,7 +34,7 @@ int Read_CAgentless(XML_NODE node, void *config, void *config2) agentlessd_config *lessd_config = (agentlessd_config *)config; - + /* Getting any configured entry. */ if(lessd_config->entries) { @@ -41,9 +42,9 @@ int Read_CAgentless(XML_NODE node, void *config, void *config2) s++; } - + /* Allocating the memory for the config. */ - os_realloc(lessd_config->entries, (s + 2) * sizeof(agentlessd_entries *), + os_realloc(lessd_config->entries, (s + 2) * sizeof(agentlessd_entries *), lessd_config->entries); os_calloc(1, sizeof(agentlessd_entries), lessd_config->entries[s]); lessd_config->entries[s + 1] = NULL; @@ -60,7 +61,7 @@ int Read_CAgentless(XML_NODE node, void *config, void *config2) lessd_config->entries[s]->port = 0; lessd_config->entries[s]->error_flag = 0; - + /* Reading the XML. */ while(node[i]) { @@ -98,7 +99,7 @@ int Read_CAgentless(XML_NODE node, void *config, void *config2) { char s_content[1024 +1]; s_content[1024] = '\0'; - + /* Getting any configured entry. */ j = 0; if(lessd_config->entries[s]->server) @@ -107,8 +108,8 @@ int Read_CAgentless(XML_NODE node, void *config, void *config2) j++; } - os_realloc(lessd_config->entries[s]->server, (j + 2) * - sizeof(char *), + os_realloc(lessd_config->entries[s]->server, (j + 2) * + sizeof(char *), lessd_config->entries[s]->server); if(strncmp(node[i]->content, "use_su ", 7) == 0) { @@ -122,8 +123,8 @@ int Read_CAgentless(XML_NODE node, void *config, void *config2) { snprintf(s_content, 1024, " %s", node[i]->content); } - - os_strdup(s_content, + + os_strdup(s_content, lessd_config->entries[s]->server[j]); lessd_config->entries[s]->server[j + 1] = NULL; } @@ -134,11 +135,11 @@ int Read_CAgentless(XML_NODE node, void *config, void *config2) script_path[1024] = '\0'; snprintf(script_path, 1024, "%s/%s", AGENTLESSDIRPATH, node[i]->content); - + if(File_DateofChange(script_path) <= 0) { merror("%s: ERROR: Unable to find '%s' at '%s'.", - ARGV0, node[i]->content, AGENTLESSDIRPATH); + ARGV0, node[i]->content, AGENTLESSDIRPATH); merror(XML_VALUEERR,ARGV0, node[i]->element, node[i]->content); return(OS_INVALID); } @@ -190,8 +191,8 @@ int Read_CAgentless(XML_NODE node, void *config, void *config2) merror(XML_INV_MISSOPTS, ARGV0); return(OS_INVALID); } - - + + if((lessd_config->entries[s]->state == LESSD_STATE_PERIODIC) && !lessd_config->entries[s]->frequency) { diff --git a/src/config/agentlessd-config.h b/src/config/agentlessd-config.h index 9d522b3..c69a6b8 100755 --- a/src/config/agentlessd-config.h +++ b/src/config/agentlessd-config.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/config/agentlessd-config.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -31,16 +32,16 @@ typedef struct _agentlessd_entries int current_state; int port; int error_flag; - + char *type; char **server; char *options; char *command; - + }agentlessd_entries; -/* Configuration structure. */ +/* Configuration structure. */ typedef struct _agentlessd_config { int queue; diff --git a/src/config/alerts-config.c b/src/config/alerts-config.c index 85efc95..353ba46 100755 --- a/src/config/alerts-config.c +++ b/src/config/alerts-config.c @@ -25,10 +25,15 @@ int Read_Alerts(XML_NODE node, void *configp, void *mailp) char *xml_email_level = "email_alert_level"; char *xml_log_level = "log_alert_level"; +#ifdef GEOIP + /* GeoIP */ + char *xml_log_geoip = "use_geoip"; +#endif + _Config *Config; - + Config = (_Config *)configp; - + while(node[i]) { @@ -63,6 +68,22 @@ int Read_Alerts(XML_NODE node, void *configp, void *mailp) } Config->logbylevel = atoi(node[i]->content); } +#ifdef GEOIP + /* Enable GeoIP */ + else if(strcmp(node[i]->element, xml_log_geoip) == 0) + { + if(strcmp(node[i]->content, "yes") == 0) + { if(Config) Config->loggeoip = 1;} + else if(strcmp(node[i]->content, "no") == 0) + {if(Config) Config->loggeoip = 0;} + else + { + merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + return(OS_INVALID); + } + + } +#endif else { merror(XML_INVELEM, ARGV0, node[i]->element); diff --git a/src/config/client-config.c b/src/config/client-config.c index 3eddfc3..5721755 100755 --- a/src/config/client-config.c +++ b/src/config/client-config.c @@ -16,16 +16,18 @@ #include "os_net/os_net.h" -int Read_Client(XML_NODE node, void *d1, void *d2) +int Read_Client(XML_NODE node, void *d1, void *d2) { int i = 0; - + /* XML definitions */ char *xml_client_ip = "server-ip"; char *xml_client_hostname = "server-hostname"; char *xml_local_ip = "local_ip"; char *xml_client_port = "port"; char *xml_ar_disabled = "disable-active-response"; + /* cmoraes */ + char *xml_profile_name = "config-profile"; agent *logr; @@ -70,7 +72,7 @@ int Read_Client(XML_NODE node, void *d1, void *d2) os_realloc(logr->rip, (ip_id + 2) * sizeof(char*), logr->rip); logr->rip[ip_id] = NULL; logr->rip[ip_id +1] = NULL; - + os_strdup(node[i]->content, logr->rip[ip_id]); if(OS_IsValidIP(logr->rip[ip_id], NULL) != 1) { @@ -98,7 +100,7 @@ int Read_Client(XML_NODE node, void *d1, void *d2) os_realloc(logr->rip, (ip_id + 2) * sizeof(char*), logr->rip); - + s_ip = OS_GetHost(node[i]->content, 5); if(!s_ip) { @@ -108,7 +110,7 @@ int Read_Client(XML_NODE node, void *d1, void *d2) os_strdup("invalid_ip", s_ip); } - + f_ip[127] = '\0'; snprintf(f_ip, 127, "%s/%s", node[i]->content, s_ip); @@ -147,6 +149,12 @@ int Read_Client(XML_NODE node, void *d1, void *d2) return(OS_INVALID); } } + /* cmoraes */ + else if(strcmp(node[i]->element,xml_profile_name) == 0) + { + /* profile name can be anything hence no validation */ + os_strdup(node[i]->content, logr->profile); + } else { merror(XML_INVELEM, ARGV0, node[i]->element); diff --git a/src/config/client-config.h b/src/config/client-config.h index 5049a9d..ce2f558 100755 --- a/src/config/client-config.h +++ b/src/config/client-config.h @@ -23,7 +23,8 @@ typedef struct _agent int execdq; int rip_id; char *lip; - char **rip; /* remote (server) ip */ + char **rip; /* remote (server) ip */ + char *profile; }agent; diff --git a/src/config/config.c b/src/config/config.c index c0cda89..57a0afb 100755 --- a/src/config/config.c +++ b/src/config/config.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/config/config.c, 2011/11/01 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -21,33 +22,33 @@ /* Read the main elements of the configuration. */ -int read_main_elements(OS_XML xml, int modules, - XML_NODE node, - void *d1, +int read_main_elements(OS_XML xml, int modules, + XML_NODE node, + void *d1, void *d2) { int i = 0; - char *osglobal = "global"; - char *osrules = "rules"; - char *ossyscheck = "syscheck"; - char *osrootcheck = "rootcheck"; - char *osalerts = "alerts"; - char *osemailalerts = "email_alerts"; - char *osdbd = "database_output"; - char *oscsyslogd = "syslog_output"; - char *oscagentless = "agentless"; - char *oslocalfile = "localfile"; - char *osremote = "remote"; - char *osclient = "client"; - char *oscommand = "command"; - char *osreports = "reports"; - char *osactive_response = "active-response"; - - + char *osglobal = "global"; /*Server Config*/ + char *osrules = "rules"; /*Server Config*/ + char *ossyscheck = "syscheck"; /*Agent Config*/ + char *osrootcheck = "rootcheck"; /*Agent Config*/ + char *osalerts = "alerts"; /*Server Config*/ + char *osemailalerts = "email_alerts"; /*Server Config*/ + char *osdbd = "database_output"; /*Server Config*/ + char *oscsyslogd = "syslog_output"; /*Server Config*/ + char *oscagentless = "agentless"; /*Server Config*/ + char *oslocalfile = "localfile"; /*Agent Config*/ + char *osremote = "remote"; /*Agent Config*/ + char *osclient = "client"; /*Agent Config*/ + char *oscommand = "command"; /*? Config*/ + char *osreports = "reports"; /*Server Config*/ + char *osactive_response = "active-response"; /*Agent Config*/ + + while(node[i]) { XML_NODE chld_node = NULL; - + chld_node = OS_GetElementsbyNode(&xml,node[i]); if(!node[i]->element) @@ -62,7 +63,7 @@ int read_main_elements(OS_XML xml, int modules, } else if(strcmp(node[i]->element, osglobal) == 0) { - if(((modules & CGLOBAL) || (modules & CMAIL)) + if(((modules & CGLOBAL) || (modules & CMAIL)) && (Read_Global(chld_node, d1, d2) < 0)) return(OS_INVALID); } @@ -96,7 +97,7 @@ int read_main_elements(OS_XML xml, int modules, if((modules & CSYSCHECK) && (Read_Syscheck(chld_node, d1,d2) < 0)) return(OS_INVALID); if((modules & CGLOBAL) && (Read_GlobalSK(chld_node, d1, d2) < 0)) - return(OS_INVALID); + return(OS_INVALID); } else if(strcmp(node[i]->element, osrootcheck) == 0) { @@ -143,7 +144,7 @@ int read_main_elements(OS_XML xml, int modules, merror(XML_INVELEM, ARGV0, node[i]->element); return(OS_INVALID); } - + //printf("before\n"); OS_ClearNode(chld_node); //printf("after\n"); @@ -157,7 +158,7 @@ int read_main_elements(OS_XML xml, int modules, /* ReadConfig(int modules, char *cfgfile) * Read the config files */ -int ReadConfig(int modules, char *cfgfile, void *d1, void *d2) +int ReadConfig(int modules, char *cfgfile, void *d1, void *d2) { int i; OS_XML xml; @@ -169,10 +170,13 @@ int ReadConfig(int modules, char *cfgfile, void *d1, void *d2) char *xml_start_ossec = "ossec_config"; char *xml_start_agent = "agent_config"; + /* Attributes of the tag */ char *xml_agent_name = "name"; char *xml_agent_os = "os"; char *xml_agent_overwrite = "overwrite"; - + /* cmoraes */ + char *xml_agent_profile = "profile"; + if(OS_ReadXML(cfgfile,&xml) < 0) { @@ -188,7 +192,7 @@ int ReadConfig(int modules, char *cfgfile, void *d1, void *d2) } return(OS_INVALID); } - + node = OS_GetElementsbyNode(&xml, NULL); if(!node) @@ -221,7 +225,7 @@ int ReadConfig(int modules, char *cfgfile, void *d1, void *d2) return(OS_INVALID); } - OS_ClearNode(chld_node); + OS_ClearNode(chld_node); } } else if((modules & CAGENT_CONFIG) && @@ -235,9 +239,10 @@ int ReadConfig(int modules, char *cfgfile, void *d1, void *d2) /* Checking if this is specific to any agent. */ if(node[i]->attributes && node[i]->values) - { + { while(node[i]->attributes[attrs] && node[i]->values[attrs]) { + /* Checking if there is an "name=" attribute */ if(strcmp(xml_agent_name, node[i]->attributes[attrs]) == 0) { #ifdef CLIENT @@ -277,6 +282,37 @@ int ReadConfig(int modules, char *cfgfile, void *d1, void *d2) } #endif } + else if(strcmp(xml_agent_profile, node[i]->attributes[attrs]) == 0) + { + #ifdef CLIENT + char *agentprofile = os_read_agent_profile(); + debug2("Read agent config profile name [%s]", agentprofile); + + if(!agentprofile) + { + passed_agent_test = 0; + } + else + { + /* match the profile name of this section + * with a comma separated list of values in agent's + * tag. + */ + if(!OS_Match2(node[i]->values[attrs], agentprofile)) + { + passed_agent_test = 0; + debug2("[%s] did not match agent config profile name [%s]", + node[i]->values[attrs], agentprofile); + } + else + { + debug2("Matched agent config profile name [%s]", agentprofile); + } + free(agentprofile); + } + #endif + } + /* cmoraes: end add */ else if(strcmp(xml_agent_overwrite, node[i]->attributes[attrs]) == 0) { } @@ -288,8 +324,25 @@ int ReadConfig(int modules, char *cfgfile, void *d1, void *d2) attrs++; } } + #ifdef CLIENT + else + { + debug2("agent_config element does not have any attributes."); + + /* if node does not have any attributes, it is a generic config block. + * check if agent has a profile name + * if agent does not have profile name, then only read this generic + * agent_config block + */ + + if (!os_read_agent_profile()) + { + debug2("but agent has a profile name."); + passed_agent_test = 0; + } + } + #endif - /* Main element does not need to have any child */ if(chld_node) { @@ -299,7 +352,7 @@ int ReadConfig(int modules, char *cfgfile, void *d1, void *d2) return(OS_INVALID); } - OS_ClearNode(chld_node); + OS_ClearNode(chld_node); } } else @@ -309,7 +362,7 @@ int ReadConfig(int modules, char *cfgfile, void *d1, void *d2) } i++; } - + /* Clearing node and xml */ OS_ClearNode(node); OS_ClearXML(&xml); diff --git a/src/config/config.h b/src/config/config.h index af1eb7e..83d649a 100755 --- a/src/config/config.h +++ b/src/config/config.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/config/config.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -12,7 +13,7 @@ * online at: http://www.ossec.net/en/licensing.html */ - + #ifndef _HCONFIG__H #define _HCONFIG__H @@ -30,7 +31,7 @@ #define CDBD 0002000 #define CSYSLOGD 0004000 #define CAGENTLESS 0020000 -#define CREPORTS 0040000 +#define CREPORTS 0040000 #define CAGENT_CONFIG 0010000 diff --git a/src/config/csyslogd-config.c b/src/config/csyslogd-config.c index 1ce6082..77d268e 100644 --- a/src/config/csyslogd-config.c +++ b/src/config/csyslogd-config.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/config/csyslogd-config.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -34,7 +35,7 @@ int Read_CSyslog(XML_NODE node, void *config, void *config2) GeneralConfig *gen_config = (GeneralConfig *)config; SyslogConfig **syslog_config = (SyslogConfig **)gen_config->data; - + /* Getting Granular mail_to size */ if(syslog_config) { @@ -42,7 +43,7 @@ int Read_CSyslog(XML_NODE node, void *config, void *config2) s++; } - + /* Allocating the memory for the config. */ os_realloc(syslog_config, (s + 2) * sizeof(SyslogConfig *), syslog_config); os_calloc(1, sizeof(SyslogConfig), syslog_config[s]); @@ -56,6 +57,7 @@ int Read_CSyslog(XML_NODE node, void *config, void *config2) syslog_config[s]->location = NULL; syslog_config[s]->level = 0; syslog_config[s]->port = 514; + syslog_config[s]->format = DEFAULT_CSYSLOG; /* local 0 facility (16) + severity 4 - warning. --default */ syslog_config[s]->priority = (16 * 8) + 4; @@ -116,24 +118,24 @@ int Read_CSyslog(XML_NODE node, void *config, void *config2) else if(isdigit((int)*str_pt)) { int id_i = 0; - + r_id = atoi(str_pt); debug1("%s: DEBUG: Adding '%d' to syslog alerting", ARGV0, r_id); - + if(syslog_config[s]->rule_id) { while(syslog_config[s]->rule_id[id_i]) id_i++; } - + os_realloc(syslog_config[s]->rule_id, (id_i +2) * sizeof(int), syslog_config[s]->rule_id); - + syslog_config[s]->rule_id[id_i + i] = 0; syslog_config[s]->rule_id[id_i] = r_id; - + str_pt = strchr(str_pt, ','); if(str_pt) { @@ -165,6 +167,21 @@ int Read_CSyslog(XML_NODE node, void *config, void *config2) { /* Default is full format */ } + else if (strcmp(node[i]->content, "cef") == 0) + { + /* Enable the CEF format */ + syslog_config[s]->format = CEF_CSYSLOG; + } + else if (strcmp(node[i]->content, "json") == 0) + { + /* Enable the JSON format */ + syslog_config[s]->format = JSON_CSYSLOG; + } + else if (strcmp(node[i]->content, "splunk") == 0) + { + /* Enable the Splunk Key/Value format */ + syslog_config[s]->format = SPLUNK_CSYSLOG; + } else { merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); @@ -174,7 +191,7 @@ int Read_CSyslog(XML_NODE node, void *config, void *config2) else if(strcmp(node[i]->element, xml_syslog_location) == 0) { os_calloc(1, sizeof(OSMatch),syslog_config[s]->location); - if(!OSMatch_Compile(node[i]->content, + if(!OSMatch_Compile(node[i]->content, syslog_config[s]->location, 0)) { merror(REGEX_COMPILE, ARGV0, node[i]->content, @@ -185,7 +202,7 @@ int Read_CSyslog(XML_NODE node, void *config, void *config2) else if(strcmp(node[i]->element, xml_syslog_group) == 0) { os_calloc(1, sizeof(OSMatch),syslog_config[s]->group); - if(!OSMatch_Compile(node[i]->content, + if(!OSMatch_Compile(node[i]->content, syslog_config[s]->group, 0)) { merror(REGEX_COMPILE, ARGV0, node[i]->content, @@ -208,7 +225,7 @@ int Read_CSyslog(XML_NODE node, void *config, void *config2) merror(XML_INV_CSYSLOG, ARGV0); return(OS_INVALID); } - + gen_config->data = syslog_config; return(0); diff --git a/src/config/csyslogd-config.h b/src/config/csyslogd-config.h index 08ed723..47a11eb 100755 --- a/src/config/csyslogd-config.h +++ b/src/config/csyslogd-config.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/config/csyslogd-config.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -11,7 +12,7 @@ #include "shared.h" - + #ifndef _CSYSLOGCONFIG__H #define _CSYSLOGCONFIG__H @@ -35,6 +36,9 @@ typedef struct _SyslogConfig /* Syslog formats. */ #define DEFAULT_CSYSLOG 0 +#define CEF_CSYSLOG 1 +#define JSON_CSYSLOG 2 +#define SPLUNK_CSYSLOG 3 /* Syslog severities */ diff --git a/src/config/dbd-config.c b/src/config/dbd-config.c index 4537306..949ef5d 100644 --- a/src/config/dbd-config.c +++ b/src/config/dbd-config.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/config/dbd-config.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -32,7 +33,7 @@ int Read_DB(XML_NODE node, void *config1, void *config2) char *xml_dbsock = "socket"; char *xml_dbtype = "type"; - + db_config = (DBConfig *)config2; if(!db_config) { @@ -40,7 +41,7 @@ int Read_DB(XML_NODE node, void *config1, void *config2) } - /* Reading the xml */ + /* Reading the xml */ while(node[i]) { if(!node[i]->element) diff --git a/src/config/dbd-config.h b/src/config/dbd-config.h index 51c0af4..2a3d29a 100755 --- a/src/config/dbd-config.h +++ b/src/config/dbd-config.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/config/dbd-config.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -9,7 +10,7 @@ * Foundation */ - + #ifndef _DBDCONFIG__H #define _DBDONFIG__H @@ -30,7 +31,7 @@ typedef struct _DBConfig char *pass; char *db; char *sock; - + void *conn; void *location_hash; diff --git a/src/config/email-alerts-config.c b/src/config/email-alerts-config.c index 4b63608..8d61e13 100644 --- a/src/config/email-alerts-config.c +++ b/src/config/email-alerts-config.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/config/email-alerts-config.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -33,7 +34,7 @@ int Read_EmailAlerts(XML_NODE node, void *configp, void *mailp) char *xml_email_donotgroup = "do_not_group"; MailConfig *Mail; - + Mail = (MailConfig *)mailp; if(!Mail) { @@ -56,44 +57,44 @@ int Read_EmailAlerts(XML_NODE node, void *configp, void *mailp) if(Mail) { - os_realloc(Mail->gran_to, + os_realloc(Mail->gran_to, sizeof(char *)*(granto_size +1), Mail->gran_to); - os_realloc(Mail->gran_id, + os_realloc(Mail->gran_id, sizeof(int *)*(granto_size +1), Mail->gran_id); - os_realloc(Mail->gran_level, + os_realloc(Mail->gran_level, sizeof(int)*(granto_size +1), Mail->gran_level); - os_realloc(Mail->gran_set, + os_realloc(Mail->gran_set, sizeof(int)*(granto_size +1), Mail->gran_set); - os_realloc(Mail->gran_format, + os_realloc(Mail->gran_format, sizeof(int)*(granto_size +1), Mail->gran_format); - os_realloc(Mail->gran_location, + os_realloc(Mail->gran_location, sizeof(OSMatch)*(granto_size +1), Mail->gran_location); - os_realloc(Mail->gran_group, + os_realloc(Mail->gran_group, sizeof(OSMatch)*(granto_size +1), Mail->gran_group); - + Mail->gran_to[granto_size -1] = NULL; Mail->gran_to[granto_size] = NULL; - + Mail->gran_id[granto_size -1] = NULL; Mail->gran_id[granto_size] = NULL; - + Mail->gran_location[granto_size -1] = NULL; Mail->gran_location[granto_size] = NULL; Mail->gran_group[granto_size -1] = NULL; Mail->gran_group[granto_size] = NULL; - + Mail->gran_level[granto_size -1] = 0; Mail->gran_level[granto_size] = 0; - - Mail->gran_format[granto_size -1] = FULL_FORMAT; - Mail->gran_format[granto_size] = FULL_FORMAT; - + + Mail->gran_format[granto_size -1] = FULL_FORMAT; + Mail->gran_format[granto_size] = FULL_FORMAT; + Mail->gran_set[granto_size -1] = 0; Mail->gran_set[granto_size] = 0; } - - + + while(node[i]) { if(!node[i]->element) @@ -142,11 +143,11 @@ int Read_EmailAlerts(XML_NODE node, void *configp, void *mailp) else if(isdigit((int)*str_pt)) { int id_i = 0; - + r_id = atoi(str_pt); debug1("%s: DEBUG: Adding '%d' to granular e-mail", ARGV0, r_id); - + if(!Mail->gran_id[granto_size -1]) { os_calloc(2,sizeof(int),Mail->gran_id[granto_size -1]); @@ -159,14 +160,14 @@ int Read_EmailAlerts(XML_NODE node, void *configp, void *mailp) { id_i++; } - + os_realloc(Mail->gran_id[granto_size -1], (id_i +2) * sizeof(int), - Mail->gran_id[granto_size -1]); + Mail->gran_id[granto_size -1]); Mail->gran_id[granto_size -1][id_i +1] = 0; } Mail->gran_id[granto_size -1][id_i] = r_id; - + str_pt = strchr(str_pt, ','); if(str_pt) @@ -227,7 +228,7 @@ int Read_EmailAlerts(XML_NODE node, void *configp, void *mailp) else if(strcmp(node[i]->element, xml_email_location) == 0) { os_calloc(1, sizeof(OSMatch),Mail->gran_location[granto_size -1]); - if(!OSMatch_Compile(node[i]->content, + if(!OSMatch_Compile(node[i]->content, Mail->gran_location[granto_size -1], 0)) { merror(REGEX_COMPILE, ARGV0, node[i]->content, @@ -238,7 +239,7 @@ int Read_EmailAlerts(XML_NODE node, void *configp, void *mailp) else if(strcmp(node[i]->element, xml_email_group) == 0) { os_calloc(1, sizeof(OSMatch),Mail->gran_group[granto_size -1]); - if(!OSMatch_Compile(node[i]->content, + if(!OSMatch_Compile(node[i]->content, Mail->gran_group[granto_size -1], 0)) { merror(REGEX_COMPILE, ARGV0, node[i]->content, @@ -265,7 +266,7 @@ int Read_EmailAlerts(XML_NODE node, void *configp, void *mailp) merror(XML_INV_GRAN_MAIL, ARGV0); return(OS_INVALID); } - + return(0); } diff --git a/src/config/global-config.c b/src/config/global-config.c index 9380308..dad66a4 100755 --- a/src/config/global-config.c +++ b/src/config/global-config.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/config/global-config.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -45,8 +46,8 @@ int Read_GlobalSK(XML_NODE node, void *configp, void *mailp) _Config *Config; Config = (_Config *)configp; - - + + /* Shouldn't be here if !Config */ if(!Config) return(0); @@ -164,12 +165,18 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) char *xml_smtpserver = "smtp_server"; char *xml_mailmaxperhour = "email_maxperhour"; +#ifdef GEOIP + /* GeoIP */ + char *xml_geoip_db_path = "geoip_db_path"; + char *xml_geoip6_db_path = "geoip6_db_path"; +#endif + _Config *Config; MailConfig *Mail; - + Config = (_Config *)configp; Mail = (MailConfig *)mailp; - + /* Getting right white_size */ if(Config && Config->white_list) { @@ -182,7 +189,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) ww++; } } - + /* Getting right white_size */ if(Config && Config->hostname_white_list) { @@ -195,7 +202,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) ww++; } } - + /* Getting mail_to size */ if(Mail && Mail->to) { @@ -224,13 +231,13 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) else if(strcmp(node[i]->element, xml_mailnotify) == 0) { if(strcmp(node[i]->content, "yes") == 0) - { - if(Config) Config->mailnotify = 1; + { + if(Config) Config->mailnotify = 1; if(Mail) Mail->mn = 1; } else if(strcmp(node[i]->content, "no") == 0) - { - if(Config) Config->mailnotify = 0; + { + if(Config) Config->mailnotify = 0; if(Mail) Mail->mn = 0; } else @@ -267,12 +274,12 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) else if(strcmp(node[i]->element, xml_prelude) == 0) { if(strcmp(node[i]->content, "yes") == 0) - { - if(Config) Config->prelude = 1; + { + if(Config) Config->prelude = 1; } else if(strcmp(node[i]->content, "no") == 0) - { - if(Config) Config->prelude = 0; + { + if(Config) Config->prelude = 0; } else { @@ -391,11 +398,11 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) char *ip_address_regex = "^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}/?" "([0-9]{0,2}|[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3})$"; - + if(Config && OS_PRegex(node[i]->content, ip_address_regex)) { white_size++; - Config->white_list = + Config->white_list = realloc(Config->white_list, sizeof(os_ip *)*white_size); if(!Config->white_list) { @@ -405,11 +412,11 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) os_calloc(1, sizeof(os_ip), Config->white_list[white_size -2]); Config->white_list[white_size -1] = NULL; - + if(!OS_IsValidIP(node[i]->content, Config->white_list[white_size -2])) { - merror(INVALID_IP, ARGV0, + merror(INVALID_IP, ARGV0, node[i]->content); return(OS_INVALID); } @@ -421,20 +428,20 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) Config->hostname_white_list = realloc(Config->hostname_white_list, sizeof(OSMatch *)*hostname_white_size); - + if(!Config->hostname_white_list) { merror(MEM_ERROR, ARGV0); return(OS_INVALID); } - os_calloc(1, - sizeof(OSMatch), + os_calloc(1, + sizeof(OSMatch), Config->hostname_white_list[hostname_white_size -2]); Config->hostname_white_list[hostname_white_size -1] = NULL; if(!OSMatch_Compile( - node[i]->content, - Config->hostname_white_list[hostname_white_size -2], + node[i]->content, + Config->hostname_white_list[hostname_white_size -2], 0)) { merror(REGEX_COMPILE, ARGV0, node[i]->content, @@ -443,12 +450,12 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) return(-1); } } - + #endif - + } - /* For the email now + /* For the email now * email_to, email_from, smtp_Server and maxperhour. * We will use a separate structure for that. */ @@ -461,7 +468,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) return(OS_INVALID); } #endif - + if(Mail) { mailto_size++; @@ -499,7 +506,7 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) return(OS_INVALID); } } - #endif + #endif } else if(strcmp(node[i]->element, xml_mailmaxperhour) == 0) { @@ -519,6 +526,24 @@ int Read_Global(XML_NODE node, void *configp, void *mailp) } } } +#ifdef GEOIP + /* GeoIP v4 DB location */ + else if(strcmp(node[i]->element, xml_geoip_db_path) == 0) + { + if(Config) + { + os_strdup(node[i]->content, Config->geoip_db_path); + } + } + /* GeoIP v6 DB location */ + else if(strcmp(node[i]->element, xml_geoip6_db_path) == 0) + { + if(Config) + { + os_strdup(node[i]->content, Config->geoip6_db_path); + } + } +#endif else { merror(XML_INVELEM, ARGV0, node[i]->element); diff --git a/src/config/global-config.h b/src/config/global-config.h index 57dcf6b..8867ece 100755 --- a/src/config/global-config.h +++ b/src/config/global-config.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/config/global-config.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -9,7 +10,7 @@ * Foundation */ - + #ifndef _CCONFIG__H #define _CCONFIG__H @@ -29,7 +30,7 @@ typedef struct __Config u_int8_t mailbylevel; u_int8_t logbylevel; u_int8_t logfw; - + /* Prelude support */ u_int8_t prelude; /* which min. level the alert must be sent to prelude */ @@ -46,14 +47,14 @@ typedef struct __Config /* Mail alerting */ short int mailnotify; - - /* For the active response */ + + /* For the active response */ int ar; - + /* For the correlation */ int memorysize; - - /* List of files to ignore (syscheck) */ + + /* List of files to ignore (syscheck) */ char **syscheck_ignore; /* List of ips to never block */ @@ -74,6 +75,13 @@ typedef struct __Config /* Global rule hash. */ void *g_rules_hash; +#ifdef GEOIP + /* GeoIP support */ + u_int8_t loggeoip; + char *geoip_db_path; + char *geoip6_db_path; +#endif + }_Config; diff --git a/src/config/localfile-config.c b/src/config/localfile-config.c index 6f53bff..b9df546 100755 --- a/src/config/localfile-config.c +++ b/src/config/localfile-config.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/config/localfile-config.c, 2012/03/28 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -9,9 +10,9 @@ * Foundation */ - -#include "shared.h" + +#include "shared.h" #include "localfile-config.h" @@ -19,9 +20,9 @@ int Read_Localfile(XML_NODE node, void *d1, void *d2) { int pl = 0; int i = 0; - - int glob_set = 0; - + + int glob_set = 0; + #ifndef WIN32 int glob_offset = 0; #endif @@ -40,7 +41,7 @@ int Read_Localfile(XML_NODE node, void *d1, void *d2) log_config = (logreader_config *)d1; - /* If config is not set, we need to create it */ + /* If config is not set, we need to create it */ if(!log_config->config) { os_calloc(2, sizeof(logreader), log_config->config); @@ -61,7 +62,7 @@ int Read_Localfile(XML_NODE node, void *d1, void *d2) { pl++; } - + /* Allocating more memory */ os_realloc(logf, (pl +2)*sizeof(logreader), log_config->config); logf = log_config->config; @@ -70,7 +71,7 @@ int Read_Localfile(XML_NODE node, void *d1, void *d2) logf[pl +1].alias = NULL; logf[pl +1].logformat = NULL; } - + logf[pl].file = NULL; logf[pl].command = NULL; logf[pl].alias = NULL; @@ -80,7 +81,7 @@ int Read_Localfile(XML_NODE node, void *d1, void *d2) logf[pl].djb_program_name = NULL; logf[pl].ign = 360; - + /* Searching for entries related to files */ i = 0; while(node[i]) @@ -97,6 +98,21 @@ int Read_Localfile(XML_NODE node, void *d1, void *d2) } else if(strcmp(node[i]->element,xml_localfile_command) == 0) { + /* We don't accept remote commands from the manager - just in case. */ + if(log_config->agent_cfg == 1 && log_config->accept_remote == 0) + { + merror("%s: Remote commands are not accepted from the manager. " + "Ignoring it on the agent.conf", ARGV0); + + logf[pl].file = NULL; + logf[pl].ffile = NULL; + logf[pl].command = NULL; + logf[pl].alias = NULL; + logf[pl].logformat = NULL; + logf[pl].fp = NULL; + return(OS_INVALID); + } + os_strdup(node[i]->content, logf[pl].file); logf[pl].command = logf[pl].file; } @@ -116,11 +132,11 @@ int Read_Localfile(XML_NODE node, void *d1, void *d2) /* Expand variables on Windows. */ if(strchr(node[i]->content, '%')) { - int expandreturn = 0; + int expandreturn = 0; char newfile[OS_MAXSTR +1]; newfile[OS_MAXSTR] = '\0'; - expandreturn = ExpandEnvironmentStrings(node[i]->content, + expandreturn = ExpandEnvironmentStrings(node[i]->content, newfile, OS_MAXSTR); if((expandreturn > 0) && (expandreturn < OS_MAXSTR)) @@ -129,7 +145,7 @@ int Read_Localfile(XML_NODE node, void *d1, void *d2) os_strdup(newfile, node[i]->content); } - } + } #endif @@ -137,17 +153,17 @@ int Read_Localfile(XML_NODE node, void *d1, void *d2) * We will call this file multiple times until * there is no one else available. */ - #ifndef WIN32 /* No windows support for glob */ + #ifndef WIN32 /* No windows support for glob */ if(strchr(node[i]->content, '*') || strchr(node[i]->content, '?') || strchr(node[i]->content, '[')) { glob_t g; - + /* Setting ot the first entry of the glob */ if(glob_set == 0) glob_set = pl +1; - + if(glob(node[i]->content, 0, NULL, &g) != 0) { merror(GLOB_ERROR, ARGV0, node[i]->content); @@ -155,7 +171,7 @@ int Read_Localfile(XML_NODE node, void *d1, void *d2) i++; continue; } - + /* Checking for the last entry */ if((g.gl_pathv[glob_offset]) == NULL) { @@ -196,7 +212,7 @@ int Read_Localfile(XML_NODE node, void *d1, void *d2) os_strdup(g.gl_pathv[glob_offset], logf[pl].file); } - + glob_offset++; globfree(&g); @@ -204,13 +220,13 @@ int Read_Localfile(XML_NODE node, void *d1, void *d2) pl++; os_realloc(logf, (pl +2)*sizeof(logreader), log_config->config); logf = log_config->config; - + logf[pl].file = NULL; logf[pl].alias = NULL; logf[pl].logformat = NULL; logf[pl].fp = NULL; logf[pl].ffile = NULL; - + logf[pl +1].file = NULL; logf[pl +1].alias = NULL; logf[pl +1].logformat = NULL; @@ -220,7 +236,7 @@ int Read_Localfile(XML_NODE node, void *d1, void *d2) } else if(strchr(node[i]->content, '%')) #else - if(strchr(node[i]->content, '%')) + if(strchr(node[i]->content, '%')) #endif /* WIN32 */ /* We need the format file (based on date) */ @@ -243,8 +259,8 @@ int Read_Localfile(XML_NODE node, void *d1, void *d2) os_strdup(node[i]->content, logf[pl].ffile); os_strdup(node[i]->content, logf[pl].file); } - - + + /* Normal file */ else { @@ -284,6 +300,9 @@ int Read_Localfile(XML_NODE node, void *d1, void *d2) else if(strcmp(logf[pl].logformat, "mysql_log") == 0) { } + else if(strcmp(logf[pl].logformat, "ossecalert") == 0) + { + } else if(strcmp(logf[pl].logformat, "mssql_log") == 0) { } @@ -309,7 +328,7 @@ int Read_Localfile(XML_NODE node, void *d1, void *d2) while(logf[pl].logformat[0] == ' ') logf[pl].logformat++; - + if(logf[pl].logformat[0] != ':') { merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); @@ -319,8 +338,8 @@ int Read_Localfile(XML_NODE node, void *d1, void *d2) while(*logf[pl].logformat == ' ') logf[pl].logformat++; - - while(logf[pl].logformat[x] >= '0' && logf[pl].logformat[x] <= '9') + + while(logf[pl].logformat[x] >= '0' && logf[pl].logformat[x] <= '9') x++; while(logf[pl].logformat[x] == ' ') @@ -359,7 +378,7 @@ int Read_Localfile(XML_NODE node, void *d1, void *d2) if(glob_set) { char *format; - + /* Getting log format */ if(logf[pl].logformat) { @@ -388,7 +407,7 @@ int Read_Localfile(XML_NODE node, void *d1, void *d2) merror(MISS_FILE, ARGV0); return(OS_INVALID); } - + if(logf[i].logformat == NULL) { logf[i].logformat = format; @@ -410,7 +429,7 @@ int Read_Localfile(XML_NODE node, void *d1, void *d2) merror(MISS_FILE, ARGV0); return(OS_INVALID); } - + /* Verifying a valid event log config */ if(strcmp(logf[pl].logformat, EVENTLOG) == 0) { @@ -425,7 +444,7 @@ int Read_Localfile(XML_NODE node, void *d1, void *d2) } if((strcmp(logf[pl].logformat, "command") == 0)|| - (strcmp(logf[pl].logformat, "full_command") == 0)) + (strcmp(logf[pl].logformat, "full_command") == 0)) { if(!logf[pl].command) { diff --git a/src/config/localfile-config.h b/src/config/localfile-config.h index 821c3e2..ee9c38d 100755 --- a/src/config/localfile-config.h +++ b/src/config/localfile-config.h @@ -16,7 +16,7 @@ #define __CLOGREADER_H #define EVENTLOG "eventlog" -#define VCHECK_FILES 64 +#define VCHECK_FILES 64 #define DATE_MODIFIED 1 @@ -29,25 +29,25 @@ typedef struct _logreader { unsigned int size; int ign; - + #ifdef WIN32 HANDLE h; int fd; #else ino_t fd; #endif - - - /* ffile - format file is only used when + + + /* ffile - format file is only used when * the file has format string to retrieve * the date, - */ - char *ffile; + */ + char *ffile; char *file; char *logformat; char *djb_program_name; char *command; - char *alias; + char *alias; void (*read)(int i, int *rc, int drop_it); @@ -56,6 +56,8 @@ typedef struct _logreader typedef struct _logreader_config { + int agent_cfg; + int accept_remote; logreader *config; }logreader_config; diff --git a/src/config/mail-config.h b/src/config/mail-config.h index 45276dc..8d75c24 100755 --- a/src/config/mail-config.h +++ b/src/config/mail-config.h @@ -9,7 +9,7 @@ * Foundation */ - + #ifndef _MCCONFIG__H #define _MCCONFIG__H @@ -35,6 +35,12 @@ typedef struct _MailConfig int *gran_set; int *gran_format; char **gran_to; + +#ifdef GEOIP + /* Use GeoIP */ + int geoip; +#endif + OSMatch **gran_location; OSMatch **gran_group; }MailConfig; diff --git a/src/config/remote-config.c b/src/config/remote-config.c index 6627813..e85d625 100755 --- a/src/config/remote-config.c +++ b/src/config/remote-config.c @@ -34,6 +34,7 @@ int Read_Remote(XML_NODE node, void *d1, void *d2) /* Remote options */ char *xml_remote_port = "port"; char *xml_remote_proto = "protocol"; + char *xml_remote_ipv6 = "ipv6"; char *xml_remote_connection = "connection"; char *xml_remote_lip = "local_ip"; @@ -52,8 +53,8 @@ int Read_Remote(XML_NODE node, void *d1, void *d2) while(logr->denyips[deny_size -1]) deny_size++; } - - + + /* conn and port must not be null */ if(!logr->conn) { @@ -70,13 +71,18 @@ int Read_Remote(XML_NODE node, void *d1, void *d2) os_calloc(1, sizeof(int), logr->proto); logr->proto[0] = 0; } + if(!logr->ipv6) + { + os_calloc(1, sizeof(int), logr->ipv6); + logr->ipv6[0] = 0; + } if(!logr->lip) { os_calloc(1, sizeof(char *), logr->lip); logr->lip[0] = NULL; } - - + + /* Cleaning */ while(logr->conn[pl] != 0) pl++; @@ -86,22 +92,25 @@ int Read_Remote(XML_NODE node, void *d1, void *d2) logr->port = realloc(logr->port, sizeof(int)*(pl +2)); logr->conn = realloc(logr->conn, sizeof(int)*(pl +2)); logr->proto = realloc(logr->proto, sizeof(int)*(pl +2)); + logr->ipv6 = realloc(logr->ipv6, sizeof(int)*(pl +2)); logr->lip = realloc(logr->lip, sizeof(char *)*(pl +2)); if(!logr->port || !logr->conn || !logr->proto || !logr->lip) { merror(MEM_ERROR, ARGV0); } - + logr->port[pl] = 0; logr->conn[pl] = 0; logr->proto[pl] = 0; + logr->ipv6[pl] = 0; logr->lip[pl] = NULL; - + logr->port[pl +1] = 0; logr->conn[pl +1] = 0; logr->proto[pl +1] = 0; + logr->ipv6[pl +1] = 0; logr->lip[pl +1] = NULL; - + while(node[i]) { if(!node[i]->element) @@ -162,6 +171,13 @@ int Read_Remote(XML_NODE node, void *d1, void *d2) return(OS_INVALID); } } + else if(strcasecmp(node[i]->element,xml_remote_ipv6) == 0) + { + if(strcasecmp(node[i]->content, "yes") == 0) + { + logr->ipv6[pl] = 1; + } + } else if(strcasecmp(node[i]->element,xml_remote_lip) == 0) { os_strdup(node[i]->content,logr->lip[pl]); @@ -183,7 +199,7 @@ int Read_Remote(XML_NODE node, void *d1, void *d2) os_calloc(1, sizeof(os_ip), logr->allowips[allow_size -2]); logr->allowips[allow_size -1] = NULL; - + if(!OS_IsValidIP(node[i]->content,logr->allowips[allow_size -2])) { merror(INVALID_IP, ARGV0, node[i]->content); @@ -194,7 +210,7 @@ int Read_Remote(XML_NODE node, void *d1, void *d2) { deny_size++; logr->denyips = realloc(logr->denyips,sizeof(os_ip *)*deny_size); - if(!logr->denyips) + if(!logr->denyips) { merror(MEM_ERROR, ARGV0); return(OS_INVALID); @@ -222,14 +238,14 @@ int Read_Remote(XML_NODE node, void *d1, void *d2) merror(CONN_ERROR, ARGV0); return(OS_INVALID); } - + /* Set port in here */ if(logr->port[pl] == 0) { if(logr->conn[pl] == SECURE_CONN) logr->port[pl] = DEFAULT_SECURE; else - logr->port[pl] = DEFAULT_SYSLOG; + logr->port[pl] = DEFAULT_SYSLOG; } /* set default protocol */ @@ -243,7 +259,7 @@ int Read_Remote(XML_NODE node, void *d1, void *d2) { logr->proto[pl] = UDP_PROTO; } - + return(0); } diff --git a/src/config/remote-config.h b/src/config/remote-config.h index a043078..7896830 100755 --- a/src/config/remote-config.h +++ b/src/config/remote-config.h @@ -14,7 +14,7 @@ #define __CLOGREMOTE_H -#define SYSLOG_CONN 1 +#define SYSLOG_CONN 1 #define SECURE_CONN 2 #define UDP_PROTO 6 #define TCP_PROTO 17 @@ -27,6 +27,7 @@ typedef struct _remoted int *proto; int *port; int *conn; + int *ipv6; char **lip; os_ip **allowips; @@ -34,7 +35,7 @@ typedef struct _remoted int m_queue; int sock; - socklen_t peer_size; + socklen_t peer_size; }remoted; #endif diff --git a/src/config/reports-config.c b/src/config/reports-config.c index 2f5ce66..22a4832 100644 --- a/src/config/reports-config.c +++ b/src/config/reports-config.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/config/reports-config.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -66,7 +67,7 @@ int Read_CReports(XML_NODE node, void *config, void *config2) monitor_config *mon_config = (monitor_config *)config; - + /* Getting any configured entry. */ if(mon_config->reports) { @@ -74,9 +75,9 @@ int Read_CReports(XML_NODE node, void *config, void *config2) s++; } - + /* Allocating the memory for the config. */ - os_realloc(mon_config->reports, (s + 2) * sizeof(report_config *), + os_realloc(mon_config->reports, (s + 2) * sizeof(report_config *), mon_config->reports); os_calloc(1, sizeof(report_config), mon_config->reports[s]); mon_config->reports[s + 1] = NULL; @@ -105,7 +106,7 @@ int Read_CReports(XML_NODE node, void *config, void *config2) mon_config->reports[s]->r_filter.show_alerts = 0; - + /* Reading the XML. */ while(node[i]) { @@ -203,7 +204,7 @@ int Read_CReports(XML_NODE node, void *config, void *config2) os_strdup(node[i]->content, ncat); - if(os_report_configfilter(node[i]->element, ncat, + if(os_report_configfilter(node[i]->element, ncat, &mon_config->reports[s]->r_filter, reportf) < 0) { merror("%s: Invalid filter: %s:%s (ignored).", __local_name, node[i]->element, node[i]->content); @@ -230,7 +231,7 @@ int Read_CReports(XML_NODE node, void *config, void *config2) if(mon_config->reports[s]->title) merror("%s: No \"email to\" configured for the report '%s'. Ignoring it.", __local_name, mon_config->reports[s]->title); else - merror("%s: No \"email to\" and title configured for report. Ignoring it.", __local_name); + merror("%s: No \"email to\" and title configured for report. Ignoring it.", __local_name); } if(!mon_config->reports[s]->title) diff --git a/src/config/reports-config.h b/src/config/reports-config.h index 4b37a8d..202a738 100755 --- a/src/config/reports-config.h +++ b/src/config/reports-config.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/config/reports-config.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -26,7 +27,7 @@ typedef struct _report_config char **emailto; report_filter r_filter; }report_config; - + typedef struct _monitor_config { short int day_wait; diff --git a/src/config/rootcheck-config.c b/src/config/rootcheck-config.c index 79a3cec..51af27e 100755 --- a/src/config/rootcheck-config.c +++ b/src/config/rootcheck-config.c @@ -14,14 +14,26 @@ #include "rootcheck-config.h" +short eval_bool(char *str) +{ + if (str == NULL) + return(OS_INVALID); + else if (strcmp(str, "yes") == 0) + return(1); + else if (strcmp(str, "no") == 0) + return(0); + else + return(OS_INVALID); +} + /* Read_Rootcheck: Reads the rootcheck config */ -int Read_Rootcheck(XML_NODE node, void *configp, void *mailp) +int Read_Rootcheck(XML_NODE node, void *configp, void *mailp) { int i = 0; - + rkconfig *rootcheck; - + /* XML Definitions */ char *xml_rootkit_files = "rootkit_files"; char *xml_rootkit_trojans = "rootkit_trojans"; @@ -36,9 +48,20 @@ int Read_Rootcheck(XML_NODE node, void *configp, void *mailp) char *xml_base_dir = "base_directory"; char *xml_ignore = "ignore"; + char *xml_check_dev = "check_dev"; + char *xml_check_files = "check_files"; + char *xml_check_if = "check_if"; + char *xml_check_pids = "check_pids"; + char *xml_check_ports = "check_ports"; + char *xml_check_sys = "check_sys"; + char *xml_check_trojans = "check_trojans"; + char *xml_check_unixaudit = "check_unixaudit"; + char *xml_check_winapps = "check_winapps"; + char *xml_check_winaudit = "check_winaudit"; + char *xml_check_winmalware = "check_winmalware"; rootcheck = (rkconfig *)configp; - + while(node[i]) { if(!node[i]->element) @@ -66,11 +89,8 @@ int Read_Rootcheck(XML_NODE node, void *configp, void *mailp) /* getting scan all */ else if(strcmp(node[i]->element,xml_scanall) == 0) { - if(strcmp(node[i]->content, "yes") == 0) - rootcheck->scanall = 1; - else if(strcmp(node[i]->content, "no") == 0) - rootcheck->scanall = 0; - else + rootcheck->scanall = eval_bool(node[i]->content); + if (rootcheck->scanall == OS_INVALID) { merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); return(OS_INVALID); @@ -78,11 +98,8 @@ int Read_Rootcheck(XML_NODE node, void *configp, void *mailp) } else if(strcmp(node[i]->element, xml_disabled) == 0) { - if(strcmp(node[i]->content, "yes") == 0) - rootcheck->disabled = 1; - else if(strcmp(node[i]->content, "no") == 0) - rootcheck->disabled = 0; - else + rootcheck->disabled = eval_bool(node[i]->content); + if (rootcheck->disabled == OS_INVALID) { merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); return(OS_INVALID); @@ -90,11 +107,8 @@ int Read_Rootcheck(XML_NODE node, void *configp, void *mailp) } else if(strcmp(node[i]->element,xml_readall) == 0) { - if(strcmp(node[i]->content, "yes") == 0) - rootcheck->readall = 1; - else if(strcmp(node[i]->content, "no") == 0) - rootcheck->readall = 0; - else + rootcheck->readall = eval_bool(node[i]->content); + if (rootcheck->readall == OS_INVALID) { merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); return(OS_INVALID); @@ -117,12 +131,12 @@ int Read_Rootcheck(XML_NODE node, void *configp, void *mailp) int j = 0; while(rootcheck->unixaudit && rootcheck->unixaudit[j]) j++; - - os_realloc(rootcheck->unixaudit, sizeof(char *)*(j+2), + + os_realloc(rootcheck->unixaudit, sizeof(char *)*(j+2), rootcheck->unixaudit); rootcheck->unixaudit[j] = NULL; rootcheck->unixaudit[j + 1] = NULL; - + os_strdup(node[i]->content, rootcheck->unixaudit[j]); } else if(strcmp(node[i]->element, xml_ignore) == 0) @@ -130,12 +144,12 @@ int Read_Rootcheck(XML_NODE node, void *configp, void *mailp) int j = 0; while(rootcheck->ignore && rootcheck->ignore[j]) j++; - - os_realloc(rootcheck->ignore, sizeof(char *)*(j+2), + + os_realloc(rootcheck->ignore, sizeof(char *)*(j+2), rootcheck->ignore); rootcheck->ignore[j] = NULL; rootcheck->ignore[j + 1] = NULL; - + os_strdup(node[i]->content, rootcheck->ignore[j]); } else if(strcmp(node[i]->element, xml_winmalware) == 0) @@ -150,6 +164,113 @@ int Read_Rootcheck(XML_NODE node, void *configp, void *mailp) { os_strdup(node[i]->content, rootcheck->basedir); } + else if (strcmp(node[i]->element, xml_check_dev) == 0) + { + rootcheck->checks.rc_dev = eval_bool(node[i]->content); + if (rootcheck->checks.rc_dev == OS_INVALID) + { + merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + return(OS_INVALID); + } + } + else if (strcmp(node[i]->element, xml_check_files) == 0) + { + rootcheck->checks.rc_files = eval_bool(node[i]->content); + if (rootcheck->checks.rc_files == OS_INVALID) + { + merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + return(OS_INVALID); + } + } + else if (strcmp(node[i]->element, xml_check_if) == 0) + { + rootcheck->checks.rc_if = eval_bool(node[i]->content); + if (rootcheck->checks.rc_if == OS_INVALID) + { + merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + return(OS_INVALID); + } + } + else if (strcmp(node[i]->element, xml_check_pids) == 0) + { + rootcheck->checks.rc_pids = eval_bool(node[i]->content); + if (rootcheck->checks.rc_pids == OS_INVALID) + { + merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + return(OS_INVALID); + } + } + else if (strcmp(node[i]->element, xml_check_ports) == 0) + { + rootcheck->checks.rc_ports = eval_bool(node[i]->content); + if (rootcheck->checks.rc_ports == OS_INVALID) + { + merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + return(OS_INVALID); + } + } + else if (strcmp(node[i]->element, xml_check_sys) == 0) + { + rootcheck->checks.rc_sys = eval_bool(node[i]->content); + if (rootcheck->checks.rc_sys == OS_INVALID) + { + merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + return(OS_INVALID); + } + } + else if (strcmp(node[i]->element, xml_check_trojans) == 0) + { + rootcheck->checks.rc_trojans = eval_bool(node[i]->content); + if (rootcheck->checks.rc_trojans == OS_INVALID) + { + merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + return(OS_INVALID); + } + } + else if (strcmp(node[i]->element, xml_check_unixaudit) == 0) + { + #ifndef WIN32 + rootcheck->checks.rc_unixaudit = eval_bool(node[i]->content); + if (rootcheck->checks.rc_unixaudit == OS_INVALID) + { + merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + return(OS_INVALID); + } + #endif + } + else if (strcmp(node[i]->element, xml_check_winapps) == 0) + { + #ifdef WIN32 + rootcheck->checks.rc_winapps = eval_bool(node[i]->content); + if (rootcheck->checks.rc_winapps == OS_INVALID) + { + merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + return(OS_INVALID); + } + #endif + } + else if (strcmp(node[i]->element, xml_check_winaudit) == 0) + { + #ifdef WIN32 + rootcheck->checks.rc_winaudit = eval_bool(node[i]->content); + if (rootcheck->checks.rc_winaudit == OS_INVALID) + { + merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + return(OS_INVALID); + } + #endif + } + else if (strcmp(node[i]->element, xml_check_winmalware) == 0) + { + #ifdef WIN32 + rootcheck->checks.rc_winmalware = eval_bool(node[i]->content); + if (rootcheck->checks.rc_winmalware == OS_INVALID) + { + merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); + return(OS_INVALID); + } + #endif + } else { merror(XML_INVELEM, ARGV0, node[i]->element); diff --git a/src/config/rootcheck-config.h b/src/config/rootcheck-config.h index 7e82693..7a45baf 100755 --- a/src/config/rootcheck-config.h +++ b/src/config/rootcheck-config.h @@ -8,7 +8,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation */ - + #ifndef __CROOTCHECK_H @@ -38,6 +38,32 @@ typedef struct _rkconfig int time; int queue; + + struct _checks + { + short rc_dev; + short rc_files; + short rc_if; + short rc_pids; + short rc_ports; + short rc_sys; + short rc_trojans; + + #ifdef WIN32 + + short rc_winaudit; + short rc_winmalware; + short rc_winapps; + + #else + + short rc_unixaudit; + + #endif + + + } checks; + }rkconfig; #endif diff --git a/src/config/rules-config.c b/src/config/rules-config.c index 4801386..89c0721 100755 --- a/src/config/rules-config.c +++ b/src/config/rules-config.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/config/rules-config.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -12,20 +13,20 @@ /* Functions to handle the configuration files */ - +#include "config.h" #include "shared.h" #include "global-config.h" -static int cmpr(const void *a, const void *b) { +static int cmpr(const void *a, const void *b) { /*printf("%s - %s\n", *(char **)a, *(char **)b);*/ return strcmp(*(char **)a, *(char **)b); } static int file_in_list(int list_size, char *f_name, char *d_name, char **alist) { - int i = 0; + int i = 0; for(i=0; i<(list_size-1); i++) { if((strcmp(alist[i], f_name) == 0 || strcmp(alist[i], d_name) == 0)) @@ -33,25 +34,26 @@ static int file_in_list(int list_size, char *f_name, char *d_name, char **alist) return(1); } } - return(0); + return(0); } int Read_Rules(XML_NODE node, void *configp, void *mailp) { int i = 0; + int ii = 0; int rules_size = 1; int lists_size = 1; int decoders_size = 1; - + char path[PATH_MAX +2]; char f_name[PATH_MAX +2]; - int start_point = 0; + int start_point = 0; int att_count = 0; struct dirent *entry; - DIR *dfd; - OSRegex regex; + DIR *dfd; + OSRegex regex; /* XML definitions */ @@ -59,14 +61,19 @@ int Read_Rules(XML_NODE node, void *configp, void *mailp) char *xml_rules_rule = "rule"; char *xml_rules_rules_dir = "rule_dir"; char *xml_rules_lists = "list"; - char *xml_rules_lists_dir = "list_dir"; char *xml_rules_decoders = "decoder"; char *xml_rules_decoders_dir = "decoder_dir"; _Config *Config; - + Config = (_Config *)configp; - + + /* initialise OSRegex */ + regex.patterns = NULL; + regex.prts_closure = NULL; + regex.prts_str = NULL; + regex.sub_strings = NULL; + while(node[i]) { if(!node[i]->element) @@ -80,11 +87,11 @@ int Read_Rules(XML_NODE node, void *configp, void *mailp) return(OS_INVALID); } /* Mail notification */ - else if((strcmp(node[i]->element, xml_rules_include) == 0) || + else if((strcmp(node[i]->element, xml_rules_include) == 0) || (strcmp(node[i]->element, xml_rules_rule) == 0)) { rules_size++; - Config->includes = realloc(Config->includes, + Config->includes = realloc(Config->includes, sizeof(char *)*rules_size); if(!Config->includes) { @@ -182,7 +189,7 @@ int Read_Rules(XML_NODE node, void *configp, void *mailp) snprintf(f_name, PATH_MAX +1, "%s/%s", node[i]->content, entry->d_name); /* Just ignore . and .. */ - if((strcmp(entry->d_name,".") == 0) || (strcmp(entry->d_name,"..") == 0)) + if((strcmp(entry->d_name,".") == 0) || (strcmp(entry->d_name,"..") == 0)) continue; /* no dups allowed */ @@ -196,6 +203,7 @@ int Read_Rules(XML_NODE node, void *configp, void *mailp) if(!Config->decoders) { merror(MEM_ERROR, ARGV0); + OSRegex_FreePattern(®ex); return(-1); } @@ -208,12 +216,11 @@ int Read_Rules(XML_NODE node, void *configp, void *mailp) debug1("Regex does not match \"%s\"", f_name); } } - + closedir(dfd); /* Sort just then newly added items */ qsort(Config->decoders + start_point , decoders_size- start_point -1, sizeof(char *), cmpr); } - int ii=0; debug1("decoders_size %d", decoders_size); for(ii=0;iidecoders[ii]); @@ -260,7 +267,7 @@ int Read_Rules(XML_NODE node, void *configp, void *mailp) snprintf(f_name, PATH_MAX +1, "%s/%s", node[i]->content, entry->d_name); /* Just ignore . and .. */ - if((strcmp(entry->d_name,".") == 0) || (strcmp(entry->d_name,"..") == 0)) + if((strcmp(entry->d_name,".") == 0) || (strcmp(entry->d_name,"..") == 0)) continue; /* no dups allowed */ @@ -274,6 +281,7 @@ int Read_Rules(XML_NODE node, void *configp, void *mailp) if(!Config->includes) { merror(MEM_ERROR, ARGV0); + OSRegex_FreePattern(®ex); return(-1); } @@ -286,7 +294,7 @@ int Read_Rules(XML_NODE node, void *configp, void *mailp) debug1("Regex does not match \"%s\"", f_name); } } - + closedir(dfd); /* Sort just then newly added items */ qsort(Config->includes + start_point , rules_size - start_point -1, sizeof(char *), cmpr); @@ -295,6 +303,7 @@ int Read_Rules(XML_NODE node, void *configp, void *mailp) else { merror(XML_INVELEM, ARGV0, node[i]->element); + OSRegex_FreePattern(®ex); return(OS_INVALID); } i++; diff --git a/src/config/syscheck-config.c b/src/config/syscheck-config.c index 08fe42a..31cbede 100755 --- a/src/config/syscheck-config.c +++ b/src/config/syscheck-config.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/config/syscheck-config.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -19,7 +20,7 @@ int dump_syscheck_entry(config *syscheck, char *entry, int vals, int reg, char *restrictfile) { int pl = 0; - + if(reg == 1) { #ifdef WIN32 @@ -27,7 +28,7 @@ int dump_syscheck_entry(config *syscheck, char *entry, int vals, int reg, char * { os_calloc(2, sizeof(char *), syscheck->registry); syscheck->registry[pl + 1] = NULL; - os_strdup(entry, syscheck->registry[pl]); + os_strdup(entry, syscheck->registry[pl]); } else { @@ -35,16 +36,16 @@ int dump_syscheck_entry(config *syscheck, char *entry, int vals, int reg, char * { pl++; } - os_realloc(syscheck->registry, (pl +2) * sizeof(char *), + os_realloc(syscheck->registry, (pl +2) * sizeof(char *), syscheck->registry); syscheck->registry[pl + 1] = NULL; os_strdup(entry, syscheck->registry[pl]); } #endif - + } - + else { if(syscheck->dir == NULL) @@ -56,7 +57,7 @@ int dump_syscheck_entry(config *syscheck, char *entry, int vals, int reg, char * os_calloc(2, sizeof(int), syscheck->opts); syscheck->opts[pl + 1] = 0; syscheck->opts[pl] = vals; - + os_calloc(2, sizeof(OSMatch *), syscheck->filerestrict); syscheck->filerestrict[pl] = NULL; syscheck->filerestrict[pl + 1] = NULL; @@ -67,17 +68,17 @@ int dump_syscheck_entry(config *syscheck, char *entry, int vals, int reg, char * { pl++; } - os_realloc(syscheck->dir, (pl +2) * sizeof(char *), + os_realloc(syscheck->dir, (pl +2) * sizeof(char *), syscheck->dir); syscheck->dir[pl + 1] = NULL; os_strdup(entry, syscheck->dir[pl]); - os_realloc(syscheck->opts, (pl +2) * sizeof(int), + os_realloc(syscheck->opts, (pl +2) * sizeof(int), syscheck->opts); syscheck->opts[pl + 1] = 0; - syscheck->opts[pl] = vals; + syscheck->opts[pl] = vals; - os_realloc(syscheck->filerestrict, (pl +2) * sizeof(char *), + os_realloc(syscheck->filerestrict, (pl +2) * sizeof(char *), syscheck->filerestrict); syscheck->filerestrict[pl] = NULL; syscheck->filerestrict[pl + 1] = NULL; @@ -112,7 +113,7 @@ int read_reg(config *syscheck, char *entries) char **entry; char *tmp_str; - + /* Getting each entry separately */ entry = OS_StrBreak(',', entries, MAX_DIR_SIZE); /* Max number */ @@ -158,10 +159,10 @@ int read_reg(config *syscheck, char *entries) { int str_len_i; int str_len_dir; - + str_len_dir = strlen(tmp_entry); str_len_i = strlen(syscheck->registry[i]); - + if(str_len_dir > str_len_i) { str_len_dir = str_len_i; @@ -175,15 +176,15 @@ int read_reg(config *syscheck, char *entries) } i++; } - + /* Adding new entry */ dump_syscheck_entry(syscheck, tmp_entry, 0, 1, NULL); - - + + /* Next entry */ - entry++; + entry++; } - + return(1); } #endif /* For read_reg */ @@ -191,7 +192,7 @@ int read_reg(config *syscheck, char *entries) -/* Read directories attributes */ +/* Read directories attributes */ int read_attr(config *syscheck, char *dirs, char **g_attrs, char **g_values) { char *xml_check_all = "check_all"; @@ -210,6 +211,9 @@ int read_attr(config *syscheck, char *dirs, char **g_attrs, char **g_values) char **dir; char *tmp_str; dir = OS_StrBreak(',', dirs, MAX_DIR_SIZE); /* Max number */ + char **dir_org = dir; + + int ret = 0, i; /* Dir can not be null */ if(dir == NULL) @@ -227,7 +231,7 @@ int read_attr(config *syscheck, char *dirs, char **g_attrs, char **g_values) char **attrs = NULL; char **values = NULL; - + tmp_dir = *dir; restrictfile = NULL; @@ -256,7 +260,8 @@ int read_attr(config *syscheck, char *dirs, char **g_attrs, char **g_values) if(!g_attrs || !g_values) { merror(SYSCHECK_NO_OPT, ARGV0, dirs); - return(0); + ret = 0; + goto out_free; } attrs = g_attrs; @@ -282,7 +287,8 @@ int read_attr(config *syscheck, char *dirs, char **g_attrs, char **g_values) else { merror(SK_INV_OPT, ARGV0, *values, *attrs); - return(0); + ret = 0; + goto out_free; } } /* Checking sum */ @@ -299,7 +305,8 @@ int read_attr(config *syscheck, char *dirs, char **g_attrs, char **g_values) else { merror(SK_INV_OPT, ARGV0, *values, *attrs); - return(0); + ret = 0; + goto out_free; } } /* Checking md5sum */ @@ -315,7 +322,8 @@ int read_attr(config *syscheck, char *dirs, char **g_attrs, char **g_values) else { merror(SK_INV_OPT, ARGV0, *values, *attrs); - return(0); + ret = 0; + goto out_free; } } /* Checking sha1sum */ @@ -331,7 +339,8 @@ int read_attr(config *syscheck, char *dirs, char **g_attrs, char **g_values) else { merror(SK_INV_OPT, ARGV0, *values, *attrs); - return(0); + ret = 0; + goto out_free; } } /* Checking permission */ @@ -347,7 +356,8 @@ int read_attr(config *syscheck, char *dirs, char **g_attrs, char **g_values) else { merror(SK_INV_OPT, ARGV0, *values, *attrs); - return(0); + ret = 0; + goto out_free; } } /* Checking size */ @@ -363,7 +373,8 @@ int read_attr(config *syscheck, char *dirs, char **g_attrs, char **g_values) else { merror(SK_INV_OPT, ARGV0, *values, *attrs); - return(0); + ret = 0; + goto out_free; } } /* Checking owner */ @@ -379,7 +390,8 @@ int read_attr(config *syscheck, char *dirs, char **g_attrs, char **g_values) else { merror(SK_INV_OPT, ARGV0, *values, *attrs); - return(0); + ret = 0; + goto out_free; } } /* Checking group */ @@ -395,7 +407,8 @@ int read_attr(config *syscheck, char *dirs, char **g_attrs, char **g_values) else { merror(SK_INV_OPT, ARGV0, *values, *attrs); - return(0); + ret = 0; + goto out_free; } } else if(strcmp(*attrs, xml_real_time) == 0) @@ -410,7 +423,8 @@ int read_attr(config *syscheck, char *dirs, char **g_attrs, char **g_values) else { merror(SK_INV_OPT, ARGV0, *values, *attrs); - return(0); + ret = 0; + goto out_free; } } else if(strcmp(*attrs, xml_report_changes) == 0) @@ -425,7 +439,8 @@ int read_attr(config *syscheck, char *dirs, char **g_attrs, char **g_values) else { merror(SK_INV_OPT, ARGV0, *values, *attrs); - return(0); + ret = 0; + goto out_free; } } else if(strcmp(*attrs, xml_restrict) == 0) @@ -435,7 +450,8 @@ int read_attr(config *syscheck, char *dirs, char **g_attrs, char **g_values) else { merror(SK_INV_ATTR, ARGV0, *attrs); - return(0); + ret = 0; + goto out_free; } attrs++; values++; } @@ -446,20 +462,21 @@ int read_attr(config *syscheck, char *dirs, char **g_attrs, char **g_values) { merror(SYSCHECK_NO_OPT, ARGV0, dirs); if(restrictfile) free(restrictfile); - return(0); + ret = 0; + goto out_free; } - - + + /* Adding directory - looking for the last available */ i = 0; while(syscheck->dir && syscheck->dir[i]) { int str_len_i; int str_len_dir; - + str_len_dir = strlen(tmp_dir); str_len_i = strlen(syscheck->dir[i]); - + if(str_len_dir > str_len_i) { str_len_dir = str_len_i; @@ -469,7 +486,8 @@ int read_attr(config *syscheck, char *dirs, char **g_attrs, char **g_values) if(strcmp(syscheck->dir[i], tmp_dir) == 0) { merror(SK_DUP, ARGV0, tmp_dir); - return(1); + ret = 1; + goto out_free; } i++; @@ -488,21 +506,23 @@ int read_attr(config *syscheck, char *dirs, char **g_attrs, char **g_values) if(glob(tmp_dir, 0, NULL, &g) != 0) { merror(GLOB_ERROR, ARGV0, tmp_dir); - return(1); + ret = 1; + goto out_free; } if(g.gl_pathv[0] == NULL) { merror(GLOB_NFOUND, ARGV0, tmp_dir); - return(1); + ret = 1; + goto out_free; } - + while(g.gl_pathv[gindex]) { dump_syscheck_entry(syscheck, g.gl_pathv[gindex], opts, 0, restrictfile); gindex++; } - + globfree(&g); } @@ -519,13 +539,23 @@ int read_attr(config *syscheck, char *dirs, char **g_attrs, char **g_values) free(restrictfile); restrictfile = NULL; } - - + + /* Next entry */ - dir++; + dir++; } - - return(1); + + ret = 1; + +out_free: + + i = 0; + while(dir_org[i]) + free(dir_org[i++]); + + free(dir_org); + + return ret; } @@ -546,18 +576,19 @@ int Read_Syscheck(XML_NODE node, void *configp, void *mailp) char *xml_alert_new_files = "alert_new_files"; char *xml_disabled = "disabled"; char *xml_scan_on_start = "scan_on_start"; + char *xml_prefilter_cmd = "prefilter_cmd"; - /* Configuration example + /* Configuration example /etc,/usr/bin - /var/log */ config *syscheck; syscheck = (config *)configp; - - + + while(node[i]) { if(!node[i]->element) @@ -575,16 +606,16 @@ int Read_Syscheck(XML_NODE node, void *configp, void *mailp) else if(strcmp(node[i]->element,xml_directories) == 0) { char dirs[OS_MAXSTR]; - + #ifdef WIN32 ExpandEnvironmentStrings(node[i]->content, dirs, sizeof(dirs) -1); #else strncpy(dirs, node[i]->content, sizeof(dirs) -1); #endif - + if(!read_attr(syscheck, - dirs, - node[i]->attributes, + dirs, + node[i]->attributes, node[i]->values)) { return(OS_INVALID); @@ -602,7 +633,7 @@ int Read_Syscheck(XML_NODE node, void *configp, void *mailp) } /* Getting frequency */ else if(strcmp(node[i]->element,xml_time) == 0) - { + { if(!OS_StrIsNum(node[i]->content)) { merror(XML_VALUEERR,ARGV0,node[i]->element,node[i]->content); @@ -632,7 +663,7 @@ int Read_Syscheck(XML_NODE node, void *configp, void *mailp) return(OS_INVALID); } } - + /* Getting if xml_scan_on_start. */ else if(strcmp(node[i]->element, xml_scan_on_start) == 0) { @@ -646,7 +677,7 @@ int Read_Syscheck(XML_NODE node, void *configp, void *mailp) return(OS_INVALID); } } - + /* Getting if disabled. */ else if(strcmp(node[i]->element,xml_disabled) == 0) { @@ -660,7 +691,7 @@ int Read_Syscheck(XML_NODE node, void *configp, void *mailp) return(OS_INVALID); } } - + /* Getting file/dir ignore */ else if(strcmp(node[i]->element,xml_ignore) == 0) { @@ -670,22 +701,22 @@ int Read_Syscheck(XML_NODE node, void *configp, void *mailp) #ifdef WIN32 char *new_ig = NULL; os_calloc(2048, sizeof(char), new_ig); - - ExpandEnvironmentStrings(node[i]->content, new_ig, 2047); + + ExpandEnvironmentStrings(node[i]->content, new_ig, 2047); free(node[i]->content); node[i]->content = new_ig; #endif - + /* Adding if regex */ if(node[i]->attributes && node[i]->values) { if(node[i]->attributes[0] && node[i]->values[0] && - (strcmp(node[i]->attributes[0], "type") == 0) && + (strcmp(node[i]->attributes[0], "type") == 0) && (strcmp(node[i]->values[0], "sregex") == 0)) { OSMatch *mt_pt; - + if(!syscheck->ignore_regex) { os_calloc(2, sizeof(OSMatch *),syscheck->ignore_regex); @@ -702,7 +733,7 @@ int Read_Syscheck(XML_NODE node, void *configp, void *mailp) syscheck->ignore_regex); syscheck->ignore_regex[ign_size +1] = NULL; } - os_calloc(1, sizeof(OSMatch), + os_calloc(1, sizeof(OSMatch), syscheck->ignore_regex[ign_size]); if(!OSMatch_Compile(node[i]->content, @@ -735,7 +766,7 @@ int Read_Syscheck(XML_NODE node, void *configp, void *mailp) while(syscheck->ignore[ign_size] != NULL) ign_size++; - os_realloc(syscheck->ignore, + os_realloc(syscheck->ignore, sizeof(char *)*(ign_size +2), syscheck->ignore); syscheck->ignore[ign_size +1] = NULL; @@ -776,7 +807,7 @@ int Read_Syscheck(XML_NODE node, void *configp, void *mailp) syscheck->registry_ignore_regex); syscheck->registry_ignore_regex[ign_size +1] = NULL; } - + os_calloc(1, sizeof(OSMatch), syscheck->registry_ignore_regex[ign_size]); @@ -797,7 +828,7 @@ int Read_Syscheck(XML_NODE node, void *configp, void *mailp) } } /* We do not add duplicated entries */ - else if(!os_IsStrOnArray(node[i]->content, + else if(!os_IsStrOnArray(node[i]->content, syscheck->registry_ignore)) { if(!syscheck->registry_ignore) @@ -828,13 +859,41 @@ int Read_Syscheck(XML_NODE node, void *configp, void *mailp) { /* alert_new_files option is not read here. */ } + else if(strcmp(node[i]->element,xml_prefilter_cmd) == 0) + { + char cmd[OS_MAXSTR]; + struct stat statbuf; + + #ifdef WIN32 + ExpandEnvironmentStrings(node[i]->content, cmd, sizeof(cmd) -1); + #else + strncpy(cmd, node[i]->content, sizeof(cmd)-1); + #endif + + if (strlen(cmd) > 0) { + char statcmd[OS_MAXSTR]; + char *ix; + strncpy(statcmd, cmd, sizeof(statcmd)-1); + if (NULL != (ix = strchr(statcmd, ' '))) { *ix = '\0'; } + if (stat(statcmd, &statbuf) == 0) { + // More checks needed (perms, owner, etc.) + os_calloc(1, strlen(cmd)+1, syscheck->prefilter_cmd); + strncpy(syscheck->prefilter_cmd, cmd, strlen(cmd)); + } + else + { + merror(XML_VALUEERR,ARGV0, node[i]->element, node[i]->content); + return(OS_INVALID); + } + } + } else { merror(XML_INVELEM, ARGV0, node[i]->element); return(OS_INVALID); } i++; - } - + } + return(0); } diff --git a/src/config/syscheck-config.h b/src/config/syscheck-config.h index b380e8b..2417587 100755 --- a/src/config/syscheck-config.h +++ b/src/config/syscheck-config.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/config/syscheck-config.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation */ - + #ifndef __SYSCHECKC_H #define __SYSCHECKC_H @@ -42,43 +43,45 @@ typedef struct _rtfim typedef struct _config { - int tsleep; + int tsleep; /* sleep for sometime for daemon to settle */ int sleep_after; - int rootcheck; - int disabled; + int rootcheck; /* set to 0 when rootcheck is disabled */ + int disabled; /* is syscheck disabled? */ int scan_on_start; int realtime_count; - - int time; - int queue; - - int *opts; - char *workdir; + int time; /* frequency (secs) for syscheck to run */ + int queue; /* file descriptor of socket to write to queue */ + + int *opts; /* attributes set in the tag element */ + + char *workdir; /* set to the DEFAULTDIR (/var/ossec) */ char *remote_db; char *db; - char *scan_day; - char *scan_time; - - char **ignore; - void **ignore_regex; - - char **dir; + char *scan_day; /* run syscheck on this day */ + char *scan_time; /* run syscheck at this time */ + + char **ignore; /* list of files/dirs to ignore */ + void **ignore_regex; /* regex of files/dirs to ignore */ + + char **dir; /* array of directories to be scanned */ void **filerestrict; /* Windows only registry checking */ #ifdef WIN32 - char **registry_ignore; - void **registry_ignore_regex; - char **registry; + char **registry_ignore; /* list of registry entries to ignore */ + void **registry_ignore_regex; /* regex of registry entries to ignore */ + char **registry; /* array of registry entries to be scanned */ FILE *reg_fp; #endif - + void *fp; rtfim *realtime; + char *prefilter_cmd; + }config; #endif diff --git a/src/error_messages/error_messages.h b/src/error_messages/error_messages.h index eb1bd14..ca36538 100755 --- a/src/error_messages/error_messages.h +++ b/src/error_messages/error_messages.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/error_messages/error_messages.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -28,7 +29,7 @@ #define FOPEN_ERROR "%s(1103): ERROR: Unable to open file '%s'." #define SIZE_ERROR "%s(1104): ERROR: Maximum string size reached for: %s." #define NULL_ERROR "%s(1105): ERROR: Attempted to use null string. " -#define FORMAT_ERROR "%s(1106): ERROR: String not correctly formated." +#define FORMAT_ERROR "%s(1106): ERROR: String not correctly formated." #define MKDIR_ERROR "%s(1107): ERROR: Unable to create directory: '%s'" #define PERM_ERROR "%s(1108): ERROR: Permission error. Operation not completed." #define THREAD_ERROR "%s(1109): ERROR: Unable to create new pthread." @@ -97,6 +98,8 @@ #define IMSG_ERROR "%s(1222): ERROR: Invalid msg: %s" #define SNDMAIL_ERROR "%s(1223): ERROR: Error Sending email to %s (smtp server)" #define XML_INV_GRAN_MAIL "%s(1224): ERROR: Invalid 'email_alerts' config (missing parameters)." +#define CHLDWAIT_ERROR "%s(1261): ERROR: Waiting for child process. (status: %d)." +#define TOOMANY_WAIT_ERROR "%s(1262): ERROR: Too many errors waiting for child process(es)." /* rootcheck */ @@ -104,7 +107,7 @@ #define INVALID_RKCL_NAME "%s(1251): ERROR: Invalid rk configuration name: '%s'." #define INVALID_RKCL_VALUE "%s(1252): ERROR: Invalid rk configuration value: '%s'." #define INVALID_ROOTDIR "%s(1253): ERROR: Invalid rootdir (unable to retrieve)." -#define INVALID_RKCL_VAR "%s(1254): ERROR: Invalid rk variable: '%s'." +#define INVALID_RKCL_VAR "%s(1254): ERROR: Invalid rk variable: '%s'." /* syscheck */ @@ -126,6 +129,9 @@ #define INVALID_CAT "%s(1273): ERROR: Invalid category '%s' chosen." #define INVALID_CONFIG "%s(1274): ERROR: Invalid configuration. Element '%s': %s." #define INVALID_HOSTNAME "%s(1275): ERROR: Invalid hostname in syslog message: '%s'." +#ifdef GEOIP +#define INVALID_GEOIP_DB "%s(1276): ERROR: Cannot open GeoIP database: '%s'." +#endif /* Log collector */ @@ -142,7 +148,7 @@ #define AR_CMD_MISS "%s(1280): ERROR: Missing command options. " \ "You must specify a 'name', 'executable' and 'expect'." #define AR_MISS "%s(1281): ERROR: Missing options in the active response " \ - "configuration. " + "configuration. " #define ARQ_ERROR "%s(1301): ERROR: Unable to connect to active response queue." #define AR_INV_LOC "%s(1302): ERROR: Invalid active response location: '%s'." #define AR_INV_CMD "%s(1303): ERROR: Invalid command '%s' in the active response." @@ -193,7 +199,7 @@ #define ENCFILE_CHANGED "%s(1409): INFO: Authentication file changed. Updating." #define ENC_READ "%s(1410): INFO: Reading authentication keys file." - + /* Regex errors */ #define REGEX_COMPILE "%s(1450): ERROR: Syntax error on regex: '%s': %d." #define REGEX_SUBS "%s(1451): ERROR: Missing sub_strings on regex: '%s'." @@ -216,7 +222,7 @@ #define DUP_REGEX "%s(2109): ERROR: Duplicated offsets for same regex: '%s'." #define INV_DECOPTION "%s(2110): ERROR: Invalid decoder argument for %s: '%s'." #define DECODE_ADD "%s(2111): ERROR: Additional data to plugin decoder: '%s'." - + #define INV_OFFSET "%s(2120): ERROR: Invalid offset value: '%s'" #define INV_ATTR "%s(2121): ERROR: Invalid decoder attribute: '%s'" @@ -246,7 +252,7 @@ /* Rules reading errors */ -#define RL_INV_ROOT "%s(5101): ERROR: Invalid root element: '%s'." +#define RL_INV_ROOT "%s(5101): ERROR: Invalid root element: '%s'." #define RL_INV_RULE "%s(5102): ERROR: Invalid rule element: '%s'." #define RL_INV_ENTRY "%s(5103): ERROR: Invalid rule on '%s'. Missing id/level." #define RL_EMPTY_ATTR "%s(5104): ERROR: Rule attribute '%s' empty." @@ -273,7 +279,7 @@ #define DB_MISS_CONFIG "%s(5205): ERROR: Missing database configuration. "\ "It requires host, user, pass and database." #define DB_CONFIGERR "%s(5206): ERROR: Database configuration error." -#define DB_COMPILED "%s(5207): ERROR: OSSEC not compiled with support for '%s'." +#define DB_COMPILED "%s(5207): ERROR: OSSEC not compiled with support for '%s'." #define DB_MAINERROR "%s(5208): ERROR: Multiple database errors. Exiting." #define DB_CLOSING "%s(5209): INFO: Closing connection to database." #define DB_ATTEMPT "%s(5210): INFO: Attempting to reconnect to database." @@ -290,7 +296,7 @@ #define CONN_TO "%s: INFO: Connected to '%s' (%s queue)" #define MAIL_DIS "%s: INFO: E-Mail notification disabled. Clean Exit." - + /* Debug Messages */ #define STARTED_MSG "%s: DEBUG: Starting ..." #define FOUND_USER "%s: DEBUG: Found user/group ..." diff --git a/src/external/zlib-1.2.3/adler32.c b/src/external/zlib-1.2.3/adler32.c index 007ba26..c5bdc83 100755 --- a/src/external/zlib-1.2.3/adler32.c +++ b/src/external/zlib-1.2.3/adler32.c @@ -3,7 +3,8 @@ * For conditions of distribution and use, see copyright notice in zlib.h */ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/external/zlib-1.2.3/adler32.c, 2011/09/08 dcid Exp $ + */ #define ZLIB_INTERNAL #include "zlib.h" diff --git a/src/external/zlib-1.2.3/compress.c b/src/external/zlib-1.2.3/compress.c index ea739e0..262bbea 100755 --- a/src/external/zlib-1.2.3/compress.c +++ b/src/external/zlib-1.2.3/compress.c @@ -3,7 +3,8 @@ * For conditions of distribution and use, see copyright notice in zlib.h */ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/external/zlib-1.2.3/compress.c, 2011/09/08 dcid Exp $ + */ #define ZLIB_INTERNAL #include "zlib.h" diff --git a/src/external/zlib-1.2.3/crc32.c b/src/external/zlib-1.2.3/crc32.c index f658a9e..d979d2c 100755 --- a/src/external/zlib-1.2.3/crc32.c +++ b/src/external/zlib-1.2.3/crc32.c @@ -9,7 +9,8 @@ * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3. */ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/external/zlib-1.2.3/crc32.c, 2011/09/08 dcid Exp $ + */ /* Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore diff --git a/src/external/zlib-1.2.3/deflate.c b/src/external/zlib-1.2.3/deflate.c index 29ce1f6..0879f83 100755 --- a/src/external/zlib-1.2.3/deflate.c +++ b/src/external/zlib-1.2.3/deflate.c @@ -47,7 +47,8 @@ * */ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/external/zlib-1.2.3/deflate.c, 2011/09/08 dcid Exp $ + */ #include "deflate.h" diff --git a/src/external/zlib-1.2.3/deflate.h b/src/external/zlib-1.2.3/deflate.h index 05a5ab3..604002d 100755 --- a/src/external/zlib-1.2.3/deflate.h +++ b/src/external/zlib-1.2.3/deflate.h @@ -8,7 +8,8 @@ subject to change. Applications should only use zlib.h. */ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/external/zlib-1.2.3/deflate.h, 2011/09/08 dcid Exp $ + */ #ifndef DEFLATE_H #define DEFLATE_H diff --git a/src/external/zlib-1.2.3/gzio.c b/src/external/zlib-1.2.3/gzio.c index 7a664fc..3b016f6 100755 --- a/src/external/zlib-1.2.3/gzio.c +++ b/src/external/zlib-1.2.3/gzio.c @@ -5,7 +5,8 @@ * Compile this file with -DNO_GZCOMPRESS to avoid the compression code. */ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/external/zlib-1.2.3/gzio.c, 2011/09/08 dcid Exp $ + */ #include @@ -126,7 +127,7 @@ local gzFile gz_open (path, mode, fd) s->transparent = 0; path_size = strlen(path) +1; - + s->path = (char*)ALLOC(path_size +1); if (s->path == NULL) { return destroy(s), (gzFile)Z_NULL; @@ -1010,7 +1011,7 @@ const char * ZEXPORT gzerror (file, errnum) TRYFREE(s->msg); msg_size = strlen(s->path) + strlen(m) + 4; - + s->msg = (char*)ALLOC(msg_size +1); if (s->msg == Z_NULL) return (const char*)ERR_MSG(Z_MEM_ERROR); diff --git a/src/external/zlib-1.2.3/trees.c b/src/external/zlib-1.2.3/trees.c index 395e4e1..659349e 100755 --- a/src/external/zlib-1.2.3/trees.c +++ b/src/external/zlib-1.2.3/trees.c @@ -29,7 +29,8 @@ * Addison-Wesley, 1983. ISBN 0-201-06672-6. */ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/external/zlib-1.2.3/trees.c, 2011/09/08 dcid Exp $ + */ /* #define GEN_TREES_H */ diff --git a/src/external/zlib-1.2.3/uncompr.c b/src/external/zlib-1.2.3/uncompr.c index 41b78f7..3a39ec5 100755 --- a/src/external/zlib-1.2.3/uncompr.c +++ b/src/external/zlib-1.2.3/uncompr.c @@ -3,7 +3,8 @@ * For conditions of distribution and use, see copyright notice in zlib.h */ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/external/zlib-1.2.3/uncompr.c, 2011/09/08 dcid Exp $ + */ #define ZLIB_INTERNAL #include "zlib.h" diff --git a/src/external/zlib-1.2.3/zconf.h b/src/external/zlib-1.2.3/zconf.h index 03a9431..3ef5bf1 100755 --- a/src/external/zlib-1.2.3/zconf.h +++ b/src/external/zlib-1.2.3/zconf.h @@ -3,7 +3,8 @@ * For conditions of distribution and use, see copyright notice in zlib.h */ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/external/zlib-1.2.3/zconf.h, 2011/09/08 dcid Exp $ + */ #ifndef ZCONF_H #define ZCONF_H diff --git a/src/external/zlib-1.2.3/zconf.in.h b/src/external/zlib-1.2.3/zconf.in.h index 03a9431..1b8ff9e 100755 --- a/src/external/zlib-1.2.3/zconf.in.h +++ b/src/external/zlib-1.2.3/zconf.in.h @@ -3,7 +3,8 @@ * For conditions of distribution and use, see copyright notice in zlib.h */ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/external/zlib-1.2.3/zconf.in.h, 2011/09/08 dcid Exp $ + */ #ifndef ZCONF_H #define ZCONF_H diff --git a/src/external/zlib-1.2.3/zutil.c b/src/external/zlib-1.2.3/zutil.c index d55f594..0c8d520 100755 --- a/src/external/zlib-1.2.3/zutil.c +++ b/src/external/zlib-1.2.3/zutil.c @@ -3,7 +3,8 @@ * For conditions of distribution and use, see copyright notice in zlib.h */ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/external/zlib-1.2.3/zutil.c, 2011/09/08 dcid Exp $ + */ #include "zutil.h" diff --git a/src/external/zlib-1.2.3/zutil.h b/src/external/zlib-1.2.3/zutil.h index b7d5eff..f967580 100755 --- a/src/external/zlib-1.2.3/zutil.h +++ b/src/external/zlib-1.2.3/zutil.h @@ -8,7 +8,8 @@ subject to change. Applications should only use zlib.h. */ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/external/zlib-1.2.3/zutil.h, 2011/09/08 dcid Exp $ + */ #ifndef ZUTIL_H #define ZUTIL_H diff --git a/src/headers/agent_op.h b/src/headers/agent_op.h index 9b53ea4..fdce89d 100755 --- a/src/headers/agent_op.h +++ b/src/headers/agent_op.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/headers/agent_op.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -11,7 +12,7 @@ #ifndef __AGENT_OP_H -#define __AGENT_OP_H +#define __AGENT_OP_H @@ -47,12 +48,21 @@ char *os_read_agent_ip(); */ char *os_read_agent_id(); +/* cmoraes: added */ + +/** char *os_read_agent_profile() + * Reads the agent profile name for the current agent. + * Returns NULL on error. + */ +char *os_read_agent_profile(); + /** int os_write_agent_info(char *agent_name, char *agent_ip, char *agent_id) * Writes the agent info inside the queue, for the other processes to read. * Returns 1 on success or <= 0 on failure. */ -int os_write_agent_info(char *agent_name, char *agent_ip, char *agent_id); +int os_write_agent_info(char *agent_name, char *agent_ip, char *agent_id, + char *cfg_profile_name); /*cmoraes*/ int os_agent_config_changed(); diff --git a/src/headers/ar.h b/src/headers/ar.h index 03b61a1..699c114 100755 --- a/src/headers/ar.h +++ b/src/headers/ar.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/headers/ar.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. diff --git a/src/headers/debug_op.h b/src/headers/debug_op.h index b35e73d..52b9f18 100755 --- a/src/headers/debug_op.h +++ b/src/headers/debug_op.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/headers/debug_op.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -57,7 +58,7 @@ void nowDaemon(); int isChroot(); /* Debug analysisd */ -#ifdef DEBUGAD +#ifdef DEBUGAD #define DEBUG_MSG(x,y,z) verbose(x,y,z) #else #define DEBUG_MSG(x,y,z) diff --git a/src/headers/defs.h b/src/headers/defs.h index 9a9e5c4..8fa06a6 100755 --- a/src/headers/defs.h +++ b/src/headers/defs.h @@ -1,6 +1,7 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/headers/defs.h, 2012/08/11 dcid Exp $ + */ -/* Copyright (C) 2009 Trend Micro Inc. +/* Copyright (C) 2009-2012 Trend Micro Inc. * All rights reserved. * * This program is a free software; you can redistribute it @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -21,6 +22,11 @@ #define __OS_HEADERS +/* TRUE / FALSE definitions + */ +#define TRUE 1 +#define FALSE 0 + /* Read / Write definitions */ #define READ 1 @@ -46,7 +52,7 @@ /* Some Global names */ #define __name "OSSEC HIDS" -#define __version "v2.5.1" +#define __version "v2.7" #define __author "Trend Micro Inc." #define __contact "contact@ossec.net" #define __site "http://www.ossec.net" @@ -63,17 +69,17 @@ http://www.ossec.net/main/license/\n" #define MAX_PID 32768 #endif - + /* Max limit of 256 agents */ #ifndef MAX_AGENTS #define MAX_AGENTS 256 -#endif +#endif /* manager notification */ #define NOTIFY_TIME 600 /* every 10 minutes */ - + /* User Configuration */ #ifndef MAILUSER #define MAILUSER "ossecm" @@ -82,15 +88,15 @@ http://www.ossec.net/main/license/\n" #ifndef USER #define USER "ossec" #endif - + #ifndef REMUSER #define REMUSER "ossecr" #endif - + #ifndef GROUPGLOBAL #define GROUPGLOBAL "ossec" -#endif - +#endif + #ifndef DEFAULTDIR #define DEFAULTDIR "/var/ossec" #endif @@ -111,7 +117,7 @@ http://www.ossec.net/main/license/\n" #define AR_BINDIR "active-response/bin" #define AGENTCONFIG "shared/agent.conf" #define AGENTCONFIGINT "shared/agent.conf" -#endif +#endif /* Exec queue */ @@ -126,7 +132,7 @@ http://www.ossec.net/main/license/\n" #define XML_DECODER "/etc/decoder.xml" #define XML_LDECODER "/etc/local_decoder.xml" - + /* Agent information location */ #define AGENTINFO_DIR "/queue/agent-info" @@ -178,14 +184,14 @@ http://www.ossec.net/main/license/\n" #else #define SYSCHECK_RESTART "syscheck/.syscheck_run" #define SYSCHECK_RESTART_PATH "syscheck/.syscheck_run" -#endif +#endif + - -/* Agentless directories. */ +/* Agentless directories. */ #define AGENTLESSDIR "/agentless" #define AGENTLESSPASS "/agentless/.passlist" #define AGENTLESS_ENTRYDIR "/queue/agentless" - + /* Internal definitions files */ #ifndef WIN32 @@ -230,8 +236,8 @@ http://www.ossec.net/main/license/\n" #ifndef WIN32 #define SHAREDCFG_DIR "/etc/shared" #else - #define SHAREDCFG_DIR "shared" -#endif + #define SHAREDCFG_DIR "shared" +#endif /* Built in defines */ #define DEFAULTQPATH DEFAULTDIR DEFAULTQUEUE diff --git a/src/headers/dirtree_op.h b/src/headers/dirtree_op.h index c154982..7563a79 100755 --- a/src/headers/dirtree_op.h +++ b/src/headers/dirtree_op.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/headers/dirtree_op.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -11,9 +12,9 @@ * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ - + /* Common API for dealing with directory trees */ - + #ifndef _OS_DIRTREE #define _OS_DIRTREE @@ -22,7 +23,7 @@ typedef struct _OSTreeNode { struct _OSTreeNode *next; void *child; - + char *value; void *data; }OSTreeNode; @@ -38,7 +39,7 @@ typedef struct _OSDirTree OSDirTree *OSDirTree_Create(); void OSDirTree_AddToTree(OSDirTree *tree, char *str, void *data, char sep); void *OSDirTree_SearchTree(OSDirTree *tree, char *str, char sep); - + #endif diff --git a/src/headers/file-queue.h b/src/headers/file-queue.h index b3f85e4..0865a8f 100755 --- a/src/headers/file-queue.h +++ b/src/headers/file-queue.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/headers/file-queue.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -24,10 +25,10 @@ typedef struct _file_queue int year; int day; int flags; - + char mon[4]; char file_name[MAX_FQUEUE +1]; - + FILE *fp; struct stat f_status; }file_queue; diff --git a/src/headers/file_op.h b/src/headers/file_op.h index 7d03cf1..7b07c4a 100755 --- a/src/headers/file_op.h +++ b/src/headers/file_op.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/headers/file_op.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. diff --git a/src/headers/hash_op.h b/src/headers/hash_op.h index 0ea3fe9..9b0777a 100755 --- a/src/headers/hash_op.h +++ b/src/headers/hash_op.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/headers/hash_op.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -11,9 +12,9 @@ * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ - + /* Common API for dealing with directory trees */ - + #ifndef _OS_HASHOP #define _OS_HASHOP @@ -23,9 +24,9 @@ typedef struct _OSHashNode { struct _OSHashNode *next; - + void *key; - void *data; + void *data; }OSHashNode; @@ -34,7 +35,7 @@ typedef struct _OSHash unsigned int rows; unsigned int initial_seed; unsigned int constant; - + OSHashNode **table; }OSHash; @@ -54,7 +55,7 @@ OSHash *OSHash_Create(); * Frees the memory used by the hash. */ void *OSHash_Free(OSHash *self); - + /** void OSHash_Add(OSHash *hash, char *key, void *data) @@ -64,6 +65,7 @@ void *OSHash_Free(OSHash *self); * Key must not be NULL. */ int OSHash_Add(OSHash *hash, char *key, void *data); +int OSHash_Update(OSHash *hash, char *key, void *data); /** void *OSHash_Get(OSHash *self, char *key) diff --git a/src/headers/help.h b/src/headers/help.h index 19a4cd1..e6ad433 100755 --- a/src/headers/help.h +++ b/src/headers/help.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/headers/help.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. diff --git a/src/headers/list_op.h b/src/headers/list_op.h index d93c554..d395099 100755 --- a/src/headers/list_op.h +++ b/src/headers/list_op.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/headers/list_op.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -28,7 +29,7 @@ typedef struct _OSList OSListNode *first_node; OSListNode *last_node; OSListNode *cur_node; - + int currently_size; int max_size; diff --git a/src/headers/math_op.h b/src/headers/math_op.h index 7654aba..e5840d9 100755 --- a/src/headers/math_op.h +++ b/src/headers/math_op.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/headers/math_op.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -21,7 +22,7 @@ * Get the first available prime after the provided value. * Returns 0 on error. */ -int os_getprime(int val); +int os_getprime(int val); #endif diff --git a/src/headers/mem_op.h b/src/headers/mem_op.h index d135fbe..4da491c 100755 --- a/src/headers/mem_op.h +++ b/src/headers/mem_op.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/headers/mem_op.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. diff --git a/src/headers/mq_op.h b/src/headers/mq_op.h index c7ef5ad..a0c16c0 100755 --- a/src/headers/mq_op.h +++ b/src/headers/mq_op.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/headers/mq_op.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. diff --git a/src/headers/os_err.h b/src/headers/os_err.h index 65f287c..681ed0a 100755 --- a/src/headers/os_err.h +++ b/src/headers/os_err.h @@ -1,11 +1,12 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/headers/os_err.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * * This program is a free software; you can redistribute it * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software + * License (version 2) as published by the FSF - Free Software * Foundation */ diff --git a/src/headers/privsep_op.h b/src/headers/privsep_op.h index eb29313..7a44d2f 100755 --- a/src/headers/privsep_op.h +++ b/src/headers/privsep_op.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/headers/privsep_op.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. diff --git a/src/headers/pthreads_op.h b/src/headers/pthreads_op.h index cdb4026..409be20 100755 --- a/src/headers/pthreads_op.h +++ b/src/headers/pthreads_op.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/headers/pthreads_op.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. diff --git a/src/headers/rc.h b/src/headers/rc.h index 61e67d0..f71a0c4 100755 --- a/src/headers/rc.h +++ b/src/headers/rc.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/headers/rc.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -22,7 +23,7 @@ #define IsValidHeader(str) ((str[0] == '#') && \ (str[1] == '!') && \ (str[2] == '-') && \ - (str+=3) ) + (str+=3) ) /* Exec message */ diff --git a/src/headers/read-agents.h b/src/headers/read-agents.h index a0a26c3..a450b72 100755 --- a/src/headers/read-agents.h +++ b/src/headers/read-agents.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/headers/read-agents.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -29,7 +30,7 @@ typedef struct _agent_info /* Print syscheck db (of modified files). */ -int print_syscheck(char *sk_name, char *sk_ip, char *fname, int print_registry, +int print_syscheck(char *sk_name, char *sk_ip, char *fname, int print_registry, int all_files, int csv_output, int update_counter); /* Print rootcheck db. */ @@ -51,7 +52,7 @@ char **get_agents(int flag); /* Free the agent list */ void free_agents(char **agent_list); -/** char *print_agent_status(int status) +/** char *print_agent_status(int status) * Prints the text representation of the agent status. */ char *print_agent_status(int status); @@ -65,7 +66,7 @@ int get_agent_status(char *agent_name, char *agent_ip); * Get information from an agent. */ agent_info *get_agent_info(char *agent_name, char *agent_ip); - + /** int connect_to_remoted() * Connects to remoted to be able to send messages to the agents. @@ -76,15 +77,15 @@ int connect_to_remoted(); /** int send_msg_to_agent(int socket, char *msg) * Sends a message to an agent. * returns -1 on error. - */ + */ int send_msg_to_agent(int msocket, char *msg, char *agt_id, char *exec); - + #define GA_NOTACTIVE 2 #define GA_ACTIVE 3 -#define GA_ALL 5 +#define GA_ALL 5 #define GA_ALL_WSTATUS 7 /* Status */ diff --git a/src/headers/read-alert.h b/src/headers/read-alert.h index 83bcd26..48b415f 100755 --- a/src/headers/read-alert.h +++ b/src/headers/read-alert.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/headers/read-alert.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -14,7 +15,7 @@ #ifndef __CRALERT_H #define __CRALERT_H -#define CRALERT_MAIL_SET 0x001 +#define CRALERT_MAIL_SET 0x001 #define CRALERT_EXEC_SET 0x002 #define CRALERT_READ_ALL 0x004 #define CRALERT_FP_SET 0x010 @@ -25,13 +26,26 @@ typedef struct _alert_data { int rule; int level; + char *alertid; char *date; char *location; char *comment; char *group; char *srcip; + int srcport; + char *dstip; + int dstport; char *user; + char *filename; + char *old_md5; + char *new_md5; + char *old_sha1; + char *new_sha1; char **log; +#ifdef GEOIP + char *geoipdatasrc; + char *geoipdatadst; +#endif }alert_data; diff --git a/src/headers/regex_op.h b/src/headers/regex_op.h index 05cca8f..8fde0d6 100755 --- a/src/headers/regex_op.h +++ b/src/headers/regex_op.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/headers/regex_op.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. diff --git a/src/headers/report_op.h b/src/headers/report_op.h index 9218e2f..a19ec93 100755 --- a/src/headers/report_op.h +++ b/src/headers/report_op.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/headers/report_op.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -14,10 +15,10 @@ #define __REPORT_OP_H -#define REPORT_RELATED 1 +#define REPORT_RELATED 1 #define REPORT_FILTER 2 - + #define REPORT_REL_USER 0x001 #define REPORT_REL_SRCIP 0x002 #define REPORT_REL_LEVEL 0x004 @@ -25,7 +26,8 @@ #define REPORT_REL_GROUP 0x020 #define REPORT_REL_LOCATION 0x040 #define REPORT_TYPE_DAILY 0x100 - +#define REPORT_REL_FILE 0x200 + typedef struct _report_filter @@ -38,6 +40,7 @@ typedef struct _report_filter char *location; char *user; char *srcip; + char *files; char *filename; void *top_user; @@ -46,8 +49,10 @@ typedef struct _report_filter void *top_rule; void *top_group; void *top_location; + void *top_files; int related_user; + int related_file; int related_srcip; int related_level; int related_rule; @@ -57,13 +62,13 @@ typedef struct _report_filter int report_type; int show_alerts; void *fp; - + }report_filter; -int os_report_configfilter(char *filter_by, char *filter_value, +int os_report_configfilter(char *filter_by, char *filter_value, report_filter *r_filter, int arg_type); void os_report_printtop(void *topstore, char *hname, int print_related); void os_ReportdStart(report_filter *r_filter); diff --git a/src/headers/rules_op.h b/src/headers/rules_op.h index dd03e63..1b80e08 100755 --- a/src/headers/rules_op.h +++ b/src/headers/rules_op.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/headers/rules_op.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -11,9 +12,9 @@ * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ - + /* Common API for dealing with directory trees */ - + #ifndef _OS_RULESOP_H #define _OS_RULESOP_H @@ -93,7 +94,7 @@ typedef struct _RuleInfo int __frequency; char **last_events; - + /* Not an option in the rule */ u_int16_t alert_opts; @@ -103,7 +104,7 @@ typedef struct _RuleInfo /* category */ u_int8_t category; - + /* Decoded as */ u_int16_t decoded_as; @@ -125,7 +126,7 @@ typedef struct _RuleInfo /* Function pointer to the event_search. */ void *(*event_search)(void *lf, void *rule); - + char *group; OSMatch *match; @@ -147,11 +148,11 @@ typedef struct _RuleInfo OSMatch *program_name; OSMatch *extra_data; char *action; - + char *comment; /* description in the xml */ char *info; char *cve; - + char *if_sid; char *if_level; char *if_group; @@ -159,14 +160,14 @@ typedef struct _RuleInfo OSRegex *if_matched_regex; OSMatch *if_matched_group; int if_matched_sid; - + void **ar; }RuleInfo; /** Prototypes **/ -int OS_ReadXMLRules(char *rulefile, +int OS_ReadXMLRules(char *rulefile, void *(*ruleact_function)(RuleInfo *rule, void *data), void *data); diff --git a/src/headers/sec.h b/src/headers/sec.h index 4c59c7d..841492f 100755 --- a/src/headers/sec.h +++ b/src/headers/sec.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/headers/sec.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -21,7 +22,7 @@ typedef struct _keyentry unsigned int local; unsigned int keyid; unsigned int global; - + char *id; char *key; char *name; @@ -37,8 +38,8 @@ typedef struct _keystore { /* Array with all the keys */ keyentry **keyentries; - - + + /* Hashes, based on the id/ip to lookup the keys. */ void *keyhash_id; void *keyhash_ip; @@ -66,7 +67,7 @@ void OS_FreeKeys(keystore *keys); /* Checks if key changed. */ int OS_CheckUpdateKeys(keystore *keys); - + /* Update the keys if they changed on the system. */ int OS_UpdateKeys(keystore *keys); @@ -97,7 +98,7 @@ int OS_IsAllowedDynamicID(keystore *keys, char *id, char *srcip); /** Function prototypes -- send/recv messages **/ /* Decrypt and decompress a remote message. */ -char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, +char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, int id, int buffer_size); /* Creates an ossec message (encrypts and compress) */ @@ -114,7 +115,7 @@ int CreateSecMSG(keystore *keys, char *msg, char *msg_encrypted, int id); #endif #define SENDER_COUNTER "sender_counter" -#define KEYSIZE 128 +#define KEYSIZE 128 #endif diff --git a/src/headers/shared.h b/src/headers/shared.h index 4165c5b..fe2827c 100755 --- a/src/headers/shared.h +++ b/src/headers/shared.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/headers/shared.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -18,7 +19,7 @@ * The stack smashing protector defeats some BoF via: gcc -fstack-protector * Reference: http://gcc.gnu.org/onlinedocs/gcc-4.1.2/cpp.pdf */ - + #if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 1) && (__GNUC_PATCHLEVEL__ >= 2)) || \ ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 2)) || \ (__GNUC__ >= 5)) @@ -82,6 +83,8 @@ #include #include #include +#include +#include #endif #include @@ -175,7 +178,7 @@ char *__local_name; /*** These functions will exit on error. No need to check return code ***/ /* for calloc: x = calloc(4,sizeof(char)) -> os_calloc(4,sizeof(char),x) */ -#define os_calloc(x,y,z) (z = calloc(x,y))?(void)1:ErrorExit(MEM_ERROR, ARGV0) +#define os_calloc(x,y,z) (z = calloc(x,y))?(void)1:ErrorExit(MEM_ERROR, ARGV0) #define os_strdup(x,y) (y = strdup(x))?(void)1:ErrorExit(MEM_ERROR, ARGV0) @@ -190,9 +193,9 @@ char *__local_name; #ifdef CLIENT #define isAgent 1 #else - #define isAgent 0 + #define isAgent 0 #endif - + #include "debug_op.h" @@ -216,6 +219,7 @@ char *__local_name; #include "file-queue.h" #include "read-agents.h" #include "report_op.h" +#include "string_op.h" #include "os_xml/os_xml.h" #include "os_regex/os_regex.h" @@ -224,5 +228,5 @@ char *__local_name; #endif /* __SHARED_H */ - + /* EOF */ diff --git a/src/headers/sig_op.h b/src/headers/sig_op.h index d2ce0f8..e017849 100755 --- a/src/headers/sig_op.h +++ b/src/headers/sig_op.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/headers/sig_op.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. diff --git a/src/headers/store_op.h b/src/headers/store_op.h index 4ae7d3a..a8e155b 100755 --- a/src/headers/store_op.h +++ b/src/headers/store_op.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/headers/store_op.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -41,7 +42,7 @@ typedef struct _OSStore OSStore *OSStore_Create(); OSStore *OSStore_Free(OSStore *list); - + int OSStore_Put(OSStore *list, char *key, void *data); int OSStore_Check(OSStore *list, char *key); int OSStore_NCheck(OSStore *list, char *key); @@ -50,7 +51,7 @@ int OSStore_GetPosition(OSStore *list, char *key); void *OSStore_Get(OSStore *list, char *key); OSStoreNode *OSStore_GetFirstNode(OSStore *list); int OSStore_Sort(OSStore *list, void*(sort_data_function)(void *d1, void *d2)); - + #endif diff --git a/src/headers/string_op.h b/src/headers/string_op.h new file mode 100755 index 0000000..2df963e --- /dev/null +++ b/src/headers/string_op.h @@ -0,0 +1,34 @@ +/* @(#) $Id: ./src/headers/string_op.h, 2011/09/08 dcid Exp $ + */ + +/* Copyright (C) 2009 Trend Micro Inc. + * All rights reserved. + * + * This program is a free software; you can redistribute it + * and/or modify it under the terms of the GNU General Public + * License (version 2) as published by the FSF - Free Software + * Foundation + * + * License details at the LICENSE file included with OSSEC or + * online at: http://www.ossec.net/en/licensing.html + */ + + +#ifndef H_STRINGOP_OS +#define H_STRINGOP_OS + + +/** os_trimcrlf + * Trims the cr and/or LF from the last positions of a string + */ +void os_trimcrlf(char *str); + +/* Similiar to Perl's substr() function */ +int os_substr(char *dest, const char *src, int position, int length); + +/* Remove a character from a string */ +char *os_strip_char(char *source, char remove); + +#endif + +/* EOF */ diff --git a/src/headers/validate_op.h b/src/headers/validate_op.h index e8e7094..ade6afa 100755 --- a/src/headers/validate_op.h +++ b/src/headers/validate_op.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/headers/validate_op.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -42,7 +43,7 @@ int getDefine_Int(char *high_name, char *low_name, int min, int max); */ int OS_IPFound(char *ip_address, os_ip *that_ip); - + /** int OS_IPFoundList(char *ip_address, char **list_of_ips) * Checks if ip_address is present on the "list_of_ips". @@ -60,8 +61,8 @@ int OS_IPFoundList(char *ip_address, os_ip **list_of_ips); * ** On success this function may modify the value of ip_address */ int OS_IsValidIP(char *ip_address, os_ip *final_ip); - - + + /** Time range validations **/ /** char *OS_IsValidTime(char *time_str) @@ -77,9 +78,9 @@ int OS_IsValidIP(char *ip_address, os_ip *final_ip); * hh:mm am - hh:mm pm (12 hour format) * hh am - hh pm (12 hour format) */ -char *OS_IsValidTime(char *time_str); +char *OS_IsValidTime(char *time_str); -/* Same as above, but only accepts a unique time, not a range. */ +/* Same as above, but only accepts a unique time, not a range. */ char *OS_IsValidUniqueTime(char *time_str); @@ -103,7 +104,7 @@ int OS_IsAfterTime(char *time_str, char *ossec_time); * range. */ int OS_IsonDay(int week_day, char *ossec_day); - + /** char *OS_IsValidDay(char *day_str) * Validates if an day is in an acceptable format @@ -123,7 +124,7 @@ char *OS_IsValidDay(char *day_str); /* Checks if the ip is a single host, not a network with a netmask */ #define isSingleHost(x) (x->netmask == 0xFFFFFFFF) - + #endif /* EOF */ diff --git a/src/headers/wait_op.h b/src/headers/wait_op.h index 1755b8f..8d1c4fe 100755 --- a/src/headers/wait_op.h +++ b/src/headers/wait_op.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/headers/wait_op.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -10,7 +11,7 @@ */ #ifndef __WAIT_OP_H -#define __WAIT_OP_H +#define __WAIT_OP_H void os_setwait(); diff --git a/src/init/init.sh b/src/init/init.sh index 7be15f2..fb39d9e 100755 --- a/src/init/init.sh +++ b/src/init/init.sh @@ -128,7 +128,7 @@ runInit() elif [ -d "/etc/init.d" -a -f "/usr/sbin/update-rc.d" ]; then echo " - ${systemis} Debian (Ubuntu or derivative)." echo " - ${modifiedinit}" - cp -pr ./src/init/ossec-hids.init /etc/init.d/ossec + cp -pr ./src/init/ossec-hids-debian.init /etc/init.d/ossec chmod +x /etc/init.d/ossec chmod go-w /etc/init.d/ossec chown root:ossec /etc/init.d/ossec diff --git a/src/init/ossec-client.sh b/src/init/ossec-client.sh index f8d6159..3a27bab 100755 --- a/src/init/ossec-client.sh +++ b/src/init/ossec-client.sh @@ -11,7 +11,7 @@ DIR=`dirname $PWD`; ### Do not modify bellow here ### NAME="OSSEC HIDS" -VERSION="v2.5.1" +VERSION="v2.7" AUTHOR="Trend Micro Inc." DAEMONS="ossec-logcollector ossec-syscheckd ossec-agentd ossec-execd" @@ -226,6 +226,12 @@ case "$1" in restart) testconfig stopa + sleep 1; + start + ;; + reload) + DAEMONS="ossec-logcollector ossec-syscheckd ossec-agentd" + stopa start ;; status) @@ -237,3 +243,4 @@ case "$1" in *) help esac + diff --git a/src/init/ossec-hids-debian.init b/src/init/ossec-hids-debian.init new file mode 100755 index 0000000..0e25549 --- /dev/null +++ b/src/init/ossec-hids-debian.init @@ -0,0 +1,57 @@ +#!/bin/sh +# OSSEC Controls OSSEC HIDS +# Author: Daniel B. Cid +# Modified for Debian by Michael Starks (patch by Costas Drogos) + +### BEGIN INIT INFO +# Provides: ossec +# Required-Start: $remote_fs $syslog +# Required-Stop: $remote_fs $syslog +# Should-Start: $network +# Should-Stop: $network +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Start and stop OSSEC HIDS +# Description: Controls OSSEC HIDS daemons +# +### END INIT INFO + +. /etc/ossec-init.conf +if [ "X${DIRECTORY}" = "X" ]; then + DIRECTORY="/var/ossec" +fi + + +start() { + ${DIRECTORY}/bin/ossec-control start +} + +stop() { + ${DIRECTORY}/bin/ossec-control stop +} + +status() { + ${DIRECTORY}/bin/ossec-control status +} + + +case "$1" in + start) + start + ;; + stop) + stop + ;; + restart) + stop + start + ;; + status) + status + ;; + *) + echo "*** Usage: $0 {start|stop|restart|status}" + exit 1 +esac + +exit 0 diff --git a/src/init/ossec-hids-rh.init b/src/init/ossec-hids-rh.init index 2ce397b..0b2ff89 100755 --- a/src/init/ossec-hids-rh.init +++ b/src/init/ossec-hids-rh.init @@ -46,6 +46,8 @@ stop() { status() { ${DIRECTORY}/bin/ossec-control status + RETVAL=$? + return $RETVAL } diff --git a/src/init/ossec-local.sh b/src/init/ossec-local.sh index 12f5196..1fd9cb0 100755 --- a/src/init/ossec-local.sh +++ b/src/init/ossec-local.sh @@ -22,7 +22,7 @@ fi NAME="OSSEC HIDS" -VERSION="v2.5.1" +VERSION="v2.7" AUTHOR="Trend Micro Inc." DAEMONS="ossec-monitord ossec-logcollector ossec-syscheckd ossec-analysisd ossec-maild ossec-execd ${DB_DAEMON} ${CSYSLOG_DAEMON} ${AGENTLESS_DAEMON}" @@ -177,14 +177,17 @@ disable() # Status function status() { + RETVAL=0 for i in ${DAEMONS}; do pstatus ${i}; if [ $? = 0 ]; then + RETVAL=1 echo "${i} not running..." else echo "${i} is running..." fi - done + done + exit $RETVAL } testconfig() @@ -207,9 +210,10 @@ start() SDAEMONS="${DB_DAEMON} ${CSYSLOG_DAEMON} ${AGENTLESS_DAEMON} ossec-maild ossec-execd ossec-analysisd ossec-logcollector ossec-syscheckd ossec-monitord" echo "Starting $NAME $VERSION (by $AUTHOR)..." - ${DIR}/bin/ossec-logtest -t + echo | ${DIR}/bin/ossec-logtest > /dev/null 2>&1; if [ ! $? = 0 ]; then echo "ossec-analysisd: Configuration error. Exiting." + exit 1; fi lock; @@ -237,6 +241,14 @@ start() # to internally create their PID files. sleep 2; unlock; + + ls -la "${DIR}/ossec-agent/" >/dev/null 2>&1 + if [ $? = 0 ]; then + echo "" + echo "Starting sub agent directory (for hybrid mode)" + ${DIR}/ossec-agent/bin/ossec-control start + fi + echo "Completed." } @@ -291,6 +303,13 @@ stopa() done unlock; + + ls -la "${DIR}/ossec-agent/" >/dev/null 2>&1 + if [ $? = 0 ]; then + echo "" + echo "Stopping sub agent directory (for hybrid mode)" + ${DIR}/ossec-agent/bin/ossec-control stop + fi echo "$NAME $VERSION Stopped" } @@ -308,6 +327,7 @@ case "$1" in restart) testconfig stopa + sleep 1; start ;; status) diff --git a/src/init/ossec-server.sh b/src/init/ossec-server.sh index c7f34f9..d07993b 100755 --- a/src/init/ossec-server.sh +++ b/src/init/ossec-server.sh @@ -22,7 +22,7 @@ fi NAME="OSSEC HIDS" -VERSION="v2.5.1" +VERSION="v2.7" AUTHOR="Trend Micro Inc." DAEMONS="ossec-monitord ossec-logcollector ossec-remoted ossec-syscheckd ossec-analysisd ossec-maild ossec-execd ${DB_DAEMON} ${CSYSLOG_DAEMON} ${AGENTLESS_DAEMON}" @@ -177,14 +177,17 @@ disable() # Status function status() { + RETVAL=0 for i in ${DAEMONS}; do pstatus ${i}; if [ $? = 0 ]; then echo "${i} not running..." + RETVAL=1 else echo "${i} is running..." fi - done + done + exit $RETVAL } testconfig() @@ -206,9 +209,10 @@ start() SDAEMONS="${DB_DAEMON} ${CSYSLOG_DAEMON} ${AGENTLESS_DAEMON} ossec-maild ossec-execd ossec-analysisd ossec-logcollector ossec-remoted ossec-syscheckd ossec-monitord" echo "Starting $NAME $VERSION (by $AUTHOR)..." - ${DIR}/bin/ossec-logtest -t + echo | ${DIR}/bin/ossec-logtest > /dev/null 2>&1; if [ ! $? = 0 ]; then - echo "ossec-analysisd: Configuration error. Exiting." + echo "OSSEC analysisd: Testing rules failed. Configuration error. Exiting." + exit 1; fi lock; checkpid; @@ -306,8 +310,14 @@ case "$1" in restart) testconfig stopa + sleep 1; start ;; + reload) + DAEMONS="ossec-monitord ossec-logcollector ossec-remoted ossec-syscheckd ossec-analysisd ossec-maild ${DB_DAEMON} ${CSYSLOG_DAEMON} ${AGENTLESS_DAEMON}" + stopa + start + ;; status) status ;; diff --git a/src/init/update.sh b/src/init/update.sh index a822f3a..61ff28e 100755 --- a/src/init/update.sh +++ b/src/init/update.sh @@ -17,6 +17,7 @@ isUpdate() if [ $? = 0 ]; then . ${OSSEC_INIT} if [ "X$DIRECTORY" = "X" ]; then + echo "# ($FUNCNAME) ERROR: The variable DIRECTORY wasn't set" 1>&2 echo "${FALSE}" return 1; fi @@ -24,30 +25,31 @@ isUpdate() if [ $? = 0 ]; then echo "${TRUE}" return 0; - fi + fi fi - echo "${FALSE}" - return 1; + return 1; } ########## -# doUpdatecleanup +# doUpdatecleanup ########## doUpdatecleanup() { . ${OSSEC_INIT} if [ "X$DIRECTORY" = "X" ]; then - # Invalid ossec init file. Unable to update + echo "# ($FUNCNAME) ERROR: The variable DIRECTORY wasn't set." 1>&2 echo "${FALSE}" return 1; fi - + # Checking if the directory is valid. - echo $DIRECTORY | grep -E "^/[a-zA-Z0-9/-]{3,128}$" > /dev/null 2>&1 + local _dir_pattern="^/[-a-zA-Z0-9/\.-]{3,128}$" + echo $DIRECTORY | grep -E "$_dir_pattern" > /dev/null 2>&1 if [ ! $? = 0 ]; then + echo "# ($FUNCNAME) ERROR: directory name ($DIRECTORY) doesn't match the pattern $_dir_pattern" 1>&2 echo "${FALSE}" return 1; fi @@ -55,7 +57,7 @@ doUpdatecleanup() ########## -# getPreinstalled +# getPreinstalled ########## getPreinstalled() { @@ -67,15 +69,15 @@ getPreinstalled() echo "agent" return 0; fi - + cat $DIRECTORY/etc/ossec.conf | grep "" > /dev/null 2>&1 if [ $? = 0 ]; then echo "server" return 0; fi - + echo "local" - return 0; + return 0; } @@ -96,8 +98,8 @@ getPreinstalledDir() UpdateStartOSSEC() { . ${OSSEC_INIT} - - $DIRECTORY/bin/ossec-control start + + $DIRECTORY/bin/ossec-control start } @@ -107,8 +109,8 @@ UpdateStartOSSEC() UpdateStopOSSEC() { . ${OSSEC_INIT} - - $DIRECTORY/bin/ossec-control stop + + $DIRECTORY/bin/ossec-control stop # We also need to remove all syscheck queue file (format changed) if [ "X$VERSION" = "X0.9-3" ]; then @@ -118,9 +120,8 @@ UpdateStopOSSEC() rm -f $DIRECTORY/queue/syscheck/.* > /dev/null 2>&1 } - ########## -# UpdateOSSECRules +# UpdateOSSECRules ########## UpdateOSSECRules() { @@ -130,13 +131,27 @@ UpdateOSSECRules() # Backing up the old config cp -pr ${OSSEC_CONF_FILE} "${OSSEC_CONF_FILE}.$$.bak" - - cat ${OSSEC_CONF_FILE}|grep -v "" |grep -v "" |grep -v "" > "${OSSEC_CONF_FILE}.$$.tmp" + # Getting rid of old rules entries + grep -Ev "|||||rules global entry" ${OSSEC_CONF_FILE} > "${OSSEC_CONF_FILE}.$$.tmp" + + # Customer decoder, decoder_dir, rule_dir are carried over during upgrade + grep -E '|' ${OSSEC_CONF_FILE} | grep -v '" >> ${OSSEC_CONF_FILE} - cat ${RULES_TEMPLATE} >> ${OSSEC_CONF_FILE} + grep -v '' ${RULES_TEMPLATE} >> ${OSSEC_CONF_FILE} + cat "${OSSEC_CONF_FILE}.$$.tmp2" >> ${OSSEC_CONF_FILE} + echo "" >> ${OSSEC_CONF_FILE} echo " " >> ${OSSEC_CONF_FILE} -} + rm "${OSSEC_CONF_FILE}.$$.tmp2" +} diff --git a/src/logcollector/config.c b/src/logcollector/config.c index 33d64ab..8e1aee3 100755 --- a/src/logcollector/config.c +++ b/src/logcollector/config.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/logcollector/config.c, 2011/10/07 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -9,12 +10,12 @@ * Foundation */ -/* v0.3 (2005/08/23): Using the new OS_XML syntax and changing some usage +/* v0.3 (2005/08/23): Using the new OS_XML syntax and changing some usage * v0.2 (2005/01/17) */ - -#include "shared.h" + +#include "shared.h" #include "logcollector.h" @@ -23,7 +24,7 @@ * Read the config file (the localfiles) * v0.3: Changed for the new OS_XML */ -int LogCollectorConfig(char * cfgfile) +int LogCollectorConfig(char * cfgfile, int accept_remote) { int modules = 0; @@ -32,16 +33,20 @@ int LogCollectorConfig(char * cfgfile) modules|= CLOCALFILE; log_config.config = NULL; + log_config.agent_cfg = 0; + log_config.accept_remote = accept_remote; if(ReadConfig(modules, cfgfile, &log_config, NULL) < 0) return(OS_INVALID); - + #ifdef CLIENT modules|= CAGENT_CONFIG; + log_config.agent_cfg = 1; ReadConfig(modules, AGENTCONFIG, &log_config, NULL); + log_config.agent_cfg = 0; #endif - logff = log_config.config; + logff = log_config.config; return(1); diff --git a/src/logcollector/logcollector.c b/src/logcollector/logcollector.c index 5e3e3a2..e456467 100755 --- a/src/logcollector/logcollector.c +++ b/src/logcollector/logcollector.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/logcollector/logcollector.c, 2012/03/28 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -48,18 +49,18 @@ void LogCollectorStart() char keepalive[1024]; - + /* To check for inode changes */ struct stat tmp_stat; - - + + #ifndef WIN32 - + int int_error = 0; struct timeval fp_timeout; - + #else - + /* Checking if we are on vista. */ checkVista(); @@ -69,12 +70,12 @@ void LogCollectorStart() { win_read_vista_sec(); } - + #endif debug1("%s: DEBUG: Entering LogCollectorStart().", ARGV0); - - + + /* Initializing each file and structure */ for(i = 0;;i++) { @@ -87,7 +88,7 @@ void LogCollectorStart() { if(logff[r].file && strcmp(logff[i].file, logff[r].file) == 0) { - merror("%s: WARN: Duplicated log file given: '%s'.", + merror("%s: WARN: Duplicated log file given: '%s'.", ARGV0, logff[i].file); logff[i].file = NULL; logff[i].command = NULL; @@ -101,14 +102,14 @@ void LogCollectorStart() { /* do nothing, duplicated entry. */ } - + else if(strcmp(logff[i].logformat,"eventlog") == 0) { #ifdef WIN32 - + verbose(READING_EVTLOG, ARGV0, logff[i].file); win_startel(logff[i].file); - + #endif logff[i].file = NULL; logff[i].command = NULL; @@ -134,7 +135,7 @@ void LogCollectorStart() } else { - merror("%s: ERROR: Missing command argument. Ignoring it.", + merror("%s: ERROR: Missing command argument. Ignoring it.", ARGV0); } } @@ -155,16 +156,16 @@ void LogCollectorStart() else { merror("%s: ERROR: Missing command argument. Ignoring it.", - ARGV0); + ARGV0); } } - + else { logff[i].command = NULL; - /* Initializing the files */ + /* Initializing the files */ if(logff[i].ffile) { /* Day must be zero for all files to be initialized */ @@ -177,20 +178,26 @@ void LogCollectorStart() { ErrorExit(PARSE_ERROR, ARGV0, logff[i].ffile); } - + } else { handle_file(i, 1, 1); } - + verbose(READING_FILE, ARGV0, logff[i].file); - + /* Getting the log type */ if(strcmp("snort-full", logff[i].logformat) == 0) { logff[i].read = (void *)read_snortfull; } + #ifndef WIN32 + if(strcmp("ossecalert", logff[i].logformat) == 0) + { + logff[i].read = (void *)read_ossecalert; + } + #endif else if(strcmp("nmapg", logff[i].logformat) == 0) { logff[i].read = (void *)read_nmapg; @@ -259,7 +266,7 @@ void LogCollectorStart() /* Start up message */ verbose(STARTUP_MSG, ARGV0, (int)getpid()); - + max_file = i -1; @@ -268,8 +275,8 @@ void LogCollectorStart() { max_file = 0; } - - + + /* Daemon loop */ while(1) { @@ -277,7 +284,7 @@ void LogCollectorStart() fp_timeout.tv_sec = loop_timeout; fp_timeout.tv_usec = 0; - /* Waiting for the select timeout */ + /* Waiting for the select timeout */ if ((r = select(0, NULL, NULL, NULL, &fp_timeout)) < 0) { merror(SELECT_ERROR, ARGV0); @@ -290,18 +297,18 @@ void LogCollectorStart() continue; } #else - + /* Windows don't like select that way */ sleep(loop_timeout + 2); - + /* Check for messages in the event viewer */ win_readel(); #endif - + f_check++; - + /* Checking which file is available */ for(i = 0; i <= max_file; i++) { @@ -389,7 +396,7 @@ void LogCollectorStart() logff[i].ign++; continue; } - + #ifdef WIN32 logff[i].read(i, &r, 1); #endif @@ -401,19 +408,19 @@ void LogCollectorStart() } } - + /* Only check bellow if check > VCHECK_FILES */ if(f_check <= VCHECK_FILES) continue; - + /* Send keep alive message */ rand_keepalive_str(keepalive, 700); SendMSG(logr_queue, keepalive, "ossec-keepalive", LOCALFILE_MQ); - /* Zeroing f_check */ + /* Zeroing f_check */ f_check = 0; @@ -423,8 +430,8 @@ void LogCollectorStart() /* These are the windows logs or ignored files */ if(!logff[i].file) continue; - - + + /* Files with date -- check for day change */ if(logff[i].ffile) { @@ -449,8 +456,8 @@ void LogCollectorStart() continue; } } - - + + /* Check for file change -- if the file is open already */ if(logff[i].fp) { @@ -459,7 +466,7 @@ void LogCollectorStart() { fclose(logff[i].fp); logff[i].fp = NULL; - + merror(FILE_ERROR, ARGV0, logff[i].file); } @@ -499,21 +506,21 @@ void LogCollectorStart() snprintf(msg_alert, 512, "ossec: File rotated (inode " "changed): '%s'.", logff[i].file); - + /* Send message about log rotated */ - SendMSG(logr_queue, msg_alert, + SendMSG(logr_queue, msg_alert, "ossec-logcollector", LOCALFILE_MQ); - + debug1("%s: DEBUG: File inode changed. %s", ARGV0, logff[i].file); - + fclose(logff[i].fp); #ifdef WIN32 CloseHandle(logff[i].h); CloseHandle(h1); #endif - + logff[i].fp = NULL; handle_file(i, 0, 1); continue; @@ -529,11 +536,11 @@ void LogCollectorStart() snprintf(msg_alert, 512, "ossec: File size reduced " "(inode remained): '%s'.", logff[i].file); - + /* Send message about log rotated */ - SendMSG(logr_queue, msg_alert, + SendMSG(logr_queue, msg_alert, "ossec-logcollector", LOCALFILE_MQ); - + debug1("%s: DEBUG: File size reduced. %s", ARGV0, logff[i].file); @@ -549,7 +556,7 @@ void LogCollectorStart() CloseHandle(logff[i].h); CloseHandle(h1); #endif - + logff[i].fp = NULL; handle_file(i, 1, 1); } @@ -560,9 +567,9 @@ void LogCollectorStart() } #endif } - - - /* Too many errors for the file */ + + + /* Too many errors for the file */ if(logff[i].ign > open_file_attempts) { /* 999 Maximum ignore */ @@ -570,7 +577,7 @@ void LogCollectorStart() { continue; } - + merror(LOGC_FILE_ERROR, ARGV0, logff[i].file); if(logff[i].fp) { @@ -579,7 +586,7 @@ void LogCollectorStart() CloseHandle(logff[i].h); #endif } - + logff[i].fp = NULL; @@ -596,9 +603,9 @@ void LogCollectorStart() logff[i].ign = 999; continue; } - - - /* File not opened */ + + + /* File not opened */ if(!logff[i].fp) { if(logff[i].ign >= 999) @@ -624,13 +631,13 @@ int update_fname(int i) { struct tm *p; time_t __ctime = time(0); - + char lfile[OS_FLSIZE + 1]; size_t ret; p = localtime(&__ctime); - + /* Handle file */ if(p->tm_mday == _cday) @@ -645,17 +652,17 @@ int update_fname(int i) { ErrorExit(PARSE_ERROR, ARGV0, logff[i].ffile); } - - + + /* Update the file name */ if(strcmp(lfile, logff[i].file) != 0) { os_free(logff[i].file); - os_strdup(lfile, logff[i].file); + os_strdup(lfile, logff[i].file); verbose(VAR_LOG_MON, ARGV0, logff[i].file); - + /* Setting cday to zero because other files may need * to be changed. */ @@ -673,7 +680,7 @@ int handle_file(int i, int do_fseek, int do_log) { int fd; struct stat stat_fd; - + /* We must be able to open the file, fseek and get the * time of change from it. */ @@ -696,10 +703,10 @@ int handle_file(int i, int do_fseek, int do_log) logff[i].fp = NULL; return(-1); } - + logff[i].fd = stat_fd.st_ino; logff[i].size = stat_fd.st_size; - + #else BY_HANDLE_FILE_INFORMATION lpFileInformation; @@ -764,7 +771,7 @@ int handle_file(int i, int do_fseek, int do_log) } #endif } - + /* Setting ignore to zero */ logff[i].ign = 0; diff --git a/src/logcollector/logcollector.h b/src/logcollector/logcollector.h index 6117b64..4f9badd 100755 --- a/src/logcollector/logcollector.h +++ b/src/logcollector/logcollector.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/logcollector/logcollector.h, 2012/03/28 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -31,7 +32,7 @@ /* Read logcollector config */ -int LogCollectorConfig(char * cfgfile); +int LogCollectorConfig(char * cfgfile, int accept_remote); /* Stary log collector daemon */ void LogCollectorStart(); @@ -45,6 +46,9 @@ void *read_syslog(int pos, int *rc, int drop_it); /* Read snort full file */ void *read_snortfull(int pos, int *rc, int drop_it); +/* Read ossec alert file */ +void *read_ossecalert(int pos, int *rc, int drop_it); + /* Read nmap grepable format */ void *read_nmapg(int pos, int *rc, int drop_it); diff --git a/src/logcollector/main.c b/src/logcollector/main.c index 8608a58..fe143c2 100755 --- a/src/logcollector/main.c +++ b/src/logcollector/main.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/logcollector/main.c, 2012/03/28 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -11,9 +12,9 @@ /* v0.4 (2005/11/11): Some cleanup and bug fixes - * v0.3 (2005/08/26): Reading all files in just one process + * v0.3 (2005/08/26): Reading all files in just one process * v0.2 (2005/04/04): - */ + */ /* Logcollector daemon. @@ -41,6 +42,7 @@ int main(int argc, char **argv) int c; int debug_flag = 0; int test_config = 0,run_foreground = 0; + int accept_manager_commands = 0; char *cfg = DEFAULTCPATH; char *dir = DEFAULTDIR; @@ -58,7 +60,7 @@ int main(int argc, char **argv) /* Setting the name */ OS_SetName(ARGV0); - + while((c = getopt(argc, argv, "VtdhfD:c:")) != -1) { @@ -88,10 +90,10 @@ int main(int argc, char **argv) break; case 't': test_config = 1; - break; + break; default: help(ARGV0); - break; + break; } } @@ -99,23 +101,29 @@ int main(int argc, char **argv) debug1(STARTED_MSG,ARGV0); + accept_manager_commands = getDefine_Int("logcollector", "remote_commands", + 0, 1); + + /* Reading config file */ - if(LogCollectorConfig(cfg) < 0) + if(LogCollectorConfig(cfg, accept_manager_commands) < 0) ErrorExit(CONFIG_ERROR, ARGV0, cfg); - - + + /* Getting loop timeout */ loop_timeout = getDefine_Int("logcollector", "loop_timeout", 1, 120); - + open_file_attempts = getDefine_Int("logcollector", "open_attempts", 2, 998); - + debug_flag = getDefine_Int("logcollector", "debug", 0,2); - + accept_manager_commands = getDefine_Int("logcollector", "remote_commands", + 0, 1); + /* Getting debug values */ while(debug_flag != 0) { @@ -127,7 +135,7 @@ int main(int argc, char **argv) /* Exit if test config */ if(test_config) exit(0); - + /* No file available to monitor -- continue */ if(logff == NULL) @@ -142,13 +150,13 @@ int main(int argc, char **argv) merror(NO_FILE, ARGV0); } - + /* Starting signal handler */ StartSIG(ARGV0); - if (!run_foreground) + if (!run_foreground) { /* Going on daemon mode */ nowDaemon(); @@ -160,21 +168,21 @@ int main(int argc, char **argv) if(CreatePID(ARGV0, getpid()) < 0) merror(PID_ERROR, ARGV0); - - + + /* Waiting 6 seconds for the analysisd/agentd to settle */ debug1("%s: DEBUG: Waiting main daemons to settle.", ARGV0); sleep(6); - - + + /* Starting the queue. */ if((logr_queue = StartMQ(DEFAULTQPATH,WRITE)) < 0) ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH); - /* Main loop */ + /* Main loop */ LogCollectorStart(); - + return(0); } diff --git a/src/logcollector/read_command.c b/src/logcollector/read_command.c index a6c413f..f1de982 100755 --- a/src/logcollector/read_command.c +++ b/src/logcollector/read_command.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/logcollector/read_command.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -43,9 +44,9 @@ void *read_command(int pos, int *rc, int drop_it) } - snprintf(str, 256, "ossec: output: '%s': ", - (NULL != logff[pos].alias) - ? logff[pos].alias + snprintf(str, 256, "ossec: output: '%s': ", + (NULL != logff[pos].alias) + ? logff[pos].alias : logff[pos].command); cmd_size = strlen(str); @@ -53,7 +54,7 @@ void *read_command(int pos, int *rc, int drop_it) while(fgets(str + cmd_size, OS_MAXSTR - OS_LOG_HEADER - 256, cmd_output) != NULL) { /* Getting the last occurence of \n */ - if ((p = strrchr(str, '\n')) != NULL) + if ((p = strrchr(str, '\n')) != NULL) { *p = '\0'; } @@ -69,11 +70,11 @@ void *read_command(int pos, int *rc, int drop_it) { continue; } - - + + debug2("%s: DEBUG: Reading command message: '%s'", ARGV0, str); - + /* Sending message to queue */ if(drop_it == 0) { @@ -94,7 +95,7 @@ void *read_command(int pos, int *rc, int drop_it) pclose(cmd_output); - return(NULL); + return(NULL); } /* EOF */ diff --git a/src/logcollector/read_djb_multilog.c b/src/logcollector/read_djb_multilog.c index 18a2001..be4f56f 100755 --- a/src/logcollector/read_djb_multilog.c +++ b/src/logcollector/read_djb_multilog.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/logcollector/read_djb_multilog.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -23,8 +24,8 @@ char *(djb_month[])={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug", "Sep","Oct","Nov","Dec"}; -char djb_host[512 +1]; - +char djb_host[512 +1]; + /* Initializes multilog. */ @@ -57,7 +58,7 @@ int init_djbmultilog(int pos) #else strncpy(djb_host, "win32", 512 -1); #endif - + /* Multilog must be in the following format: /path/program_name/current */ @@ -65,7 +66,7 @@ int init_djbmultilog(int pos) if(!tmp_str) return(0); - + /* Must end with /current and must not be in the beginning of the string. */ if((strcmp(tmp_str, "/current") != 0) || (tmp_str == logff[pos].file)) { @@ -84,7 +85,7 @@ int init_djbmultilog(int pos) return(0); } - + os_strdup(djbp_name+1, logff[pos].djb_program_name); tmp_str[0] = '/'; @@ -116,19 +117,19 @@ void *read_djbmultilog(int pos, int *rc, int drop_it) { return(NULL); } - + /* Getting new entry */ while(fgets(str, OS_MAXSTR - OS_LOG_HEADER, logff[pos].fp) != NULL) { - + /* Getting buffer size */ str_len = strlen(str); - + /* Getting the last occurence of \n */ - if ((p = strrchr(str, '\n')) != NULL) + if ((p = strrchr(str, '\n')) != NULL) { *p = '\0'; @@ -143,13 +144,13 @@ void *read_djbmultilog(int pos, int *rc, int drop_it) { need_clear = 1; } - - + + /* Multilog messages have the following format: * @40000000463246020c2ca16c xx... */ if((str_len > 26) && - (str[0] == '@') && + (str[0] == '@') && isalnum((int)str[1]) && isalnum((int)str[2]) && isalnum((int)str[3]) && @@ -162,11 +163,11 @@ void *read_djbmultilog(int pos, int *rc, int drop_it) { p++; } - - + + /* If message has a valid syslog header, send as is. */ if((str_len > 44) && - (p[3] == ' ') && + (p[3] == ' ') && (p[6] == ' ') && (p[9] == ':') && (p[12] == ':') && @@ -198,18 +199,18 @@ void *read_djbmultilog(int pos, int *rc, int drop_it) p); } } - - + + else { debug2("%s: DEBUG: Invalid DJB log: '%s'", ARGV0, str); continue; } - - + + debug2("%s: DEBUG: Reading DJB multilog message: '%s'", ARGV0, buffer); - + /* Sending message to queue */ if(drop_it == 0) { @@ -222,11 +223,11 @@ void *read_djbmultilog(int pos, int *rc, int drop_it) } } } - + continue; } - return(NULL); + return(NULL); } /* EOF */ diff --git a/src/logcollector/read_fullcommand.c b/src/logcollector/read_fullcommand.c index 11d256b..c79eb22 100755 --- a/src/logcollector/read_fullcommand.c +++ b/src/logcollector/read_fullcommand.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/logcollector/read_fullcommand.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2010 Trend Micro Inc. * All right reserved. @@ -47,8 +48,8 @@ void *read_fullcommand(int pos, int *rc, int drop_it) snprintf(str, 256, "ossec: output: '%s':\n", - (NULL != logff[pos].alias) - ? logff[pos].alias + (NULL != logff[pos].alias) + ? logff[pos].alias : logff[pos].command); cmd_size = strlen(str); @@ -58,12 +59,12 @@ void *read_fullcommand(int pos, int *rc, int drop_it) str[cmd_size +n] = '\0'; /* Getting the last occurence of \n */ - if ((p = strrchr(str, '\n')) != NULL) + if ((p = strrchr(str, '\n')) != NULL) { *p = '\0'; } - + debug2("%s: DEBUG: Reading command message: '%s'", ARGV0, str); /* Removing empty lines. */ @@ -87,7 +88,7 @@ void *read_fullcommand(int pos, int *rc, int drop_it) } strfinal[n] = '\0'; - + /* Sending message to queue */ if(drop_it == 0) { @@ -106,7 +107,7 @@ void *read_fullcommand(int pos, int *rc, int drop_it) pclose(cmd_output); - return(NULL); + return(NULL); } /* EOF */ diff --git a/src/logcollector/read_mssql_log.c b/src/logcollector/read_mssql_log.c index 41ad273..ae685bb 100755 --- a/src/logcollector/read_mssql_log.c +++ b/src/logcollector/read_mssql_log.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/logcollector/read_mssql_log.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -20,7 +21,7 @@ -/* Send mssql message and check the return code. +/* Send mssql message and check the return code. */ void __send_mssql_msg(int pos, int drop_it, char *buffer) { @@ -52,7 +53,7 @@ void *read_mssql_log(int pos, int *rc, int drop_it) /* Zeroing buffer and str */ buffer[0] = '\0'; - buffer[OS_MAXSTR] = '\0'; + buffer[OS_MAXSTR] = '\0'; str[OS_MAXSTR]= '\0'; *rc = 0; @@ -60,20 +61,20 @@ void *read_mssql_log(int pos, int *rc, int drop_it) /* Getting new entry */ while(fgets(str, OS_MAXSTR - OS_LOG_HEADER, logff[pos].fp) != NULL) { - + /* Getting buffer size */ str_len = strlen(str); - + /* Checking str_len size. Very useless, but just to make sure.. */ if(str_len >= sizeof(buffer) -2) { str_len = sizeof(buffer) -10; } - + /* Getting the last occurence of \n */ - if ((p = strrchr(str, '\n')) != NULL) + if ((p = strrchr(str, '\n')) != NULL) { *p = '\0'; @@ -88,8 +89,8 @@ void *read_mssql_log(int pos, int *rc, int drop_it) { need_clear = 1; } - - + + #ifdef WIN32 if ((p = strrchr(str, '\r')) != NULL) { @@ -111,7 +112,7 @@ void *read_mssql_log(int pos, int *rc, int drop_it) } #endif - + /* MSSQL messages have the following formats: * 2009-03-25 04:47:30.01 Server @@ -119,17 +120,17 @@ void *read_mssql_log(int pos, int *rc, int drop_it) * 2009-02-06 11:48:59 Server */ if((str_len > 19) && - (str[4] == '-') && - (str[7] == '-') && - (str[10] == ' ') && - (str[13] == ':') && - (str[16] == ':') && + (str[4] == '-') && + (str[7] == '-') && + (str[10] == ' ') && + (str[13] == ':') && + (str[16] == ':') && isdigit((int)str[0]) && isdigit((int)str[1]) && isdigit((int)str[2]) && isdigit((int)str[3])) { - + /* If the saved message is empty, set it and continue. */ if(buffer[0] == '\0') { @@ -147,8 +148,8 @@ void *read_mssql_log(int pos, int *rc, int drop_it) strncpy(buffer, str, str_len + 2); } } - - + + /* Query logs can be in multiple lines. * They always start with a tab in the additional ones. */ @@ -156,16 +157,16 @@ void *read_mssql_log(int pos, int *rc, int drop_it) { /* Size of the buffer */ int buffer_len = strlen(buffer); - + p = str; - + /* Removing extra spaces and tabs */ while(*p == ' ' || *p == '\t') { p++; } - - + + /* Adding additional message to the saved buffer. */ if(sizeof(buffer) - buffer_len > str_len +256) { @@ -178,7 +179,7 @@ void *read_mssql_log(int pos, int *rc, int drop_it) strncat(buffer, str, str_len +3); } } - + continue; } @@ -188,8 +189,8 @@ void *read_mssql_log(int pos, int *rc, int drop_it) { __send_mssql_msg(pos, drop_it, buffer); } - - return(NULL); + + return(NULL); } /* EOF */ diff --git a/src/logcollector/read_multiline.c b/src/logcollector/read_multiline.c index 29a565d..02d357e 100755 --- a/src/logcollector/read_multiline.c +++ b/src/logcollector/read_multiline.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/logcollector/read_multiline.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2010 Trend Micro Inc. * All right reserved. @@ -45,11 +46,11 @@ void *read_multiline(int pos, int *rc, int drop_it) linesgot++; /* Getting the last occurence of \n */ - if ((p = strrchr(str, '\n')) != NULL) + if ((p = strrchr(str, '\n')) != NULL) { *p = '\0'; } - + /* If we didn't get the new line, because the * size is large, send what we got so far. */ @@ -64,17 +65,17 @@ void *read_multiline(int pos, int *rc, int drop_it) debug1("%s: Message not complete. Trying again: '%s'", ARGV0,str); fsetpos(logff[pos].fp, &fp_pos); break; - } - + } + #ifdef WIN32 if ((p = strrchr(str, '\r')) != NULL) { *p = '\0'; } #endif - + debug2("%s: DEBUG: Reading message: '%s'", ARGV0, str); - + /* Adding to buffer. */ buffer_size = strlen(buffer); @@ -86,12 +87,12 @@ void *read_multiline(int pos, int *rc, int drop_it) strncpy(buffer + buffer_size, str, OS_MAXSTR - buffer_size -2); - + if(linesgot < linecount) { continue; } - + /* Sending message to queue */ if(drop_it == 0) @@ -124,12 +125,12 @@ void *read_multiline(int pos, int *rc, int drop_it) } __ms = 0; } - + fgetpos(logff[pos].fp, &fp_pos); continue; } - return(NULL); + return(NULL); } /* EOF */ diff --git a/src/logcollector/read_mysql_log.c b/src/logcollector/read_mysql_log.c index 68dafc9..7d76d56 100755 --- a/src/logcollector/read_mysql_log.c +++ b/src/logcollector/read_mysql_log.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/logcollector/read_mysql_log.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -40,13 +41,13 @@ void *read_mysql_log(int pos, int *rc, int drop_it) /* Getting new entry */ while(fgets(str, OS_MAXSTR - OS_LOG_HEADER, logff[pos].fp) != NULL) { - + /* Getting buffer size */ str_len = strlen(str); - + /* Getting the last occurence of \n */ - if ((p = strrchr(str, '\n')) != NULL) + if ((p = strrchr(str, '\n')) != NULL) { *p = '\0'; @@ -61,8 +62,8 @@ void *read_mysql_log(int pos, int *rc, int drop_it) { need_clear = 1; } - - + + #ifdef WIN32 if ((p = strrchr(str, '\r')) != NULL) { @@ -84,14 +85,14 @@ void *read_mysql_log(int pos, int *rc, int drop_it) } #endif - + /* Mysql messages have the following format: * 070823 21:01:30 xx */ if((str_len > 18) && - (str[6] == ' ') && - (str[9] == ':') && - (str[12] == ':') && + (str[6] == ' ') && + (str[9] == ':') && + (str[12] == ':') && isdigit((int)str[0]) && isdigit((int)str[1]) && isdigit((int)str[2]) && @@ -105,21 +106,21 @@ void *read_mysql_log(int pos, int *rc, int drop_it) strncpy(__mysql_last_time, str, 16); __mysql_last_time[15] = '\0'; - + /* Removing spaces and tabs */ p = str + 15; while(*p == ' ' || *p == '\t') { p++; } - - + + /* Valid MySQL message */ - snprintf(buffer, OS_MAXSTR, "MySQL log: %s %s", + snprintf(buffer, OS_MAXSTR, "MySQL log: %s %s", __mysql_last_time, p); } - - + + /* Multiple events at the same second share the same * time stamp. * 0909 2020 2020 2020 20 @@ -142,20 +143,20 @@ void *read_mysql_log(int pos, int *rc, int drop_it) { p++; } - - /* Valid MySQL message */ - snprintf(buffer, OS_MAXSTR, "MySQL log: %s %s", - __mysql_last_time, p); + + /* Valid MySQL message */ + snprintf(buffer, OS_MAXSTR, "MySQL log: %s %s", + __mysql_last_time, p); } else { continue; } - - + + debug2("%s: DEBUG: Reading mysql messages: '%s'", ARGV0, buffer); - + /* Sending message to queue */ if(drop_it == 0) { @@ -168,11 +169,11 @@ void *read_mysql_log(int pos, int *rc, int drop_it) } } } - + continue; } - return(NULL); + return(NULL); } /* EOF */ diff --git a/src/logcollector/read_nmapg.c b/src/logcollector/read_nmapg.c index da32d18..c233488 100755 --- a/src/logcollector/read_nmapg.c +++ b/src/logcollector/read_nmapg.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/logcollector/read_nmapg.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -27,7 +28,7 @@ static char *__get_port(char *str, char *proto, char *port, int msize); -/* Get port and protocol. +/* Get port and protocol. */ static char *__get_port(char *str, char *proto, char *port, int msize) { @@ -41,7 +42,7 @@ static char *__get_port(char *str, char *proto, char *port, int msize) str++; } - + /* Getting port */ p = strchr(str, '/'); if(!p) @@ -49,13 +50,13 @@ static char *__get_port(char *str, char *proto, char *port, int msize) *p = '\0'; p++; - + /* Getting port */ strncpy(port, str, msize); port[msize -1] = '\0'; - - + + /* Checking if the port is open */ q = __go_after(p, NMAPG_OPEN); if(!q) @@ -69,14 +70,14 @@ static char *__get_port(char *str, char *proto, char *port, int msize) p = strchr(q, '/'); if(!p) return(NULL); - p++; + p++; } else { p = q; } - - + + /* Getting protocol */ str = p; @@ -88,16 +89,16 @@ static char *__get_port(char *str, char *proto, char *port, int msize) *p = '\0'; p++; - + strncpy(proto, str, msize); proto[msize -1] = '\0'; - - + + /* Setting proto to null if port is not open */ if(filtered) - proto[0] = '\0'; - - + proto[0] = '\0'; + + /* Removing slashes */ if(*p == '/') { @@ -112,7 +113,7 @@ static char *__get_port(char *str, char *proto, char *port, int msize) return(q); } - + return(NULL); } @@ -127,7 +128,7 @@ static char *__go_after(char *x, char *y) /* X and Y must be not null */ if(!x || !y) return(NULL); - + x_s = strlen(x); y_s = strlen(y); @@ -153,7 +154,7 @@ void *read_nmapg(int pos, int *rc, int drop_it) { int final_msg_s; int need_clear = 0; - + char str[OS_MAXSTR + 1]; char final_msg[OS_MAXSTR + 1]; char buffer[OS_MAXSTR + 1]; @@ -163,7 +164,7 @@ void *read_nmapg(int pos, int *rc, int drop_it) char *ip = NULL; char *p; char *q; - + *rc = 0; str[OS_MAXSTR] = '\0'; final_msg[OS_MAXSTR] = '\0'; @@ -183,7 +184,7 @@ void *read_nmapg(int pos, int *rc, int drop_it) } continue; } - + /* Removing \n at the end of the string */ if ((q = strchr(str, '\n')) != NULL) { @@ -194,22 +195,22 @@ void *read_nmapg(int pos, int *rc, int drop_it) need_clear = 1; } - + /* Do not get commented lines */ if((str[0] == '#') || (str[0] == '\0')) { continue; } - + /* Getting host */ q = __go_after(str, NMAPG_HOST); if(!q) { goto file_error; } - - + + /* Getting ip/hostname */ p = strchr(q, ')'); if(!p) @@ -217,10 +218,10 @@ void *read_nmapg(int pos, int *rc, int drop_it) goto file_error; } - + /* Setting the valid ip */ ip = q; - + /* Getting the ports */ @@ -235,8 +236,8 @@ void *read_nmapg(int pos, int *rc, int drop_it) /* Now fixing p, to have the closing parenthesis */ p++; *p = '\0'; - - + + /* q now should point to the ports */ p = __go_after(q, NMAPG_PORT); if(!p) @@ -256,7 +257,7 @@ void *read_nmapg(int pos, int *rc, int drop_it) snprintf(final_msg, OS_MAXSTR, "Host: %s, open ports:", ip); final_msg_s = OS_MAXSTR - ((strlen(final_msg) +3)); - + /* Getting port and protocol */ do @@ -266,7 +267,7 @@ void *read_nmapg(int pos, int *rc, int drop_it) { break; } - + p = __get_port(p, proto, port, 9); if(!p) { @@ -274,26 +275,26 @@ void *read_nmapg(int pos, int *rc, int drop_it) break; } - + /* Port not open */ if(proto[0] == '\0') { continue; } - + /* Adding ports */ snprintf(buffer, OS_MAXSTR, " %s(%s)", port, proto); strncat(final_msg, buffer, final_msg_s); final_msg_s-=(strlen(buffer) +2); - + }while(*p == ',' && (p++)); - + if(drop_it == 0) - { + { /* Sending message to queue */ - if(SendMSG(logr_queue, final_msg, logff[pos].file, + if(SendMSG(logr_queue, final_msg, logff[pos].file, HOSTINFO_MQ) < 0) { merror(QUEUE_SEND, ARGV0); @@ -304,21 +305,21 @@ void *read_nmapg(int pos, int *rc, int drop_it) } } - + /* Getting next */ continue; - + /* Handling errors */ file_error: - + merror("%s: Bad formated nmap grepable file.", ARGV0); *rc = -1; return(NULL); - + } - + return(NULL); } diff --git a/src/logcollector/read_ossecalert.c b/src/logcollector/read_ossecalert.c new file mode 100755 index 0000000..5b669dd --- /dev/null +++ b/src/logcollector/read_ossecalert.c @@ -0,0 +1,137 @@ +/* @(#) $Id: ./src/logcollector/read_ossecalert.c, 2012/03/30 dcid Exp $ + */ + +/* Copyright (C) 2012 Daniel B. Cid (http://dcid.me) + * All right reserved. + * + * This program is a free software; you can redistribute it + * and/or modify it under the terms of the GNU General Public + * License (version 2) as published by the FSF - Free Software + * Foundation + */ + +/* Read the syslog */ + + +#include "shared.h" +#include "headers/read-alert.h" +#include "logcollector.h" + + + +/* Read syslog files/snort fast/apache files */ +void *read_ossecalert(int pos, int *rc, int drop_it) +{ + alert_data *al_data; + char user_msg[256]; + char srcip_msg[256]; + + char syslog_msg[OS_SIZE_2048 +1]; + + al_data = GetAlertData(0, logff[pos].fp); + if(!al_data) + { + return(NULL); + } + + + memset(syslog_msg, '\0', OS_SIZE_2048 +1); + + + + /* Adding source ip. */ + if(!al_data->srcip || + ((al_data->srcip[0] == '(') && + (al_data->srcip[1] == 'n') && + (al_data->srcip[2] == 'o'))) + { + srcip_msg[0] = '\0'; + } + else + { + snprintf(srcip_msg, 255, " srcip: %s;", al_data->srcip); + } + + + /* Adding username. */ + if(!al_data->user || + ((al_data->user[0] == '(') && + (al_data->user[1] == 'n') && + (al_data->user[2] == 'o'))) + { + user_msg[0] = '\0'; + } + else + { + snprintf(user_msg, 255, " user: %s;", al_data->user); + } + + + if(al_data->log[1] == NULL) + { + /* Building syslog message. */ + snprintf(syslog_msg, OS_SIZE_2048, + "ossec: Alert Level: %d; Rule: %d - %s; " + "Location: %s;%s%s %s", + al_data->level, al_data->rule, al_data->comment, + al_data->location, + srcip_msg, + user_msg, + al_data->log[0]); + } + else + { + char *tmp_msg = NULL; + short int j = 0; + + while(al_data->log[j] != NULL) + { + tmp_msg = os_LoadString(tmp_msg, al_data->log[j]); + tmp_msg = os_LoadString(tmp_msg, "\n"); + if(tmp_msg == NULL) + { + FreeAlertData(al_data); + return(NULL); + } + j++; + } + if(strlen(tmp_msg) > 1596) + { + tmp_msg[1594] = '.'; + tmp_msg[1595] = '.'; + tmp_msg[1596] = '.'; + tmp_msg[1597] = '\0'; + } + snprintf(syslog_msg, OS_SIZE_2048, + "ossec: Alert Level: %d; Rule: %d - %s; " + "Location: %s;%s%s %s", + al_data->level, al_data->rule, al_data->comment, + al_data->location, + srcip_msg, + user_msg, + tmp_msg); + } + + + /* Clearing the memory */ + FreeAlertData(al_data); + + + + /* Sending message to queue */ + if(drop_it == 0) + { + if(SendMSG(logr_queue,syslog_msg,logff[pos].file, LOCALFILE_MQ) < 0) + { + merror(QUEUE_SEND, ARGV0); + if((logr_queue = StartMQ(DEFAULTQPATH,WRITE)) < 0) + { + ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQPATH); + } + } + } + + return(NULL); +} + + diff --git a/src/logcollector/read_postgresql_log.c b/src/logcollector/read_postgresql_log.c index 6fea175..ba29919 100755 --- a/src/logcollector/read_postgresql_log.c +++ b/src/logcollector/read_postgresql_log.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/logcollector/read_postgresql_log.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -20,7 +21,7 @@ -/* Send pgsql message and check the return code. +/* Send pgsql message and check the return code. */ void __send_pgsql_msg(int pos, int drop_it, char *buffer) { @@ -52,7 +53,7 @@ void *read_postgresql_log(int pos, int *rc, int drop_it) /* Zeroing buffer and str */ buffer[0] = '\0'; - buffer[OS_MAXSTR] = '\0'; + buffer[OS_MAXSTR] = '\0'; str[OS_MAXSTR]= '\0'; *rc = 0; @@ -60,20 +61,20 @@ void *read_postgresql_log(int pos, int *rc, int drop_it) /* Getting new entry */ while(fgets(str, OS_MAXSTR - OS_LOG_HEADER, logff[pos].fp) != NULL) { - + /* Getting buffer size */ str_len = strlen(str); - + /* Checking str_len size. Very useless, but just to make sure.. */ if(str_len >= sizeof(buffer) -2) { str_len = sizeof(buffer) -10; } - + /* Getting the last occurence of \n */ - if ((p = strrchr(str, '\n')) != NULL) + if ((p = strrchr(str, '\n')) != NULL) { *p = '\0'; @@ -88,8 +89,8 @@ void *read_postgresql_log(int pos, int *rc, int drop_it) { need_clear = 1; } - - + + #ifdef WIN32 if ((p = strrchr(str, '\r')) != NULL) { @@ -111,22 +112,22 @@ void *read_postgresql_log(int pos, int *rc, int drop_it) } #endif - + /* PostgreSQL messages have the following format: * [2007-08-31 19:17:32.186 ADT] 192.168.2.99:db_name */ if((str_len > 32) && - (str[0] == '[') && - (str[5] == '-') && - (str[8] == '-') && - (str[11] == ' ') && - (str[14] == ':') && - (str[17] == ':') && + (str[0] == '[') && + (str[5] == '-') && + (str[8] == '-') && + (str[11] == ' ') && + (str[14] == ':') && + (str[17] == ':') && isdigit((int)str[1]) && isdigit((int)str[12])) { - + /* If the saved message is empty, set it and continue. */ if(buffer[0] == '\0') { @@ -144,8 +145,8 @@ void *read_postgresql_log(int pos, int *rc, int drop_it) strncpy(buffer, str, str_len + 2); } } - - + + /* Query logs can be in multiple lines. * They always start with a tab in the additional ones. */ @@ -154,16 +155,16 @@ void *read_postgresql_log(int pos, int *rc, int drop_it) { /* Size of the buffer */ int buffer_len = strlen(buffer); - + p = str +1; - + /* Removing extra spaces and tabs */ while(*p == ' ' || *p == '\t') { p++; } - - + + /* Adding additional message to the saved buffer. */ if(sizeof(buffer) - buffer_len > str_len +256) { @@ -176,7 +177,7 @@ void *read_postgresql_log(int pos, int *rc, int drop_it) strncat(buffer, str, str_len +3); } } - + continue; } @@ -186,8 +187,8 @@ void *read_postgresql_log(int pos, int *rc, int drop_it) { __send_pgsql_msg(pos, drop_it, buffer); } - - return(NULL); + + return(NULL); } /* EOF */ diff --git a/src/logcollector/read_snortfull.c b/src/logcollector/read_snortfull.c index 951b2d8..cbb3edc 100755 --- a/src/logcollector/read_snortfull.c +++ b/src/logcollector/read_snortfull.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/logcollector/read_snortfull.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -22,15 +23,15 @@ void *read_snortfull(int pos, int *rc, int drop_it) { int f_msg_size = OS_MAXSTR; - + char *one = "one"; char *two = "two"; - + char *p = NULL; char *q; char str[OS_MAXSTR + 1]; char f_msg[OS_MAXSTR +1]; - + *rc = 0; str[OS_MAXSTR]='\0'; f_msg[OS_MAXSTR] = '\0'; @@ -75,7 +76,7 @@ void *read_snortfull(int pos, int *rc, int drop_it) f_msg_size -= strlen(str)+1; p = two; } - + /* If it is a preprocessor message, it will not have * the classification. */ @@ -84,10 +85,10 @@ void *read_snortfull(int pos, int *rc, int drop_it) strncat(f_msg, "[Classification: Preprocessor] " "[Priority: 3] ", f_msg_size); strncat(f_msg, ++q, f_msg_size -40); - + /* Cleaning for next event */ p = NULL; - + /* Sending the message */ if(drop_it == 0) { @@ -133,7 +134,7 @@ void *read_snortfull(int pos, int *rc, int drop_it) } } } - + f_msg[0] = '\0'; f_msg_size = OS_MAXSTR; str[0] = '\0'; diff --git a/src/logcollector/read_syslog.c b/src/logcollector/read_syslog.c index f01c3f7..0d3024a 100755 --- a/src/logcollector/read_syslog.c +++ b/src/logcollector/read_syslog.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/logcollector/read_syslog.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -39,11 +40,11 @@ void *read_syslog(int pos, int *rc, int drop_it) while(fgets(str, OS_MAXSTR - OS_LOG_HEADER, logff[pos].fp) != NULL) { /* Getting the last occurence of \n */ - if ((p = strrchr(str, '\n')) != NULL) + if ((p = strrchr(str, '\n')) != NULL) { *p = '\0'; } - + /* If we didn't get the new line, because the * size is large, send what we got so far. */ @@ -58,8 +59,8 @@ void *read_syslog(int pos, int *rc, int drop_it) debug1("%s: Message not complete. Trying again: '%s'", ARGV0,str); fsetpos(logff[pos].fp, &fp_pos); break; - } - + } + #ifdef WIN32 if ((p = strrchr(str, '\r')) != NULL) { @@ -80,10 +81,10 @@ void *read_syslog(int pos, int *rc, int drop_it) continue; } #endif - + debug2("%s: DEBUG: Reading syslog message: '%s'", ARGV0, str); - + /* Sending message to queue */ if(drop_it == 0) { @@ -101,7 +102,13 @@ void *read_syslog(int pos, int *rc, int drop_it) /* Incorrectly message size */ if(__ms) { - merror("%s: Large message size: '%s'", ARGV0, str); + // strlen(str) >= (OS_MAXSTR - OS_LOG_HEADER - 2) + // truncate str before logging to ossec.log +#define OUTSIZE 4096 + char buf[OUTSIZE + 1]; + buf[OUTSIZE] = '\0'; + snprintf(buf, OUTSIZE, "%s", str); + merror("%s: Large message size(length=%d): '%s...'", ARGV0, (int)strlen(str), buf); while(fgets(str, OS_MAXSTR - 2, logff[pos].fp) != NULL) { /* Getting the last occurence of \n */ @@ -112,12 +119,12 @@ void *read_syslog(int pos, int *rc, int drop_it) } __ms = 0; } - + fgetpos(logff[pos].fp, &fp_pos); continue; } - return(NULL); + return(NULL); } /* EOF */ diff --git a/src/logcollector/read_win_el.c b/src/logcollector/read_win_el.c index 7eeda3d..8442f0e 100755 --- a/src/logcollector/read_win_el.c +++ b/src/logcollector/read_win_el.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/logcollector/read_win_el.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -9,9 +10,9 @@ * Foundation */ - + #include "shared.h" -#include "logcollector.h" +#include "logcollector.h" /* This is only for windows */ @@ -46,18 +47,18 @@ void *dll_hash = NULL; /** int startEL(char *app, os_el *el) - * Starts the event logging for each el + * Starts the event logging for each el */ int startEL(char *app, os_el *el) { DWORD NumberOfRecords = 0; - + /* Opening the event log */ el->h = OpenEventLog(NULL, app); if(!el->h) { merror(EVTLOG_OPEN, ARGV0, app); - return(-1); + return(-1); } el->name = app; @@ -77,18 +78,18 @@ int startEL(char *app, os_el *el) el->h = NULL; return(-1); } - + if(NumberOfRecords <= 0) { return(0); } - + return((int)NumberOfRecords); } -/** char *el_getCategory(int category_id) +/** char *el_getCategory(int category_id) * Returns a string related to the category id of the log. */ char *el_getCategory(int category_id) @@ -123,7 +124,7 @@ char *el_getCategory(int category_id) /** char *el_getEventDLL(char *evt_name, char *source, char *event) * Returns the event. */ -char *el_getEventDLL(char *evt_name, char *source, char *event) +char *el_getEventDLL(char *evt_name, char *source, char *event) { char *ret_str; HKEY key; @@ -133,9 +134,9 @@ char *el_getEventDLL(char *evt_name, char *source, char *event) keyname[511] = '\0'; - snprintf(keyname, 510, - "System\\CurrentControlSet\\Services\\EventLog\\%s\\%s", - evt_name, + snprintf(keyname, 510, + "System\\CurrentControlSet\\Services\\EventLog\\%s\\%s", + evt_name, source); @@ -147,16 +148,16 @@ char *el_getEventDLL(char *evt_name, char *source, char *event) } - /* Opening registry */ - if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyname, 0, + /* Opening registry */ + if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyname, 0, KEY_ALL_ACCESS, &key) != ERROR_SUCCESS) { - return(NULL); + return(NULL); } ret = MAX_PATH -1; - if (RegQueryValueEx(key, "EventMessageFile", NULL, + if (RegQueryValueEx(key, "EventMessageFile", NULL, NULL, (LPBYTE)event, &ret) != ERROR_SUCCESS) { event[0] = '\0'; @@ -171,24 +172,24 @@ char *el_getEventDLL(char *evt_name, char *source, char *event) skey = strdup(keyname + 42); sval = strdup(event); - + if(skey && sval) { - OSHash_Add(dll_hash, skey, sval); + OSHash_Add(dll_hash, skey, sval); } else { merror(MEM_ERROR, ARGV0); } } - + RegCloseKey(key); return(event); } -/** char *el_vista_getmessage() +/** char *el_vista_getmessage() * Returns a descriptive message of the event - Vista only. */ char *el_vista_getMessage(int evt_id_int, LPTSTR *el_sstring) @@ -208,15 +209,15 @@ char *el_vista_getMessage(int evt_id_int, LPTSTR *el_sstring) /* Getting descriptive message. */ evt_id[15] = '\0'; snprintf(evt_id, 15, "%d", evt_id_int); - + desc_string = OSHash_Get(vista_sec_id_hash, evt_id); if(!desc_string) { return(NULL); } - - if(!FormatMessage(fm_flags, desc_string, 0, 0, + + if(!FormatMessage(fm_flags, desc_string, 0, 0, (LPTSTR) &message, 0, el_sstring)) { return(NULL); @@ -227,11 +228,11 @@ char *el_vista_getMessage(int evt_id_int, LPTSTR *el_sstring) -/** char *el_getmessage() +/** char *el_getmessage() * Returns a descriptive message of the event. */ -char *el_getMessage(EVENTLOGRECORD *er, char *name, - char * source, LPTSTR *el_sstring) +char *el_getMessage(EVENTLOGRECORD *er, char *name, + char * source, LPTSTR *el_sstring) { DWORD fm_flags = 0; char tmp_str[257]; @@ -257,12 +258,12 @@ char *el_getMessage(EVENTLOGRECORD *er, char *name, /* Get the file name from the registry (stored on event) */ if(!(curr_str = el_getEventDLL(name, source, event))) { - return(NULL); - } + return(NULL); + } - /* If our event has multiple libraries, try each one of them */ + /* If our event has multiple libraries, try each one of them */ while((next_str = strchr(curr_str, ';'))) { *next_str = '\0'; @@ -271,10 +272,10 @@ char *el_getMessage(EVENTLOGRECORD *er, char *name, /* Reverting back old value. */ *next_str = ';'; - + /* Loading library. */ - hevt = LoadLibraryEx(tmp_str, NULL, + hevt = LoadLibraryEx(tmp_str, NULL, DONT_RESOLVE_DLL_REFERENCES | LOAD_LIBRARY_AS_DATAFILE); if(hevt) @@ -282,7 +283,7 @@ char *el_getMessage(EVENTLOGRECORD *er, char *name, if(!FormatMessage(fm_flags, hevt, er->EventID, 0, (LPTSTR) &message, 0, el_sstring)) { - message = NULL; + message = NULL; } FreeLibrary(hevt); @@ -295,20 +296,20 @@ char *el_getMessage(EVENTLOGRECORD *er, char *name, curr_str = next_str +1; } - + /* Getting last value. */ ExpandEnvironmentStrings(curr_str, tmp_str, 255); - hevt = LoadLibraryEx(tmp_str, NULL, + hevt = LoadLibraryEx(tmp_str, NULL, DONT_RESOLVE_DLL_REFERENCES | LOAD_LIBRARY_AS_DATAFILE); if(hevt) { - int hr; - if(!(hr = FormatMessage(fm_flags, hevt, er->EventID, + int hr; + if(!(hr = FormatMessage(fm_flags, hevt, er->EventID, 0, (LPTSTR) &message, 0, el_sstring))) { - message = NULL; + message = NULL; } FreeLibrary(hevt); @@ -324,7 +325,7 @@ char *el_getMessage(EVENTLOGRECORD *er, char *name, /** void readel(os_el *el) * Reads the event log. - */ + */ void readel(os_el *el, int printit) { DWORD _evtid = 65535; @@ -352,7 +353,7 @@ void readel(os_el *el, int printit) LPSTR el_sstring[OS_FLSIZE +1]; /* Er must point to the mbuffer */ - el->er = (EVENTLOGRECORD *) &mbuffer; + el->er = (EVENTLOGRECORD *) &mbuffer; /* Zeroing the values */ el_string[OS_MAXSTR] = '\0'; @@ -369,8 +370,8 @@ void readel(os_el *el, int printit) return; } - /* Reading the event log */ - while(ReadEventLog(el->h, + /* Reading the event log */ + while(ReadEventLog(el->h, EVENTLOG_FORWARDS_READ | EVENTLOG_SEQUENTIAL_READ, 0, el->er, BUFFER_SIZE -1, &read, &needed)) @@ -382,7 +383,7 @@ void readel(os_el *el, int printit) continue; } - + while(read > 0) { @@ -395,7 +396,7 @@ void readel(os_el *el, int printit) /* Getting event id. */ id = (int)el->er->EventID & _evtid; - + /* Initialing domain/user size */ @@ -430,7 +431,7 @@ void readel(os_el *el, int printit) else { merror("%s: Invalid application string (size+)", - ARGV0); + ARGV0); } size_left-=str_size + 2; @@ -444,7 +445,7 @@ void readel(os_el *el, int printit) if(sstr) sstr++; else - break; + break; } /* Get a more descriptive message (if available) */ @@ -455,12 +456,12 @@ void readel(os_el *el, int printit) else { - descriptive_msg = el_getMessage(el->er, - el->name, - source, + descriptive_msg = el_getMessage(el->er, + el->name, + source, el_sstring); } - + if(descriptive_msg != NULL) { /* Remove any \n or \r */ @@ -468,7 +469,7 @@ void readel(os_el *el, int printit) * So whenever we have option:\tvalue\t, it will * become option: value\t */ - tmp_str = descriptive_msg; + tmp_str = descriptive_msg; while(*tmp_str != '\0') { if(*tmp_str == '\n') @@ -480,7 +481,7 @@ void readel(os_el *el, int printit) tmp_str[1] = ' '; tmp_str++; } - + tmp_str++; } } @@ -495,13 +496,13 @@ void readel(os_el *el, int printit) if(el->er->UserSidLength) { SID_NAME_USE account_type; - if(!LookupAccountSid(NULL, - (SID *)((LPSTR)el->er + + if(!LookupAccountSid(NULL, + (SID *)((LPSTR)el->er + el->er->UserSidOffset), - el_user, - &user_size, - el_domain, - &domain_size, + el_user, + &user_size, + el_domain, + &domain_size, &account_type)) { strncpy(el_user, "(no user)", 255); @@ -521,16 +522,16 @@ void readel(os_el *el, int printit) break; case 4634: uid_array_id = 1; - break; + break; case 4647: uid_array_id = 1; - break; + break; case 4769: uid_array_id = 0; break; } - if((uid_array_id >= 0) && + if((uid_array_id >= 0) && el_sstring[uid_array_id] && el_sstring[uid_array_id +1]) { @@ -543,7 +544,7 @@ void readel(os_el *el, int printit) strncpy(el_domain, "no domain", 255); } } - + else { strncpy(el_user, "(no user)", 255); @@ -554,22 +555,22 @@ void readel(os_el *el, int printit) if(printit) { DWORD _evtid = 65535; - int id = (int)el->er->EventID & _evtid; - - final_msg[OS_MAXSTR - OS_LOG_HEADER] = '\0'; - final_msg[OS_MAXSTR - OS_LOG_HEADER -1] = '\0'; - - snprintf(final_msg, OS_MAXSTR - OS_LOG_HEADER -1, - "WinEvtLog: %s: %s(%d): %s: %s: %s: %s: %s", + int id = (int)el->er->EventID & _evtid; + + final_msg[OS_MAXSTR - OS_LOG_HEADER] = '\0'; + final_msg[OS_MAXSTR - OS_LOG_HEADER -1] = '\0'; + + snprintf(final_msg, OS_MAXSTR - OS_LOG_HEADER -1, + "WinEvtLog: %s: %s(%d): %s: %s: %s: %s: %s", el->name, - category, + category, id, source, el_user, el_domain, computer_name, descriptive_msg != NULL?descriptive_msg:el_string); - + if(SendMSG(logr_queue, final_msg, "WinEvtLog", LOCALFILE_MQ) < 0) { @@ -605,7 +606,7 @@ void readel(os_el *el, int printit) char msg_alert[512 +1]; msg_alert[512] = '\0'; merror("%s: WARN: Event log cleared: '%s'", ARGV0, el->name); - + /* Send message about cleared */ snprintf(msg_alert, 512, "ossec: Event log cleared: '%s'", el->name); @@ -619,7 +620,7 @@ void readel(os_el *el, int printit) /* Reopening. */ if(startEL(el->name, el) < 0) { - merror("%s: ERROR: Unable to reopen event log '%s'", + merror("%s: ERROR: Unable to reopen event log '%s'", ARGV0, el->name); } } @@ -660,13 +661,13 @@ void win_read_vista_sec() exit(1); } - + /* Reading the whole file and adding to memory. */ while(fgets(buf, OS_MAXSTR, fp) != NULL) { char *key; char *desc; - + /* Getting the last occurence of \n */ if ((p = strrchr(buf, '\n')) != NULL) { @@ -688,7 +689,7 @@ void win_read_vista_sec() while(*p == ' ') p++; - + /* Allocating memory. */ desc = strdup(p); key = strdup(buf); @@ -698,9 +699,9 @@ void win_read_vista_sec() "description.", ARGV0); continue; } - - - /* Inserting on hash. */ + + + /* Inserting on hash. */ OSHash_Add(vista_sec_id_hash, key, desc); } @@ -714,7 +715,7 @@ void win_read_vista_sec() void win_startel(char *evt_log) { int entries_count = 0; - + /* Maximum size */ if(el_last == 9) { @@ -734,7 +735,7 @@ void win_startel(char *evt_log) } } - + /* Starting event log -- going to last available record */ if((entries_count = startEL(evt_log, &el[el_last])) < 0) { @@ -749,16 +750,16 @@ void win_startel(char *evt_log) } -/** void win_readel() +/** void win_readel() * Reads the event logging for windows */ void win_readel() { int i = 0; - + /* Sleep plus 2 seconds before reading again */ Sleep(2000); - + for(;ititle); } - else if(OS_SendCustomEmail(mond.reports[s]->emailto, mond.reports[s]->title, + else if(OS_SendCustomEmail(mond.reports[s]->emailto, mond.reports[s]->title, mond.smtpserver, mond.emailfrom, mond.reports[s]->r_filter.fp, p) != 0) { merror("%s: WARN: Unable to send report email.", ARGV0); diff --git a/src/monitord/main.c b/src/monitord/main.c index a491529..a4329cd 100755 --- a/src/monitord/main.c +++ b/src/monitord/main.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/monitord/main.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -30,7 +31,7 @@ int main(int argc, char **argv) /* Setting the name */ OS_SetName(ARGV0); - + while((c = getopt(argc, argv, "Vdhtfu:g:D:c:")) != -1){ switch(c){ @@ -60,13 +61,14 @@ int main(int argc, char **argv) if(!optarg) ErrorExit("%s: -D needs an argument",ARGV0); dir=optarg; + break; case 'c': if(!optarg) ErrorExit("%s: -c needs an argument",ARGV0); cfg = optarg; break; case 't': - test_config = 1; + test_config = 1; break; default: help(ARGV0); @@ -154,20 +156,20 @@ int main(int argc, char **argv) if(test_config) exit(0); - - if (!run_foreground) + + if (!run_foreground) { /* Going on daemon mode */ nowDaemon(); goDaemon(); } - + /* Privilege separation */ if(Privsep_SetGroup(gid) < 0) ErrorExit(SETGID_ERROR,ARGV0,group); - + /* chrooting */ if(Privsep_Chroot(dir) < 0) ErrorExit(CHROOT_ERROR,ARGV0,dir); @@ -175,8 +177,8 @@ int main(int argc, char **argv) nowChroot(); - - /* Changing user */ + + /* Changing user */ if(Privsep_SetUser(uid) < 0) ErrorExit(SETUID_ERROR,ARGV0,user); @@ -188,16 +190,16 @@ int main(int argc, char **argv) /* Signal manipulation */ StartSIG(ARGV0); - + /* Creating PID files */ if(CreatePID(ARGV0, getpid()) < 0) ErrorExit(PID_ERROR,ARGV0); - + /* Start up message */ verbose(STARTUP_MSG, ARGV0, (int)getpid()); - + /* the real daemon now */ Monitord(); diff --git a/src/monitord/manage_files.c b/src/monitord/manage_files.c index 7ba33fc..3a33475 100755 --- a/src/monitord/manage_files.c +++ b/src/monitord/manage_files.c @@ -1,11 +1,12 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/monitord/manage_files.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * * This program is a free software; you can redistribute it * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software + * License (version 2) as published by the FSF - Free Software * Foundation */ @@ -27,13 +28,13 @@ void manage_files(int cday, int cmon, int cyear) #ifndef SOLARIS struct tm p_old; #endif - + char elogfile[OS_FLSIZE +1]; char elogfile_old[OS_FLSIZE +1]; - + char alogfile[OS_FLSIZE +1]; char alogfile_old[OS_FLSIZE +1]; - + char flogfile[OS_FLSIZE +1]; char flogfile_old[OS_FLSIZE +1]; @@ -46,7 +47,7 @@ void manage_files(int cday, int cmon, int cyear) #else pp_old = localtime(&tm_old); #endif - + memset(elogfile, '\0', OS_FLSIZE +1); memset(elogfile_old, '\0', OS_FLSIZE +1); @@ -60,7 +61,7 @@ void manage_files(int cday, int cmon, int cyear) * before compressing the file. */ sleep(mond.day_wait); - + /* Event logfile */ snprintf(elogfile, OS_FLSIZE, "%s/%d/%s/ossec-%s-%02d.log", @@ -88,7 +89,7 @@ void manage_files(int cday, int cmon, int cyear) months[cmon], "alerts", cday); - /* alert logfile old */ + /* alert logfile old */ snprintf(alogfile_old, OS_FLSIZE, "%s/%d/%s/ossec-%s-%02d.log", ALERTS, pp_old->tm_year+1900, diff --git a/src/monitord/monitor_agents.c b/src/monitord/monitor_agents.c index 133d31f..fbaac58 100755 --- a/src/monitord/monitor_agents.c +++ b/src/monitord/monitor_agents.c @@ -1,11 +1,12 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/monitord/monitor_agents.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * * This program is a free software; you can redistribute it * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software + * License (version 2) as published by the FSF - Free Software * Foundation */ @@ -39,7 +40,7 @@ void monitor_agents() { int available = 0; char **tmp_av; - + tmp_av = av_agents; while(tmp_av && *tmp_av) { @@ -55,7 +56,7 @@ void monitor_agents() if(available == 0) { char str[OS_SIZE_1024 +1]; - + /* Sending disconnected message */ snprintf(str, OS_SIZE_1024 -1, OS_AG_DISCON, *cr_agents); if(SendMSG(mond.a_queue, str, ARGV0, @@ -64,7 +65,7 @@ void monitor_agents() merror(QUEUE_SEND, ARGV0); } } - + cr_agents++; } diff --git a/src/monitord/monitord.c b/src/monitord/monitord.c index 33ab59d..8ae5c93 100755 --- a/src/monitord/monitord.c +++ b/src/monitord/monitord.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/monitord/monitord.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -18,10 +19,10 @@ /* Real monitord global */ void Monitord() { - time_t tm; - struct tm *p; + time_t tm; + struct tm *p; - int today = 0; + int today = 0; int thismonth = 0; int thisyear = 0; @@ -31,18 +32,18 @@ void Monitord() sleep(10); memset(str, '\0', OS_SIZE_1024 +1); - - + + /* Getting currently time before starting */ tm = time(NULL); p = localtime(&tm); - + today = p->tm_mday; thismonth = p->tm_mon; thisyear = p->tm_year+1900; - - + + /* Connecting to the message queue * Exit if it fails. */ @@ -60,7 +61,7 @@ void Monitord() merror(QUEUE_SEND, ARGV0); } - + /* Main monitor loop */ while(1) { @@ -73,7 +74,7 @@ void Monitord() { monitor_agents(); } - + /* Day changed, deal with log files */ if(today != p->tm_mday) { diff --git a/src/monitord/monitord.h b/src/monitord/monitord.h index 7a9c7a7..c608ca2 100755 --- a/src/monitord/monitord.h +++ b/src/monitord/monitord.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/monitord/monitord.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. diff --git a/src/monitord/report.c b/src/monitord/report.c index 0494132..5d7547a 100755 --- a/src/monitord/report.c +++ b/src/monitord/report.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/monitord/report.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2010 Trend Micro Inc. * All rights reserved. @@ -23,8 +24,13 @@ void report_help() printf("\t-f Filter the results.\n"); printf("\t-r Show related entries.\n"); printf("\t-n Creates a description for the report.\n"); + printf("\t-s Show the alert dump.\n"); + printf("\n"); + printf("\tFilters allowed: group, rule, level, location,\n"); + printf("\t user, srcip, filename\n"); + printf("\n"); printf("Examples:\n"); - printf("\t-f group authentication success (to filter on login success).\n"); + printf("\t-f group authentication_success (to filter on login success).\n"); printf("\t-f level 10 (to filter on level >= 10).\n"); printf("\t-f group authentication -r user srcip (to show the srcip for all users).\n"); exit(1); @@ -51,13 +57,15 @@ int main(int argc, char **argv) /* Setting the name */ OS_SetName(ARGV0); - + r_filter.group = NULL; r_filter.rule = NULL; r_filter.level = NULL; r_filter.location = NULL; r_filter.srcip = NULL; r_filter.user = NULL; + r_filter.files = NULL; + r_filter.show_alerts = 0; r_filter.related_group = 0; r_filter.related_rule = 0; @@ -65,10 +73,11 @@ int main(int argc, char **argv) r_filter.related_location = 0; r_filter.related_srcip = 0; r_filter.related_user = 0; - + r_filter.related_file = 0; + r_filter.report_name = NULL; - while((c = getopt(argc, argv, "Vdhtu:g:D:c:f:v:n:r:")) != -1) + while((c = getopt(argc, argv, "Vdhstu:g:D:c:f:v:n:r:")) != -1) { switch(c){ case 'V': @@ -87,8 +96,8 @@ int main(int argc, char **argv) break; case 'r': if(!optarg || !argv[optind]) - ErrorExit("%s: -r needs two argument",ARGV0); - related_of = optarg; + ErrorExit("%s: -r needs two argument",ARGV0); + related_of = optarg; related_values = argv[optind]; if(os_report_configfilter(related_of, related_values, @@ -104,7 +113,7 @@ int main(int argc, char **argv) filter_by = optarg; filter_value = argv[optind]; - if(os_report_configfilter(filter_by, filter_value, + if(os_report_configfilter(filter_by, filter_value, &r_filter, REPORT_FILTER) < 0) { ErrorExit(CONFIG_ERROR, ARGV0, "user argument"); @@ -125,13 +134,17 @@ int main(int argc, char **argv) if(!optarg) ErrorExit("%s: -D needs an argument",ARGV0); dir=optarg; + break; case 'c': if(!optarg) ErrorExit("%s: -c needs an argument",ARGV0); cfg = optarg; break; case 't': - test_config = 1; + test_config = 1; + break; + case 's': + r_filter.show_alerts = 1; break; default: report_help(); @@ -149,18 +162,18 @@ int main(int argc, char **argv) if((uid < 0)||(gid < 0)) ErrorExit(USER_ERROR,ARGV0,user,group); - + /* Exit here if test config is set */ if(test_config) exit(0); - + /* Privilege separation */ if(Privsep_SetGroup(gid) < 0) ErrorExit(SETGID_ERROR,ARGV0,group); - + /* chrooting */ if(Privsep_Chroot(dir) < 0) ErrorExit(CHROOT_ERROR,ARGV0,dir); @@ -168,8 +181,8 @@ int main(int argc, char **argv) nowChroot(); - - /* Changing user */ + + /* Changing user */ if(Privsep_SetUser(uid) < 0) ErrorExit(SETUID_ERROR,ARGV0,user); @@ -181,16 +194,15 @@ int main(int argc, char **argv) /* Signal manipulation */ StartSIG(ARGV0); - + /* Creating PID files */ if(CreatePID(ARGV0, getpid()) < 0) ErrorExit(PID_ERROR,ARGV0); - + /* Start up message */ verbose(STARTUP_MSG, ARGV0, (int)getpid()); - /* the real stuff now */ os_ReportdStart(&r_filter); diff --git a/src/monitord/sign_log.c b/src/monitord/sign_log.c index bbe1574..40b37b4 100755 --- a/src/monitord/sign_log.c +++ b/src/monitord/sign_log.c @@ -1,11 +1,12 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/monitord/sign_log.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * * This program is a free software; you can redistribute it * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software + * License (version 2) as published by the FSF - Free Software * Foundation */ @@ -54,7 +55,7 @@ void OS_SignLog(char *logfile, char *logfile_old, int log_missing) /* generating sha1 of the old file. */ if(OS_SHA1_File(logfilesum_old, sf_sum_old) < 0) { - merror("%s: No previous sha1 checksum found: '%s'. " + merror("%s: No previous sha1 checksum found: '%s'. " "Starting over.", ARGV0, logfilesum_old); strncpy(sf_sum_old, "none", 6); } @@ -64,7 +65,7 @@ void OS_SignLog(char *logfile, char *logfile_old, int log_missing) if(OS_MD5_File(logfile, mf_sum) < 0) { if(log_missing) - merror("%s: File '%s' not found. MD5 checksum skipped.", + merror("%s: File '%s' not found. MD5 checksum skipped.", ARGV0, logfile); strncpy(mf_sum, "none", 6); } @@ -78,7 +79,7 @@ void OS_SignLog(char *logfile, char *logfile_old, int log_missing) strncpy(sf_sum, "none", 6); } - + fp = fopen(logfilesum, "w"); if(!fp) { @@ -90,7 +91,7 @@ void OS_SignLog(char *logfile, char *logfile_old, int log_missing) fprintf(fp, "Current checksum:\n"); fprintf(fp, "MD5 (%s) = %s\n", logfile, mf_sum); fprintf(fp, "SHA1 (%s) = %s\n\n", logfile, sf_sum); - + fprintf(fp, "Chained checksum:\n"); fprintf(fp, "MD5 (%s) = %s\n", logfilesum_old, mf_sum_old); fprintf(fp, "SHA1 (%s) = %s\n\n", logfilesum_old, sf_sum_old); @@ -98,6 +99,6 @@ void OS_SignLog(char *logfile, char *logfile_old, int log_missing) return; } - + /* EOF */ diff --git a/src/os_auth/Makefile b/src/os_auth/Makefile new file mode 100755 index 0000000..44c7b1b --- /dev/null +++ b/src/os_auth/Makefile @@ -0,0 +1,22 @@ +# Makefile for authd +# Daniel B. Cid + +PT=../ +NAME=ossec-authd + +include ../Config.Make + +LOCAL = ssl.c + +OBJS = ${OS_CONFIG} ${OS_SHARED} ${OS_NET} ${OS_REGEX} ${OS_CRYPTO} ${OS_ZLIB} ${OPENSSLCMD} + +auth1: + ${CC} ${CFLAGS} ${OS_LINK} main-server.c ${LOCAL} ../addagent/validate.c ${OBJS} -o ${NAME} + ${CC} ${CFLAGS} ${OS_LINK} main-client.c ${LOCAL} ../addagent/validate.c ${OBJS} -o agent-auth +clean: + ${CLEAN} + rm -f ossec-authd + rm -f agent-auth +build: + ${BUILD} + cp -pr agent-auth ossec-authd ${PT}../bin diff --git a/src/os_auth/auth.h b/src/os_auth/auth.h new file mode 100755 index 0000000..08f76c7 --- /dev/null +++ b/src/os_auth/auth.h @@ -0,0 +1,57 @@ +/* @(#) $Id: ./src/os_auth/auth.h, 2011/09/08 dcid Exp $ + */ + +/* Copyright (C) 2009 Trend Micro Inc. + * All rights reserved. + * + * This program is a free software; you can redistribute it + * and/or modify it under the terms of the GNU General Public + * License (version 2) as published by the FSF - Free Software + * Foundation + * + * In addition, as a special exception, the copyright holders give + * permission to link the code of portions of this program with the + * OpenSSL library under certain conditions as described in each + * individual source file, and distribute linked combinations + * including the two. + * + * You must obey the GNU General Public License in all respects + * for all of the code used other than OpenSSL. If you modify + * file(s) with this exception, you may extend this exception to your + * version of the file(s), but you are not obligated to do so. If you + * do not wish to do so, delete this exception statement from your + * version. If you delete this exception statement from all source + * files in the program, then also delete it here. + * + */ + + +#ifndef _AUTHD_H +#define _AUTHD_H + +#ifndef ARGV0 + #define ARGV0 "ossec-authd" +#endif + +#include +#include +#include +#include + +#ifdef USE_OPENSSL + +void *os_ssl_keys(int isclient, char *dir); + +#include +#include +#include +#include "os_net/os_net.h" +#include "addagent/manage_agents.h" + +BIO *bio_err; +#define KEYFILE "/etc/sslmanager.key" +#define CERTFILE "/etc/sslmanager.cert" + +#endif + +#endif diff --git a/src/os_auth/main-client.c b/src/os_auth/main-client.c new file mode 100755 index 0000000..4312521 --- /dev/null +++ b/src/os_auth/main-client.c @@ -0,0 +1,323 @@ +/* @(#) $Id: ./src/os_auth/main-client.c, 2012/02/07 dcid Exp $ + */ + +/* Copyright (C) 2010 Trend Micro Inc. + * All rights reserved. + * + * This program is a free software; you can redistribute it + * and/or modify it under the terms of the GNU General Public + * License (version 2) as published by the FSF - Free Software + * Foundation + * + * In addition, as a special exception, the copyright holders give + * permission to link the code of portions of this program with the + * OpenSSL library under certain conditions as described in each + * individual source file, and distribute linked combinations + * including the two. + * + * You must obey the GNU General Public License in all respects + * for all of the code used other than OpenSSL. If you modify + * file(s) with this exception, you may extend this exception to your + * version of the file(s), but you are not obligated to do so. If you + * do not wish to do so, delete this exception statement from your + * version. If you delete this exception statement from all source + * files in the program, then also delete it here. + * + */ + +#include "shared.h" + +#ifndef USE_OPENSSL + +int main() +{ + printf("ERROR: Not compiled. Missing OpenSSL support.\n"); + exit(0); +} + + +#else + +#include +#include "auth.h" + + + +void report_help() +{ + printf("\nOSSEC HIDS %s: Connects to the manager to extract the agent key.\n", ARGV0); + printf("Available options:\n"); + printf("\t-h This help message.\n"); + printf("\t-m Manager IP Address.\n"); + printf("\t-p Manager port (default 1515).\n"); + printf("\t-A Agent name (default is the hostname).\n"); + printf("\t-D Location where OSSEC is installed.\n"); + exit(1); +} + + + +int main(int argc, char **argv) +{ + int c, test_config = 0; + #ifndef WIN32 + int gid = 0; + #endif + + int sock = 0, port = 1515, ret = 0; + char *dir = DEFAULTDIR; + char *user = USER; + char *group = GROUPGLOBAL; + char *cfg = DEFAULTCPATH; + char *manager = NULL; + char *agentname = NULL; + char lhostname[512 + 1]; + char buf[2048 +1]; + SSL_CTX *ctx; + SSL *ssl; + BIO *sbio; + + + bio_err = 0; + buf[2048] = '\0'; + + + /* Setting the name */ + OS_SetName(ARGV0); + + while((c = getopt(argc, argv, "Vdhu:g:D:c:m:p:A:")) != -1) + { + switch(c){ + case 'V': + print_version(); + break; + case 'h': + report_help(); + break; + case 'd': + nowDebug(); + break; + case 'u': + if(!optarg) + ErrorExit("%s: -u needs an argument",ARGV0); + user=optarg; + break; + case 'g': + if(!optarg) + ErrorExit("%s: -g needs an argument",ARGV0); + group=optarg; + break; + case 'D': + if(!optarg) + ErrorExit("%s: -D needs an argument",ARGV0); + dir=optarg; + break; + case 'c': + if(!optarg) + ErrorExit("%s: -c needs an argument",ARGV0); + cfg = optarg; + break; + case 't': + test_config = 1; + break; + case 'm': + if(!optarg) + ErrorExit("%s: -%c needs an argument",ARGV0, c); + manager = optarg; + break; + case 'A': + if(!optarg) + ErrorExit("%s: -%c needs an argument",ARGV0, c); + agentname = optarg; + break; + case 'p': + if(!optarg) + ErrorExit("%s: -%c needs an argument",ARGV0, c); + port = atoi(optarg); + if(port <= 0 || port >= 65536) + { + ErrorExit("%s: Invalid port: %s", ARGV0, optarg); + } + break; + default: + report_help(); + break; + } + } + + /* Starting daemon */ + debug1(STARTED_MSG,ARGV0); + + + #ifndef WIN32 + /* Check if the user/group given are valid */ + gid = Privsep_GetGroup(group); + if(gid < 0) + ErrorExit(USER_ERROR,ARGV0,user,group); + + + + /* Privilege separation */ + if(Privsep_SetGroup(gid) < 0) + ErrorExit(SETGID_ERROR,ARGV0,group); + + + + /* Signal manipulation */ + StartSIG(ARGV0); + + + + /* Creating PID files */ + if(CreatePID(ARGV0, getpid()) < 0) + ErrorExit(PID_ERROR,ARGV0); + #endif + + + /* Start up message */ + verbose(STARTUP_MSG, ARGV0, (int)getpid()); + + + if(agentname == NULL) + { + lhostname[512] = '\0'; + if(gethostname(lhostname, 512 -1) != 0) + { + merror("%s: ERROR: Unable to extract hostname. Custom agent name not set.", ARGV0); + exit(1); + } + agentname = lhostname; + } + + + + /* Starting SSL */ + ctx = os_ssl_keys(1, NULL); + if(!ctx) + { + merror("%s: ERROR: SSL error. Exiting.", ARGV0); + exit(1); + } + + if(!manager) + { + merror("%s: ERROR: Manager IP not set.", ARGV0); + exit(1); + } + + + /* Connecting via TCP */ + sock = OS_ConnectTCP(port, manager, 0); + if(sock <= 0) + { + merror("%s: Unable to connect to %s:%d", ARGV0, manager, port); + exit(1); + } + + + /* Connecting the SSL socket */ + ssl = SSL_new(ctx); + sbio = BIO_new_socket(sock, BIO_NOCLOSE); + SSL_set_bio(ssl, sbio, sbio); + + + ret = SSL_connect(ssl); + if(ret <= 0) + { + ERR_print_errors_fp(stderr); + merror("%s: ERROR: SSL error (%d). Exiting.", ARGV0, ret); + exit(1); + } + + + printf("INFO: Connected to %s:%d\n", manager, port); + printf("INFO: Using agent name as: %s\n", agentname); + + + snprintf(buf, 2048, "OSSEC A:'%s'\n", agentname); + ret = SSL_write(ssl, buf, strlen(buf)); + if(ret < 0) + { + printf("SSL write error (unable to send message.)\n"); + ERR_print_errors_fp(stderr); + exit(1); + } + + printf("INFO: Send request to manager. Waiting for reply.\n"); + + while(1) + { + ret = SSL_read(ssl,buf,sizeof(buf) -1); + switch(SSL_get_error(ssl,ret)) + { + case SSL_ERROR_NONE: + buf[ret] = '\0'; + if(strncmp(buf, "ERROR", 5) == 0) + { + char *tmpstr; + tmpstr = strchr(buf, '\n'); + if(tmpstr) *tmpstr = '\0'; + printf("%s (from manager)\n", buf); + } + else if(strncmp(buf, "OSSEC K:'",9) == 0) + { + char *key; + char *tmpstr; + char **entry; + printf("INFO: Received response with agent key\n"); + + key = buf; + key += 9; + tmpstr = strchr(key, '\''); + if(!tmpstr) + { + printf("ERROR: Invalid key received. Closing connection.\n"); + exit(1); + } + *tmpstr = '\0'; + entry = OS_StrBreak(' ', key, 4); + if(!OS_IsValidID(entry[0]) || !OS_IsValidName(entry[1]) || + !OS_IsValidName(entry[2]) || !OS_IsValidName(entry[3])) + { + printf("ERROR: Invalid key received (2). Closing connection.\n"); + exit(1); + } + + { + FILE *fp; + fp = fopen(KEYSFILE_PATH,"w"); + if(!fp) + { + printf("ERROR: Unable to open key file: %s", KEYSFILE_PATH); + exit(1); + } + fprintf(fp, "%s\n", key); + fclose(fp); + } + printf("INFO: Valid key created. Finished.\n"); + } + break; + case SSL_ERROR_ZERO_RETURN: + case SSL_ERROR_SYSCALL: + printf("INFO: Connection closed.\n"); + exit(0); + break; + default: + printf("ERROR: SSL read (unable to receive message)\n"); + exit(1); + break; + } + + } + + + + /* Shutdown the socket */ + SSL_CTX_free(ctx); + close(sock); + + exit(0); +} + +#endif +/* EOF */ diff --git a/src/os_auth/main-server.c b/src/os_auth/main-server.c new file mode 100755 index 0000000..cf7982a --- /dev/null +++ b/src/os_auth/main-server.c @@ -0,0 +1,379 @@ +/* @(#) $Id$ */ + +/* Copyright (C) 2010 Trend Micro Inc. + * All rights reserved. + * + * This program is a free software; you can redistribute it + * and/or modify it under the terms of the GNU General Public + * License (version 2) as published by the FSF - Free Software + * Foundation + * + * In addition, as a special exception, the copyright holders give + * permission to link the code of portions of this program with the + * OpenSSL library under certain conditions as described in each + * individual source file, and distribute linked combinations + * including the two. + * + * You must obey the GNU General Public License in all respects + * for all of the code used other than OpenSSL. If you modify + * file(s) with this exception, you may extend this exception to your + * version of the file(s), but you are not obligated to do so. If you + * do not wish to do so, delete this exception statement from your + * version. If you delete this exception statement from all source + * files in the program, then also delete it here. + * + */ + + +#include "shared.h" +#include "auth.h" + +/* TODO: Pulled this value out of the sky, may or may not be sane */ +int POOL_SIZE = 512; + +/* ossec-reportd - Runs manual reports. */ +void report_help() +{ +} + +#ifndef USE_OPENSSL +int main() +{ + printf("ERROR: Not compiled. Missing OpenSSL support.\n"); + exit(0); +} +#else + + +int main(int argc, char **argv) +{ + FILE *fp; + // Bucket to keep pids in. + int process_pool[POOL_SIZE]; + // Count of pids we are wait()ing on. + int c = 0, test_config = 0, use_ip_address = 0, pid = 0, status, i = 0, active_processes = 0; + int gid = 0, client_sock = 0, sock = 0, port = 1515, ret = 0; + char *dir = DEFAULTDIR; + char *user = USER; + char *group = GROUPGLOBAL; + char *cfg = DEFAULTCPATH; + char buf[4096 +1]; + SSL_CTX *ctx; + SSL *ssl; + char srcip[IPSIZE +1]; + struct sockaddr_in _nc; + socklen_t _ncl; + + + /* Initializing some variables */ + memset(srcip, '\0', IPSIZE + 1); + memset(process_pool, 0x0, POOL_SIZE); + + bio_err = 0; + + + /* Setting the name */ + OS_SetName(ARGV0); + /* add an option to use the ip on the socket to tie the name to a + specific address */ + while((c = getopt(argc, argv, "Vdhiu:g:D:c:m:p:")) != -1) + { + switch(c){ + case 'V': + print_version(); + break; + case 'h': + report_help(); + break; + case 'd': + nowDebug(); + break; + case 'i': + use_ip_address = 1; + break; + case 'u': + if(!optarg) + ErrorExit("%s: -u needs an argument",ARGV0); + user = optarg; + break; + case 'g': + if(!optarg) + ErrorExit("%s: -g needs an argument",ARGV0); + group = optarg; + break; + case 'D': + if(!optarg) + ErrorExit("%s: -D needs an argument",ARGV0); + dir = optarg; + break; + case 'c': + if(!optarg) + ErrorExit("%s: -c needs an argument",ARGV0); + cfg = optarg; + break; + case 't': + test_config = 1; + break; + case 'p': + if(!optarg) + ErrorExit("%s: -%c needs an argument",ARGV0, c); + port = atoi(optarg); + if(port <= 0 || port >= 65536) + { + ErrorExit("%s: Invalid port: %s", ARGV0, optarg); + } + break; + default: + report_help(); + break; + } + + } + + /* Starting daemon -- NB: need to double fork and setsid */ + debug1(STARTED_MSG,ARGV0); + + /* Check if the user/group given are valid */ + gid = Privsep_GetGroup(group); + if(gid < 0) + ErrorExit(USER_ERROR,ARGV0,user,group); + + + + /* Exit here if test config is set */ + if(test_config) + exit(0); + + + /* Privilege separation */ + if(Privsep_SetGroup(gid) < 0) + ErrorExit(SETGID_ERROR,ARGV0,group); + + + /* chrooting -- TODO: this isn't a chroot. Should also close + unneeded open file descriptors (like stdin/stdout)*/ + chdir(dir); + + + + /* Signal manipulation */ + StartSIG(ARGV0); + + + /* Creating PID files */ + if(CreatePID(ARGV0, getpid()) < 0) + ErrorExit(PID_ERROR,ARGV0); + + /* Start up message */ + verbose(STARTUP_MSG, ARGV0, (int)getpid()); + + + fp = fopen(KEYSFILE_PATH,"a"); + if(!fp) + { + merror("%s: ERROR: Unable to open %s (key file)", ARGV0, KEYSFILE_PATH); + exit(1); + } + + + /* Starting SSL */ + ctx = os_ssl_keys(0, dir); + if(!ctx) + { + merror("%s: ERROR: SSL error. Exiting.", ARGV0); + exit(1); + } + + + /* Connecting via TCP */ + sock = OS_Bindporttcp(port, NULL, 0); + if(sock <= 0) + { + merror("%s: Unable to bind to port %d", ARGV0, port); + exit(1); + } + fcntl(sock, F_SETFL, O_NONBLOCK); + + debug1("%s: DEBUG: Going into listening mode.", ARGV0); + while(1) + { + + // no need to completely pin the cpu + usleep(0); + for (i = 0; i < POOL_SIZE; i++) + { + int rv = 0; + status = 0; + if (process_pool[i]) + { + rv = waitpid(process_pool[i], &status, WNOHANG); + if (rv != 0){ + debug1("%s: DEBUG: Process %d exited", ARGV0, process_pool[i]); + process_pool[i] = 0; + active_processes = active_processes - 1; + } + } + } + memset(&_nc, 0, sizeof(_nc)); + _ncl = sizeof(_nc); + + if((client_sock = accept(sock, (struct sockaddr *) &_nc, &_ncl)) > 0){ + if (active_processes >= POOL_SIZE) + { + merror("%s: Error: Max concurrency reached. Unable to fork", ARGV0); + break; + } + pid = fork(); + if(pid) + { + active_processes = active_processes + 1; + close(client_sock); + for (i = 0; i < POOL_SIZE; i++) + { + if (! process_pool[i]) + { + process_pool[i] = pid; + break; + } + } + } + else + { + strncpy(srcip, inet_ntoa(_nc.sin_addr),IPSIZE -1); + char *agentname = NULL; + ssl = SSL_new(ctx); + SSL_set_fd(ssl, client_sock); + ret = SSL_accept(ssl); + if(ret <= 0) + { + merror("%s: ERROR: SSL Accept error (%d)", ARGV0, ret); + ERR_print_errors_fp(stderr); + } + + verbose("%s: INFO: New connection from %s", ARGV0, srcip); + + ret = SSL_read(ssl, buf, sizeof(buf)); + sleep(1); + if(ret > 0) + { + int parseok = 0; + if(strncmp(buf, "OSSEC A:'", 9) == 0) + { + char *tmpstr = buf; + agentname = tmpstr + 9; + tmpstr += 9; + while(*tmpstr != '\0') + { + if(*tmpstr == '\'') + { + *tmpstr = '\0'; + verbose("%s: INFO: Received request for a new agent (%s) from: %s", ARGV0, agentname, srcip); + parseok = 1; + break; + } + tmpstr++; + } + } + if(parseok == 0) + { + merror("%s: ERROR: Invalid request for new agent from: %s", ARGV0, srcip); + } + else + { + int acount = 2; + char fname[2048 +1]; + char response[2048 +1]; + char *finalkey = NULL; + response[2048] = '\0'; + fname[2048] = '\0'; + if(!OS_IsValidName(agentname)) + { + merror("%s: ERROR: Invalid agent name: %s from %s", ARGV0, agentname, srcip); + snprintf(response, 2048, "ERROR: Invalid agent name: %s\n\n", agentname); + ret = SSL_write(ssl, response, strlen(response)); + snprintf(response, 2048, "ERROR: Unable to add agent.\n\n"); + ret = SSL_write(ssl, response, strlen(response)); + sleep(1); + exit(0); + } + + + /* Checking for a duplicated names. */ + strncpy(fname, agentname, 2048); + while(NameExist(fname)) + { + snprintf(fname, 2048, "%s%d", agentname, acount); + acount++; + if(acount > 256) + { + merror("%s: ERROR: Invalid agent name %s (duplicated)", ARGV0, agentname); + snprintf(response, 2048, "ERROR: Invalid agent name: %s\n\n", agentname); + ret = SSL_write(ssl, response, strlen(response)); + snprintf(response, 2048, "ERROR: Unable to add agent.\n\n"); + ret = SSL_write(ssl, response, strlen(response)); + sleep(1); + exit(0); + } + } + agentname = fname; + + + /* Adding the new agent. */ + if (use_ip_address) + { + finalkey = OS_AddNewAgent(agentname, srcip, NULL, NULL); + } + else + { + finalkey = OS_AddNewAgent(agentname, NULL, NULL, NULL); + } + if(!finalkey) + { + merror("%s: ERROR: Unable to add agent: %s (internal error)", ARGV0, agentname); + snprintf(response, 2048, "ERROR: Internal manager error adding agent: %s\n\n", agentname); + ret = SSL_write(ssl, response, strlen(response)); + snprintf(response, 2048, "ERROR: Unable to add agent.\n\n"); + ret = SSL_write(ssl, response, strlen(response)); + sleep(1); + exit(0); + } + + + snprintf(response, 2048,"OSSEC K:'%s'\n\n", finalkey); + verbose("%s: INFO: Agent key generated for %s (requested by %s)", ARGV0, agentname, srcip); + ret = SSL_write(ssl, response, strlen(response)); + if(ret < 0) + { + merror("%s: ERROR: SSL write error (%d)", ARGV0, ret); + merror("%s: ERROR: Agen key not saved for %s", ARGV0, agentname); + ERR_print_errors_fp(stderr); + } + else + { + verbose("%s: INFO: Agent key created for %s (requested by %s)", ARGV0, agentname, srcip); + } + } + } + else + { + merror("%s: ERROR: SSL read error (%d)", ARGV0, ret); + ERR_print_errors_fp(stderr); + } + SSL_CTX_free(ctx); + close(client_sock); + exit(0); + } + } + } + + + /* Shutdown the socket */ + SSL_CTX_free(ctx); + close(sock); + + exit(0); +} + + +#endif +/* EOF */ diff --git a/src/os_auth/ssl-test.c b/src/os_auth/ssl-test.c new file mode 100644 index 0000000..09146d3 --- /dev/null +++ b/src/os_auth/ssl-test.c @@ -0,0 +1,196 @@ +/* + * + * Copyright (C) 2011 Trend Micro Inc. All rights reserved. + * + * OSSEC HIDS is a free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License (version 2) as + * published by the FSF - Free Software Foundation. + * + * Note that this license applies to the source code, as well as + * decoders, rules and any other data file included with OSSEC (unless + * otherwise specified). + * + * This program is distributed in the hope that it will be useful, but + * is provided AS IS, WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, and + * NON-INFRINGEMENT. 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, see . + * + * In addition, as a special exception, the copyright holders give + * permission to link the code of portions of this program with the + * OpenSSL library under certain conditions as described in each + * individual source file, and distribute linked combinations + * including the two. + * + * You must obey the GNU General Public License in all respects + * for all of the code used other than OpenSSL. If you modify + * file(s) with this exception, you may extend this exception to your + * version of the file(s), but you are not obligated to do so. If you + * do not wish to do so, delete this exception statement from your + * version. If you delete this exception statement from all source + * files in the program, then also delete it here. + * + */ + +#include +#include +#include +#include + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + + +#include +#include +#include + + +#define TEST "GET / HTTP/1.0\r\n\r\n\r\n" + +int main(int argc, char **argv) +{ + int c; + int sock = 0, port = 443, ret = 0; + char *host = NULL; + SSL_CTX *ctx; + SSL *ssl; + SSL_METHOD *sslmeth; + BIO *sbio; + BIO *bio_err = 0; + struct sockaddr_in addr; + + + while((c = getopt(argc, argv, "h:p:")) != -1) + { + switch(c){ + case 'h': + host = optarg; + break; + case 'p': + port = atoi(optarg); + if(port <= 0 || port >= 65536) + { + exit(1); + } + break; + default: + exit(1); + break; + } + } + + if(!bio_err) + { + SSL_library_init(); + SSL_load_error_strings(); + OpenSSL_add_all_algorithms(); + bio_err = BIO_new_fp(stderr,BIO_NOCLOSE); + } + + sslmeth = SSLv23_method(); + ctx = SSL_CTX_new(sslmeth); + if(!ctx) + { + printf("CTX ERROR\n"); + exit(1); + } + + if(!host) + { + printf("ERROR - host not set.\n"); + exit(1); + } + + /* Connecting via TCP */ + sock = socket(AF_INET,SOCK_STREAM, IPPROTO_TCP); + if(sock < 0) + { + printf("sock error\n"); + exit(1); + } + + memset(&addr,0,sizeof(addr)); + addr.sin_addr.s_addr = inet_addr(host); + addr.sin_family=AF_INET; + addr.sin_port=htons(port); + if(connect(sock,(struct sockaddr *)&addr, sizeof(addr)) < 0) + { + printf("connect error\n"); + exit(1); + } + + + + /* Connecting the SSL socket */ + ssl = SSL_new(ctx); + sbio = BIO_new_socket(sock, BIO_NOCLOSE); + SSL_set_bio(ssl, sbio, sbio); + ret = SSL_connect(ssl); + if(ret <= 0) + { + printf("SSL connect error\n"); + ERR_print_errors_fp(stderr); + exit(1); + } + + printf("Connected!\n"); + + + ret=SSL_write(ssl,TEST, sizeof(TEST)); + if(ret < 0) + { + printf("SSL write error\n"); + ERR_print_errors_fp(stderr); + exit(1); + } + + while(1) + { + char buf[2048]; + ret = SSL_read(ssl,buf,sizeof(buf) -1); + printf("ret: %d\n", ret); + switch(SSL_get_error(ssl,ret)) + { + case SSL_ERROR_NONE: + buf[ret] = '\0'; + printf("no error: %s\n", buf); + break; + case SSL_ERROR_ZERO_RETURN: + printf("no returen\n"); + exit(1); + break; + case SSL_ERROR_SYSCALL: + fprintf(stderr, + "SSL Error: Premature close\n"); + exit(1); + break; + default: + printf("default error\n"); + exit(1); + break; + } + + } + + exit(0); +} diff --git a/src/os_auth/ssl.c b/src/os_auth/ssl.c new file mode 100755 index 0000000..9841861 --- /dev/null +++ b/src/os_auth/ssl.c @@ -0,0 +1,108 @@ +/* @(#) $Id: ./src/os_auth/ssl.c, 2011/09/08 dcid Exp $ + */ + +/* Copyright (C) 2010 Trend Micro Inc. + * All rights reserved. + * + * This program is a free software; you can redistribute it + * and/or modify it under the terms of the GNU General Public + * License (version 2) as published by the FSF - Free Software + * Foundation + * + * In addition, as a special exception, the copyright holders give + * permission to link the code of portions of this program with the + * OpenSSL library under certain conditions as described in each + * individual source file, and distribute linked combinations + * including the two. + * + * You must obey the GNU General Public License in all respects + * for all of the code used other than OpenSSL. If you modify + * file(s) with this exception, you may extend this exception to your + * version of the file(s), but you are not obligated to do so. If you + * do not wish to do so, delete this exception statement from your + * version. If you delete this exception statement from all source + * files in the program, then also delete it here. + * + */ + + +#ifdef USE_OPENSSL + +#include "shared.h" +#include "auth.h" + + +void *os_ssl_keys(int isclient, char *dir) +{ + SSL_METHOD *sslmeth; + SSL_CTX *ctx; + char certf[1024 +1]; + char keyf[1024 +1]; + + SSL_library_init(); + SSL_load_error_strings(); + OpenSSL_add_all_algorithms(); + bio_err = BIO_new_fp(stderr,BIO_NOCLOSE); + + + /* Create our context */ + sslmeth = (SSL_METHOD *)SSLv23_method(); + ctx = SSL_CTX_new(sslmeth); + + if(isclient) + { + debug1("%s: DEBUG: Returning CTX for client.", ARGV0); + return(ctx); + } + + if(!dir) + { + return(NULL); + } + + + /* Setting final cert/key files */ + certf[1024] = '\0'; + keyf[1024] = '\0'; + snprintf(certf, 1023, "%s%s", dir, CERTFILE); + snprintf(keyf, 1023, "%s%s", dir, KEYFILE); + + + if(File_DateofChange(certf) <= 0) + { + merror("%s: ERROR: Unable to read certificate file (not found): %s", ARGV0, certf); + return(NULL); + } + + /* Load our keys and certificates*/ + if(!(SSL_CTX_use_certificate_chain_file(ctx, certf))) + { + merror("%s: ERROR: Unable to read certificate file: %s", ARGV0, certf); + ERR_print_errors_fp(stderr); + return(NULL); + } + + if(!(SSL_CTX_use_PrivateKey_file(ctx, keyf, SSL_FILETYPE_PEM))) + { + merror("%s: ERROR: Unable to read private key file: %s", ARGV0, keyf); + return(NULL); + } + + if (!SSL_CTX_check_private_key(ctx)) + { + merror("%s: ERROR: Unable to verify private key file", ARGV0); + return(NULL); + } + + + #if(OPENSSL_VERSION_NUMBER < 0x00905100L) + SSL_CTX_set_verify_depth(ctx,1); + #endif + + return ctx; +} + + +#endif + +/* EOF */ diff --git a/src/os_crypto/blowfish/bf_enc.c b/src/os_crypto/blowfish/bf_enc.c index bbe5b05..6467ee7 100755 --- a/src/os_crypto/blowfish/bf_enc.c +++ b/src/os_crypto/blowfish/bf_enc.c @@ -5,21 +5,21 @@ * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. - * + * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * + * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: @@ -34,10 +34,10 @@ * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from + * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * + * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -49,7 +49,7 @@ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. - * + * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence diff --git a/src/os_crypto/blowfish/bf_locl.h b/src/os_crypto/blowfish/bf_locl.h index 0567cb5..ea7399e 100755 --- a/src/os_crypto/blowfish/bf_locl.h +++ b/src/os_crypto/blowfish/bf_locl.h @@ -10,21 +10,21 @@ * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. - * + * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * + * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: @@ -39,10 +39,10 @@ * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from + * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * + * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -54,7 +54,7 @@ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. - * + * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence diff --git a/src/os_crypto/blowfish/bf_op.c b/src/os_crypto/blowfish/bf_op.c index 6cbff2f..d7a1118 100755 --- a/src/os_crypto/blowfish/bf_op.c +++ b/src/os_crypto/blowfish/bf_op.c @@ -27,7 +27,7 @@ typedef unsigned char uchar; -int OS_BF_Str(char *input, char *output, char *charkey, +int OS_BF_Str(char *input, char *output, char *charkey, long size, short int action) { BF_KEY key; diff --git a/src/os_crypto/blowfish/bf_op.h b/src/os_crypto/blowfish/bf_op.h index 58e98ab..4a4b2b1 100755 --- a/src/os_crypto/blowfish/bf_op.h +++ b/src/os_crypto/blowfish/bf_op.h @@ -21,7 +21,7 @@ #define OS_DECRYPT 0 -int OS_BF_Str(char * input, char *output, char *charkey, +int OS_BF_Str(char * input, char *output, char *charkey, long size, short int action); #endif diff --git a/src/os_crypto/blowfish/bf_pi.h b/src/os_crypto/blowfish/bf_pi.h index 9949513..79d23db 100755 --- a/src/os_crypto/blowfish/bf_pi.h +++ b/src/os_crypto/blowfish/bf_pi.h @@ -5,21 +5,21 @@ * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. - * + * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * + * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: @@ -34,10 +34,10 @@ * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from + * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * + * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -49,7 +49,7 @@ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. - * + * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence @@ -64,262 +64,262 @@ static const BF_KEY bf_init= { 0xc0ac29b7L, 0xc97c50ddL, 0x3f84d5b5L, 0xb5470917L, 0x9216d5d9L, 0x8979fb1b },{ - 0xd1310ba6L, 0x98dfb5acL, 0x2ffd72dbL, 0xd01adfb7L, - 0xb8e1afedL, 0x6a267e96L, 0xba7c9045L, 0xf12c7f99L, - 0x24a19947L, 0xb3916cf7L, 0x0801f2e2L, 0x858efc16L, - 0x636920d8L, 0x71574e69L, 0xa458fea3L, 0xf4933d7eL, - 0x0d95748fL, 0x728eb658L, 0x718bcd58L, 0x82154aeeL, - 0x7b54a41dL, 0xc25a59b5L, 0x9c30d539L, 0x2af26013L, - 0xc5d1b023L, 0x286085f0L, 0xca417918L, 0xb8db38efL, - 0x8e79dcb0L, 0x603a180eL, 0x6c9e0e8bL, 0xb01e8a3eL, - 0xd71577c1L, 0xbd314b27L, 0x78af2fdaL, 0x55605c60L, - 0xe65525f3L, 0xaa55ab94L, 0x57489862L, 0x63e81440L, - 0x55ca396aL, 0x2aab10b6L, 0xb4cc5c34L, 0x1141e8ceL, - 0xa15486afL, 0x7c72e993L, 0xb3ee1411L, 0x636fbc2aL, - 0x2ba9c55dL, 0x741831f6L, 0xce5c3e16L, 0x9b87931eL, - 0xafd6ba33L, 0x6c24cf5cL, 0x7a325381L, 0x28958677L, - 0x3b8f4898L, 0x6b4bb9afL, 0xc4bfe81bL, 0x66282193L, - 0x61d809ccL, 0xfb21a991L, 0x487cac60L, 0x5dec8032L, - 0xef845d5dL, 0xe98575b1L, 0xdc262302L, 0xeb651b88L, - 0x23893e81L, 0xd396acc5L, 0x0f6d6ff3L, 0x83f44239L, - 0x2e0b4482L, 0xa4842004L, 0x69c8f04aL, 0x9e1f9b5eL, - 0x21c66842L, 0xf6e96c9aL, 0x670c9c61L, 0xabd388f0L, - 0x6a51a0d2L, 0xd8542f68L, 0x960fa728L, 0xab5133a3L, - 0x6eef0b6cL, 0x137a3be4L, 0xba3bf050L, 0x7efb2a98L, - 0xa1f1651dL, 0x39af0176L, 0x66ca593eL, 0x82430e88L, - 0x8cee8619L, 0x456f9fb4L, 0x7d84a5c3L, 0x3b8b5ebeL, - 0xe06f75d8L, 0x85c12073L, 0x401a449fL, 0x56c16aa6L, - 0x4ed3aa62L, 0x363f7706L, 0x1bfedf72L, 0x429b023dL, - 0x37d0d724L, 0xd00a1248L, 0xdb0fead3L, 0x49f1c09bL, - 0x075372c9L, 0x80991b7bL, 0x25d479d8L, 0xf6e8def7L, - 0xe3fe501aL, 0xb6794c3bL, 0x976ce0bdL, 0x04c006baL, - 0xc1a94fb6L, 0x409f60c4L, 0x5e5c9ec2L, 0x196a2463L, - 0x68fb6fafL, 0x3e6c53b5L, 0x1339b2ebL, 0x3b52ec6fL, - 0x6dfc511fL, 0x9b30952cL, 0xcc814544L, 0xaf5ebd09L, - 0xbee3d004L, 0xde334afdL, 0x660f2807L, 0x192e4bb3L, - 0xc0cba857L, 0x45c8740fL, 0xd20b5f39L, 0xb9d3fbdbL, - 0x5579c0bdL, 0x1a60320aL, 0xd6a100c6L, 0x402c7279L, - 0x679f25feL, 0xfb1fa3ccL, 0x8ea5e9f8L, 0xdb3222f8L, - 0x3c7516dfL, 0xfd616b15L, 0x2f501ec8L, 0xad0552abL, - 0x323db5faL, 0xfd238760L, 0x53317b48L, 0x3e00df82L, - 0x9e5c57bbL, 0xca6f8ca0L, 0x1a87562eL, 0xdf1769dbL, - 0xd542a8f6L, 0x287effc3L, 0xac6732c6L, 0x8c4f5573L, - 0x695b27b0L, 0xbbca58c8L, 0xe1ffa35dL, 0xb8f011a0L, - 0x10fa3d98L, 0xfd2183b8L, 0x4afcb56cL, 0x2dd1d35bL, - 0x9a53e479L, 0xb6f84565L, 0xd28e49bcL, 0x4bfb9790L, - 0xe1ddf2daL, 0xa4cb7e33L, 0x62fb1341L, 0xcee4c6e8L, - 0xef20cadaL, 0x36774c01L, 0xd07e9efeL, 0x2bf11fb4L, - 0x95dbda4dL, 0xae909198L, 0xeaad8e71L, 0x6b93d5a0L, - 0xd08ed1d0L, 0xafc725e0L, 0x8e3c5b2fL, 0x8e7594b7L, - 0x8ff6e2fbL, 0xf2122b64L, 0x8888b812L, 0x900df01cL, - 0x4fad5ea0L, 0x688fc31cL, 0xd1cff191L, 0xb3a8c1adL, - 0x2f2f2218L, 0xbe0e1777L, 0xea752dfeL, 0x8b021fa1L, - 0xe5a0cc0fL, 0xb56f74e8L, 0x18acf3d6L, 0xce89e299L, - 0xb4a84fe0L, 0xfd13e0b7L, 0x7cc43b81L, 0xd2ada8d9L, - 0x165fa266L, 0x80957705L, 0x93cc7314L, 0x211a1477L, - 0xe6ad2065L, 0x77b5fa86L, 0xc75442f5L, 0xfb9d35cfL, - 0xebcdaf0cL, 0x7b3e89a0L, 0xd6411bd3L, 0xae1e7e49L, - 0x00250e2dL, 0x2071b35eL, 0x226800bbL, 0x57b8e0afL, - 0x2464369bL, 0xf009b91eL, 0x5563911dL, 0x59dfa6aaL, - 0x78c14389L, 0xd95a537fL, 0x207d5ba2L, 0x02e5b9c5L, - 0x83260376L, 0x6295cfa9L, 0x11c81968L, 0x4e734a41L, - 0xb3472dcaL, 0x7b14a94aL, 0x1b510052L, 0x9a532915L, - 0xd60f573fL, 0xbc9bc6e4L, 0x2b60a476L, 0x81e67400L, - 0x08ba6fb5L, 0x571be91fL, 0xf296ec6bL, 0x2a0dd915L, - 0xb6636521L, 0xe7b9f9b6L, 0xff34052eL, 0xc5855664L, - 0x53b02d5dL, 0xa99f8fa1L, 0x08ba4799L, 0x6e85076aL, - 0x4b7a70e9L, 0xb5b32944L, 0xdb75092eL, 0xc4192623L, - 0xad6ea6b0L, 0x49a7df7dL, 0x9cee60b8L, 0x8fedb266L, - 0xecaa8c71L, 0x699a17ffL, 0x5664526cL, 0xc2b19ee1L, - 0x193602a5L, 0x75094c29L, 0xa0591340L, 0xe4183a3eL, - 0x3f54989aL, 0x5b429d65L, 0x6b8fe4d6L, 0x99f73fd6L, - 0xa1d29c07L, 0xefe830f5L, 0x4d2d38e6L, 0xf0255dc1L, - 0x4cdd2086L, 0x8470eb26L, 0x6382e9c6L, 0x021ecc5eL, - 0x09686b3fL, 0x3ebaefc9L, 0x3c971814L, 0x6b6a70a1L, - 0x687f3584L, 0x52a0e286L, 0xb79c5305L, 0xaa500737L, - 0x3e07841cL, 0x7fdeae5cL, 0x8e7d44ecL, 0x5716f2b8L, - 0xb03ada37L, 0xf0500c0dL, 0xf01c1f04L, 0x0200b3ffL, - 0xae0cf51aL, 0x3cb574b2L, 0x25837a58L, 0xdc0921bdL, - 0xd19113f9L, 0x7ca92ff6L, 0x94324773L, 0x22f54701L, - 0x3ae5e581L, 0x37c2dadcL, 0xc8b57634L, 0x9af3dda7L, - 0xa9446146L, 0x0fd0030eL, 0xecc8c73eL, 0xa4751e41L, - 0xe238cd99L, 0x3bea0e2fL, 0x3280bba1L, 0x183eb331L, - 0x4e548b38L, 0x4f6db908L, 0x6f420d03L, 0xf60a04bfL, - 0x2cb81290L, 0x24977c79L, 0x5679b072L, 0xbcaf89afL, - 0xde9a771fL, 0xd9930810L, 0xb38bae12L, 0xdccf3f2eL, - 0x5512721fL, 0x2e6b7124L, 0x501adde6L, 0x9f84cd87L, - 0x7a584718L, 0x7408da17L, 0xbc9f9abcL, 0xe94b7d8cL, - 0xec7aec3aL, 0xdb851dfaL, 0x63094366L, 0xc464c3d2L, - 0xef1c1847L, 0x3215d908L, 0xdd433b37L, 0x24c2ba16L, - 0x12a14d43L, 0x2a65c451L, 0x50940002L, 0x133ae4ddL, - 0x71dff89eL, 0x10314e55L, 0x81ac77d6L, 0x5f11199bL, - 0x043556f1L, 0xd7a3c76bL, 0x3c11183bL, 0x5924a509L, - 0xf28fe6edL, 0x97f1fbfaL, 0x9ebabf2cL, 0x1e153c6eL, - 0x86e34570L, 0xeae96fb1L, 0x860e5e0aL, 0x5a3e2ab3L, - 0x771fe71cL, 0x4e3d06faL, 0x2965dcb9L, 0x99e71d0fL, - 0x803e89d6L, 0x5266c825L, 0x2e4cc978L, 0x9c10b36aL, - 0xc6150ebaL, 0x94e2ea78L, 0xa5fc3c53L, 0x1e0a2df4L, - 0xf2f74ea7L, 0x361d2b3dL, 0x1939260fL, 0x19c27960L, - 0x5223a708L, 0xf71312b6L, 0xebadfe6eL, 0xeac31f66L, - 0xe3bc4595L, 0xa67bc883L, 0xb17f37d1L, 0x018cff28L, - 0xc332ddefL, 0xbe6c5aa5L, 0x65582185L, 0x68ab9802L, - 0xeecea50fL, 0xdb2f953bL, 0x2aef7dadL, 0x5b6e2f84L, - 0x1521b628L, 0x29076170L, 0xecdd4775L, 0x619f1510L, - 0x13cca830L, 0xeb61bd96L, 0x0334fe1eL, 0xaa0363cfL, - 0xb5735c90L, 0x4c70a239L, 0xd59e9e0bL, 0xcbaade14L, - 0xeecc86bcL, 0x60622ca7L, 0x9cab5cabL, 0xb2f3846eL, - 0x648b1eafL, 0x19bdf0caL, 0xa02369b9L, 0x655abb50L, - 0x40685a32L, 0x3c2ab4b3L, 0x319ee9d5L, 0xc021b8f7L, - 0x9b540b19L, 0x875fa099L, 0x95f7997eL, 0x623d7da8L, - 0xf837889aL, 0x97e32d77L, 0x11ed935fL, 0x16681281L, - 0x0e358829L, 0xc7e61fd6L, 0x96dedfa1L, 0x7858ba99L, - 0x57f584a5L, 0x1b227263L, 0x9b83c3ffL, 0x1ac24696L, - 0xcdb30aebL, 0x532e3054L, 0x8fd948e4L, 0x6dbc3128L, - 0x58ebf2efL, 0x34c6ffeaL, 0xfe28ed61L, 0xee7c3c73L, - 0x5d4a14d9L, 0xe864b7e3L, 0x42105d14L, 0x203e13e0L, - 0x45eee2b6L, 0xa3aaabeaL, 0xdb6c4f15L, 0xfacb4fd0L, - 0xc742f442L, 0xef6abbb5L, 0x654f3b1dL, 0x41cd2105L, - 0xd81e799eL, 0x86854dc7L, 0xe44b476aL, 0x3d816250L, - 0xcf62a1f2L, 0x5b8d2646L, 0xfc8883a0L, 0xc1c7b6a3L, - 0x7f1524c3L, 0x69cb7492L, 0x47848a0bL, 0x5692b285L, - 0x095bbf00L, 0xad19489dL, 0x1462b174L, 0x23820e00L, - 0x58428d2aL, 0x0c55f5eaL, 0x1dadf43eL, 0x233f7061L, - 0x3372f092L, 0x8d937e41L, 0xd65fecf1L, 0x6c223bdbL, - 0x7cde3759L, 0xcbee7460L, 0x4085f2a7L, 0xce77326eL, - 0xa6078084L, 0x19f8509eL, 0xe8efd855L, 0x61d99735L, - 0xa969a7aaL, 0xc50c06c2L, 0x5a04abfcL, 0x800bcadcL, - 0x9e447a2eL, 0xc3453484L, 0xfdd56705L, 0x0e1e9ec9L, - 0xdb73dbd3L, 0x105588cdL, 0x675fda79L, 0xe3674340L, - 0xc5c43465L, 0x713e38d8L, 0x3d28f89eL, 0xf16dff20L, - 0x153e21e7L, 0x8fb03d4aL, 0xe6e39f2bL, 0xdb83adf7L, - 0xe93d5a68L, 0x948140f7L, 0xf64c261cL, 0x94692934L, - 0x411520f7L, 0x7602d4f7L, 0xbcf46b2eL, 0xd4a20068L, - 0xd4082471L, 0x3320f46aL, 0x43b7d4b7L, 0x500061afL, - 0x1e39f62eL, 0x97244546L, 0x14214f74L, 0xbf8b8840L, - 0x4d95fc1dL, 0x96b591afL, 0x70f4ddd3L, 0x66a02f45L, - 0xbfbc09ecL, 0x03bd9785L, 0x7fac6dd0L, 0x31cb8504L, - 0x96eb27b3L, 0x55fd3941L, 0xda2547e6L, 0xabca0a9aL, - 0x28507825L, 0x530429f4L, 0x0a2c86daL, 0xe9b66dfbL, - 0x68dc1462L, 0xd7486900L, 0x680ec0a4L, 0x27a18deeL, - 0x4f3ffea2L, 0xe887ad8cL, 0xb58ce006L, 0x7af4d6b6L, - 0xaace1e7cL, 0xd3375fecL, 0xce78a399L, 0x406b2a42L, - 0x20fe9e35L, 0xd9f385b9L, 0xee39d7abL, 0x3b124e8bL, - 0x1dc9faf7L, 0x4b6d1856L, 0x26a36631L, 0xeae397b2L, - 0x3a6efa74L, 0xdd5b4332L, 0x6841e7f7L, 0xca7820fbL, - 0xfb0af54eL, 0xd8feb397L, 0x454056acL, 0xba489527L, - 0x55533a3aL, 0x20838d87L, 0xfe6ba9b7L, 0xd096954bL, - 0x55a867bcL, 0xa1159a58L, 0xcca92963L, 0x99e1db33L, - 0xa62a4a56L, 0x3f3125f9L, 0x5ef47e1cL, 0x9029317cL, - 0xfdf8e802L, 0x04272f70L, 0x80bb155cL, 0x05282ce3L, - 0x95c11548L, 0xe4c66d22L, 0x48c1133fL, 0xc70f86dcL, - 0x07f9c9eeL, 0x41041f0fL, 0x404779a4L, 0x5d886e17L, - 0x325f51ebL, 0xd59bc0d1L, 0xf2bcc18fL, 0x41113564L, - 0x257b7834L, 0x602a9c60L, 0xdff8e8a3L, 0x1f636c1bL, - 0x0e12b4c2L, 0x02e1329eL, 0xaf664fd1L, 0xcad18115L, - 0x6b2395e0L, 0x333e92e1L, 0x3b240b62L, 0xeebeb922L, - 0x85b2a20eL, 0xe6ba0d99L, 0xde720c8cL, 0x2da2f728L, - 0xd0127845L, 0x95b794fdL, 0x647d0862L, 0xe7ccf5f0L, - 0x5449a36fL, 0x877d48faL, 0xc39dfd27L, 0xf33e8d1eL, - 0x0a476341L, 0x992eff74L, 0x3a6f6eabL, 0xf4f8fd37L, - 0xa812dc60L, 0xa1ebddf8L, 0x991be14cL, 0xdb6e6b0dL, - 0xc67b5510L, 0x6d672c37L, 0x2765d43bL, 0xdcd0e804L, - 0xf1290dc7L, 0xcc00ffa3L, 0xb5390f92L, 0x690fed0bL, - 0x667b9ffbL, 0xcedb7d9cL, 0xa091cf0bL, 0xd9155ea3L, - 0xbb132f88L, 0x515bad24L, 0x7b9479bfL, 0x763bd6ebL, - 0x37392eb3L, 0xcc115979L, 0x8026e297L, 0xf42e312dL, - 0x6842ada7L, 0xc66a2b3bL, 0x12754cccL, 0x782ef11cL, - 0x6a124237L, 0xb79251e7L, 0x06a1bbe6L, 0x4bfb6350L, - 0x1a6b1018L, 0x11caedfaL, 0x3d25bdd8L, 0xe2e1c3c9L, - 0x44421659L, 0x0a121386L, 0xd90cec6eL, 0xd5abea2aL, - 0x64af674eL, 0xda86a85fL, 0xbebfe988L, 0x64e4c3feL, - 0x9dbc8057L, 0xf0f7c086L, 0x60787bf8L, 0x6003604dL, - 0xd1fd8346L, 0xf6381fb0L, 0x7745ae04L, 0xd736fcccL, - 0x83426b33L, 0xf01eab71L, 0xb0804187L, 0x3c005e5fL, - 0x77a057beL, 0xbde8ae24L, 0x55464299L, 0xbf582e61L, - 0x4e58f48fL, 0xf2ddfda2L, 0xf474ef38L, 0x8789bdc2L, - 0x5366f9c3L, 0xc8b38e74L, 0xb475f255L, 0x46fcd9b9L, - 0x7aeb2661L, 0x8b1ddf84L, 0x846a0e79L, 0x915f95e2L, - 0x466e598eL, 0x20b45770L, 0x8cd55591L, 0xc902de4cL, - 0xb90bace1L, 0xbb8205d0L, 0x11a86248L, 0x7574a99eL, - 0xb77f19b6L, 0xe0a9dc09L, 0x662d09a1L, 0xc4324633L, - 0xe85a1f02L, 0x09f0be8cL, 0x4a99a025L, 0x1d6efe10L, - 0x1ab93d1dL, 0x0ba5a4dfL, 0xa186f20fL, 0x2868f169L, - 0xdcb7da83L, 0x573906feL, 0xa1e2ce9bL, 0x4fcd7f52L, - 0x50115e01L, 0xa70683faL, 0xa002b5c4L, 0x0de6d027L, - 0x9af88c27L, 0x773f8641L, 0xc3604c06L, 0x61a806b5L, - 0xf0177a28L, 0xc0f586e0L, 0x006058aaL, 0x30dc7d62L, - 0x11e69ed7L, 0x2338ea63L, 0x53c2dd94L, 0xc2c21634L, - 0xbbcbee56L, 0x90bcb6deL, 0xebfc7da1L, 0xce591d76L, - 0x6f05e409L, 0x4b7c0188L, 0x39720a3dL, 0x7c927c24L, - 0x86e3725fL, 0x724d9db9L, 0x1ac15bb4L, 0xd39eb8fcL, - 0xed545578L, 0x08fca5b5L, 0xd83d7cd3L, 0x4dad0fc4L, - 0x1e50ef5eL, 0xb161e6f8L, 0xa28514d9L, 0x6c51133cL, - 0x6fd5c7e7L, 0x56e14ec4L, 0x362abfceL, 0xddc6c837L, - 0xd79a3234L, 0x92638212L, 0x670efa8eL, 0x406000e0L, - 0x3a39ce37L, 0xd3faf5cfL, 0xabc27737L, 0x5ac52d1bL, - 0x5cb0679eL, 0x4fa33742L, 0xd3822740L, 0x99bc9bbeL, - 0xd5118e9dL, 0xbf0f7315L, 0xd62d1c7eL, 0xc700c47bL, - 0xb78c1b6bL, 0x21a19045L, 0xb26eb1beL, 0x6a366eb4L, - 0x5748ab2fL, 0xbc946e79L, 0xc6a376d2L, 0x6549c2c8L, - 0x530ff8eeL, 0x468dde7dL, 0xd5730a1dL, 0x4cd04dc6L, - 0x2939bbdbL, 0xa9ba4650L, 0xac9526e8L, 0xbe5ee304L, - 0xa1fad5f0L, 0x6a2d519aL, 0x63ef8ce2L, 0x9a86ee22L, - 0xc089c2b8L, 0x43242ef6L, 0xa51e03aaL, 0x9cf2d0a4L, - 0x83c061baL, 0x9be96a4dL, 0x8fe51550L, 0xba645bd6L, - 0x2826a2f9L, 0xa73a3ae1L, 0x4ba99586L, 0xef5562e9L, - 0xc72fefd3L, 0xf752f7daL, 0x3f046f69L, 0x77fa0a59L, - 0x80e4a915L, 0x87b08601L, 0x9b09e6adL, 0x3b3ee593L, - 0xe990fd5aL, 0x9e34d797L, 0x2cf0b7d9L, 0x022b8b51L, - 0x96d5ac3aL, 0x017da67dL, 0xd1cf3ed6L, 0x7c7d2d28L, - 0x1f9f25cfL, 0xadf2b89bL, 0x5ad6b472L, 0x5a88f54cL, - 0xe029ac71L, 0xe019a5e6L, 0x47b0acfdL, 0xed93fa9bL, - 0xe8d3c48dL, 0x283b57ccL, 0xf8d56629L, 0x79132e28L, - 0x785f0191L, 0xed756055L, 0xf7960e44L, 0xe3d35e8cL, - 0x15056dd4L, 0x88f46dbaL, 0x03a16125L, 0x0564f0bdL, - 0xc3eb9e15L, 0x3c9057a2L, 0x97271aecL, 0xa93a072aL, - 0x1b3f6d9bL, 0x1e6321f5L, 0xf59c66fbL, 0x26dcf319L, - 0x7533d928L, 0xb155fdf5L, 0x03563482L, 0x8aba3cbbL, - 0x28517711L, 0xc20ad9f8L, 0xabcc5167L, 0xccad925fL, - 0x4de81751L, 0x3830dc8eL, 0x379d5862L, 0x9320f991L, - 0xea7a90c2L, 0xfb3e7bceL, 0x5121ce64L, 0x774fbe32L, - 0xa8b6e37eL, 0xc3293d46L, 0x48de5369L, 0x6413e680L, - 0xa2ae0810L, 0xdd6db224L, 0x69852dfdL, 0x09072166L, - 0xb39a460aL, 0x6445c0ddL, 0x586cdecfL, 0x1c20c8aeL, - 0x5bbef7ddL, 0x1b588d40L, 0xccd2017fL, 0x6bb4e3bbL, - 0xdda26a7eL, 0x3a59ff45L, 0x3e350a44L, 0xbcb4cdd5L, - 0x72eacea8L, 0xfa6484bbL, 0x8d6612aeL, 0xbf3c6f47L, - 0xd29be463L, 0x542f5d9eL, 0xaec2771bL, 0xf64e6370L, - 0x740e0d8dL, 0xe75b1357L, 0xf8721671L, 0xaf537d5dL, - 0x4040cb08L, 0x4eb4e2ccL, 0x34d2466aL, 0x0115af84L, - 0xe1b00428L, 0x95983a1dL, 0x06b89fb4L, 0xce6ea048L, - 0x6f3f3b82L, 0x3520ab82L, 0x011a1d4bL, 0x277227f8L, - 0x611560b1L, 0xe7933fdcL, 0xbb3a792bL, 0x344525bdL, - 0xa08839e1L, 0x51ce794bL, 0x2f32c9b7L, 0xa01fbac9L, - 0xe01cc87eL, 0xbcc7d1f6L, 0xcf0111c3L, 0xa1e8aac7L, - 0x1a908749L, 0xd44fbd9aL, 0xd0dadecbL, 0xd50ada38L, - 0x0339c32aL, 0xc6913667L, 0x8df9317cL, 0xe0b12b4fL, - 0xf79e59b7L, 0x43f5bb3aL, 0xf2d519ffL, 0x27d9459cL, - 0xbf97222cL, 0x15e6fc2aL, 0x0f91fc71L, 0x9b941525L, - 0xfae59361L, 0xceb69cebL, 0xc2a86459L, 0x12baa8d1L, - 0xb6c1075eL, 0xe3056a0cL, 0x10d25065L, 0xcb03a442L, - 0xe0ec6e0eL, 0x1698db3bL, 0x4c98a0beL, 0x3278e964L, - 0x9f1f9532L, 0xe0d392dfL, 0xd3a0342bL, 0x8971f21eL, - 0x1b0a7441L, 0x4ba3348cL, 0xc5be7120L, 0xc37632d8L, - 0xdf359f8dL, 0x9b992f2eL, 0xe60b6f47L, 0x0fe3f11dL, - 0xe54cda54L, 0x1edad891L, 0xce6279cfL, 0xcd3e7e6fL, - 0x1618b166L, 0xfd2c1d05L, 0x848fd2c5L, 0xf6fb2299L, - 0xf523f357L, 0xa6327623L, 0x93a83531L, 0x56cccd02L, - 0xacf08162L, 0x5a75ebb5L, 0x6e163697L, 0x88d273ccL, - 0xde966292L, 0x81b949d0L, 0x4c50901bL, 0x71c65614L, - 0xe6c6c7bdL, 0x327a140aL, 0x45e1d006L, 0xc3f27b9aL, - 0xc9aa53fdL, 0x62a80f00L, 0xbb25bfe2L, 0x35bdd2f6L, - 0x71126905L, 0xb2040222L, 0xb6cbcf7cL, 0xcd769c2bL, - 0x53113ec0L, 0x1640e3d3L, 0x38abbd60L, 0x2547adf0L, - 0xba38209cL, 0xf746ce76L, 0x77afa1c5L, 0x20756060L, - 0x85cbfe4eL, 0x8ae88dd8L, 0x7aaaf9b0L, 0x4cf9aa7eL, - 0x1948c25cL, 0x02fb8a8cL, 0x01c36ae4L, 0xd6ebe1f9L, - 0x90d4f869L, 0xa65cdea0L, 0x3f09252dL, 0xc208e69fL, - 0xb74e6132L, 0xce77e25bL, 0x578fdfe3L, 0x3ac372e6L, + 0xd1310ba6L, 0x98dfb5acL, 0x2ffd72dbL, 0xd01adfb7L, + 0xb8e1afedL, 0x6a267e96L, 0xba7c9045L, 0xf12c7f99L, + 0x24a19947L, 0xb3916cf7L, 0x0801f2e2L, 0x858efc16L, + 0x636920d8L, 0x71574e69L, 0xa458fea3L, 0xf4933d7eL, + 0x0d95748fL, 0x728eb658L, 0x718bcd58L, 0x82154aeeL, + 0x7b54a41dL, 0xc25a59b5L, 0x9c30d539L, 0x2af26013L, + 0xc5d1b023L, 0x286085f0L, 0xca417918L, 0xb8db38efL, + 0x8e79dcb0L, 0x603a180eL, 0x6c9e0e8bL, 0xb01e8a3eL, + 0xd71577c1L, 0xbd314b27L, 0x78af2fdaL, 0x55605c60L, + 0xe65525f3L, 0xaa55ab94L, 0x57489862L, 0x63e81440L, + 0x55ca396aL, 0x2aab10b6L, 0xb4cc5c34L, 0x1141e8ceL, + 0xa15486afL, 0x7c72e993L, 0xb3ee1411L, 0x636fbc2aL, + 0x2ba9c55dL, 0x741831f6L, 0xce5c3e16L, 0x9b87931eL, + 0xafd6ba33L, 0x6c24cf5cL, 0x7a325381L, 0x28958677L, + 0x3b8f4898L, 0x6b4bb9afL, 0xc4bfe81bL, 0x66282193L, + 0x61d809ccL, 0xfb21a991L, 0x487cac60L, 0x5dec8032L, + 0xef845d5dL, 0xe98575b1L, 0xdc262302L, 0xeb651b88L, + 0x23893e81L, 0xd396acc5L, 0x0f6d6ff3L, 0x83f44239L, + 0x2e0b4482L, 0xa4842004L, 0x69c8f04aL, 0x9e1f9b5eL, + 0x21c66842L, 0xf6e96c9aL, 0x670c9c61L, 0xabd388f0L, + 0x6a51a0d2L, 0xd8542f68L, 0x960fa728L, 0xab5133a3L, + 0x6eef0b6cL, 0x137a3be4L, 0xba3bf050L, 0x7efb2a98L, + 0xa1f1651dL, 0x39af0176L, 0x66ca593eL, 0x82430e88L, + 0x8cee8619L, 0x456f9fb4L, 0x7d84a5c3L, 0x3b8b5ebeL, + 0xe06f75d8L, 0x85c12073L, 0x401a449fL, 0x56c16aa6L, + 0x4ed3aa62L, 0x363f7706L, 0x1bfedf72L, 0x429b023dL, + 0x37d0d724L, 0xd00a1248L, 0xdb0fead3L, 0x49f1c09bL, + 0x075372c9L, 0x80991b7bL, 0x25d479d8L, 0xf6e8def7L, + 0xe3fe501aL, 0xb6794c3bL, 0x976ce0bdL, 0x04c006baL, + 0xc1a94fb6L, 0x409f60c4L, 0x5e5c9ec2L, 0x196a2463L, + 0x68fb6fafL, 0x3e6c53b5L, 0x1339b2ebL, 0x3b52ec6fL, + 0x6dfc511fL, 0x9b30952cL, 0xcc814544L, 0xaf5ebd09L, + 0xbee3d004L, 0xde334afdL, 0x660f2807L, 0x192e4bb3L, + 0xc0cba857L, 0x45c8740fL, 0xd20b5f39L, 0xb9d3fbdbL, + 0x5579c0bdL, 0x1a60320aL, 0xd6a100c6L, 0x402c7279L, + 0x679f25feL, 0xfb1fa3ccL, 0x8ea5e9f8L, 0xdb3222f8L, + 0x3c7516dfL, 0xfd616b15L, 0x2f501ec8L, 0xad0552abL, + 0x323db5faL, 0xfd238760L, 0x53317b48L, 0x3e00df82L, + 0x9e5c57bbL, 0xca6f8ca0L, 0x1a87562eL, 0xdf1769dbL, + 0xd542a8f6L, 0x287effc3L, 0xac6732c6L, 0x8c4f5573L, + 0x695b27b0L, 0xbbca58c8L, 0xe1ffa35dL, 0xb8f011a0L, + 0x10fa3d98L, 0xfd2183b8L, 0x4afcb56cL, 0x2dd1d35bL, + 0x9a53e479L, 0xb6f84565L, 0xd28e49bcL, 0x4bfb9790L, + 0xe1ddf2daL, 0xa4cb7e33L, 0x62fb1341L, 0xcee4c6e8L, + 0xef20cadaL, 0x36774c01L, 0xd07e9efeL, 0x2bf11fb4L, + 0x95dbda4dL, 0xae909198L, 0xeaad8e71L, 0x6b93d5a0L, + 0xd08ed1d0L, 0xafc725e0L, 0x8e3c5b2fL, 0x8e7594b7L, + 0x8ff6e2fbL, 0xf2122b64L, 0x8888b812L, 0x900df01cL, + 0x4fad5ea0L, 0x688fc31cL, 0xd1cff191L, 0xb3a8c1adL, + 0x2f2f2218L, 0xbe0e1777L, 0xea752dfeL, 0x8b021fa1L, + 0xe5a0cc0fL, 0xb56f74e8L, 0x18acf3d6L, 0xce89e299L, + 0xb4a84fe0L, 0xfd13e0b7L, 0x7cc43b81L, 0xd2ada8d9L, + 0x165fa266L, 0x80957705L, 0x93cc7314L, 0x211a1477L, + 0xe6ad2065L, 0x77b5fa86L, 0xc75442f5L, 0xfb9d35cfL, + 0xebcdaf0cL, 0x7b3e89a0L, 0xd6411bd3L, 0xae1e7e49L, + 0x00250e2dL, 0x2071b35eL, 0x226800bbL, 0x57b8e0afL, + 0x2464369bL, 0xf009b91eL, 0x5563911dL, 0x59dfa6aaL, + 0x78c14389L, 0xd95a537fL, 0x207d5ba2L, 0x02e5b9c5L, + 0x83260376L, 0x6295cfa9L, 0x11c81968L, 0x4e734a41L, + 0xb3472dcaL, 0x7b14a94aL, 0x1b510052L, 0x9a532915L, + 0xd60f573fL, 0xbc9bc6e4L, 0x2b60a476L, 0x81e67400L, + 0x08ba6fb5L, 0x571be91fL, 0xf296ec6bL, 0x2a0dd915L, + 0xb6636521L, 0xe7b9f9b6L, 0xff34052eL, 0xc5855664L, + 0x53b02d5dL, 0xa99f8fa1L, 0x08ba4799L, 0x6e85076aL, + 0x4b7a70e9L, 0xb5b32944L, 0xdb75092eL, 0xc4192623L, + 0xad6ea6b0L, 0x49a7df7dL, 0x9cee60b8L, 0x8fedb266L, + 0xecaa8c71L, 0x699a17ffL, 0x5664526cL, 0xc2b19ee1L, + 0x193602a5L, 0x75094c29L, 0xa0591340L, 0xe4183a3eL, + 0x3f54989aL, 0x5b429d65L, 0x6b8fe4d6L, 0x99f73fd6L, + 0xa1d29c07L, 0xefe830f5L, 0x4d2d38e6L, 0xf0255dc1L, + 0x4cdd2086L, 0x8470eb26L, 0x6382e9c6L, 0x021ecc5eL, + 0x09686b3fL, 0x3ebaefc9L, 0x3c971814L, 0x6b6a70a1L, + 0x687f3584L, 0x52a0e286L, 0xb79c5305L, 0xaa500737L, + 0x3e07841cL, 0x7fdeae5cL, 0x8e7d44ecL, 0x5716f2b8L, + 0xb03ada37L, 0xf0500c0dL, 0xf01c1f04L, 0x0200b3ffL, + 0xae0cf51aL, 0x3cb574b2L, 0x25837a58L, 0xdc0921bdL, + 0xd19113f9L, 0x7ca92ff6L, 0x94324773L, 0x22f54701L, + 0x3ae5e581L, 0x37c2dadcL, 0xc8b57634L, 0x9af3dda7L, + 0xa9446146L, 0x0fd0030eL, 0xecc8c73eL, 0xa4751e41L, + 0xe238cd99L, 0x3bea0e2fL, 0x3280bba1L, 0x183eb331L, + 0x4e548b38L, 0x4f6db908L, 0x6f420d03L, 0xf60a04bfL, + 0x2cb81290L, 0x24977c79L, 0x5679b072L, 0xbcaf89afL, + 0xde9a771fL, 0xd9930810L, 0xb38bae12L, 0xdccf3f2eL, + 0x5512721fL, 0x2e6b7124L, 0x501adde6L, 0x9f84cd87L, + 0x7a584718L, 0x7408da17L, 0xbc9f9abcL, 0xe94b7d8cL, + 0xec7aec3aL, 0xdb851dfaL, 0x63094366L, 0xc464c3d2L, + 0xef1c1847L, 0x3215d908L, 0xdd433b37L, 0x24c2ba16L, + 0x12a14d43L, 0x2a65c451L, 0x50940002L, 0x133ae4ddL, + 0x71dff89eL, 0x10314e55L, 0x81ac77d6L, 0x5f11199bL, + 0x043556f1L, 0xd7a3c76bL, 0x3c11183bL, 0x5924a509L, + 0xf28fe6edL, 0x97f1fbfaL, 0x9ebabf2cL, 0x1e153c6eL, + 0x86e34570L, 0xeae96fb1L, 0x860e5e0aL, 0x5a3e2ab3L, + 0x771fe71cL, 0x4e3d06faL, 0x2965dcb9L, 0x99e71d0fL, + 0x803e89d6L, 0x5266c825L, 0x2e4cc978L, 0x9c10b36aL, + 0xc6150ebaL, 0x94e2ea78L, 0xa5fc3c53L, 0x1e0a2df4L, + 0xf2f74ea7L, 0x361d2b3dL, 0x1939260fL, 0x19c27960L, + 0x5223a708L, 0xf71312b6L, 0xebadfe6eL, 0xeac31f66L, + 0xe3bc4595L, 0xa67bc883L, 0xb17f37d1L, 0x018cff28L, + 0xc332ddefL, 0xbe6c5aa5L, 0x65582185L, 0x68ab9802L, + 0xeecea50fL, 0xdb2f953bL, 0x2aef7dadL, 0x5b6e2f84L, + 0x1521b628L, 0x29076170L, 0xecdd4775L, 0x619f1510L, + 0x13cca830L, 0xeb61bd96L, 0x0334fe1eL, 0xaa0363cfL, + 0xb5735c90L, 0x4c70a239L, 0xd59e9e0bL, 0xcbaade14L, + 0xeecc86bcL, 0x60622ca7L, 0x9cab5cabL, 0xb2f3846eL, + 0x648b1eafL, 0x19bdf0caL, 0xa02369b9L, 0x655abb50L, + 0x40685a32L, 0x3c2ab4b3L, 0x319ee9d5L, 0xc021b8f7L, + 0x9b540b19L, 0x875fa099L, 0x95f7997eL, 0x623d7da8L, + 0xf837889aL, 0x97e32d77L, 0x11ed935fL, 0x16681281L, + 0x0e358829L, 0xc7e61fd6L, 0x96dedfa1L, 0x7858ba99L, + 0x57f584a5L, 0x1b227263L, 0x9b83c3ffL, 0x1ac24696L, + 0xcdb30aebL, 0x532e3054L, 0x8fd948e4L, 0x6dbc3128L, + 0x58ebf2efL, 0x34c6ffeaL, 0xfe28ed61L, 0xee7c3c73L, + 0x5d4a14d9L, 0xe864b7e3L, 0x42105d14L, 0x203e13e0L, + 0x45eee2b6L, 0xa3aaabeaL, 0xdb6c4f15L, 0xfacb4fd0L, + 0xc742f442L, 0xef6abbb5L, 0x654f3b1dL, 0x41cd2105L, + 0xd81e799eL, 0x86854dc7L, 0xe44b476aL, 0x3d816250L, + 0xcf62a1f2L, 0x5b8d2646L, 0xfc8883a0L, 0xc1c7b6a3L, + 0x7f1524c3L, 0x69cb7492L, 0x47848a0bL, 0x5692b285L, + 0x095bbf00L, 0xad19489dL, 0x1462b174L, 0x23820e00L, + 0x58428d2aL, 0x0c55f5eaL, 0x1dadf43eL, 0x233f7061L, + 0x3372f092L, 0x8d937e41L, 0xd65fecf1L, 0x6c223bdbL, + 0x7cde3759L, 0xcbee7460L, 0x4085f2a7L, 0xce77326eL, + 0xa6078084L, 0x19f8509eL, 0xe8efd855L, 0x61d99735L, + 0xa969a7aaL, 0xc50c06c2L, 0x5a04abfcL, 0x800bcadcL, + 0x9e447a2eL, 0xc3453484L, 0xfdd56705L, 0x0e1e9ec9L, + 0xdb73dbd3L, 0x105588cdL, 0x675fda79L, 0xe3674340L, + 0xc5c43465L, 0x713e38d8L, 0x3d28f89eL, 0xf16dff20L, + 0x153e21e7L, 0x8fb03d4aL, 0xe6e39f2bL, 0xdb83adf7L, + 0xe93d5a68L, 0x948140f7L, 0xf64c261cL, 0x94692934L, + 0x411520f7L, 0x7602d4f7L, 0xbcf46b2eL, 0xd4a20068L, + 0xd4082471L, 0x3320f46aL, 0x43b7d4b7L, 0x500061afL, + 0x1e39f62eL, 0x97244546L, 0x14214f74L, 0xbf8b8840L, + 0x4d95fc1dL, 0x96b591afL, 0x70f4ddd3L, 0x66a02f45L, + 0xbfbc09ecL, 0x03bd9785L, 0x7fac6dd0L, 0x31cb8504L, + 0x96eb27b3L, 0x55fd3941L, 0xda2547e6L, 0xabca0a9aL, + 0x28507825L, 0x530429f4L, 0x0a2c86daL, 0xe9b66dfbL, + 0x68dc1462L, 0xd7486900L, 0x680ec0a4L, 0x27a18deeL, + 0x4f3ffea2L, 0xe887ad8cL, 0xb58ce006L, 0x7af4d6b6L, + 0xaace1e7cL, 0xd3375fecL, 0xce78a399L, 0x406b2a42L, + 0x20fe9e35L, 0xd9f385b9L, 0xee39d7abL, 0x3b124e8bL, + 0x1dc9faf7L, 0x4b6d1856L, 0x26a36631L, 0xeae397b2L, + 0x3a6efa74L, 0xdd5b4332L, 0x6841e7f7L, 0xca7820fbL, + 0xfb0af54eL, 0xd8feb397L, 0x454056acL, 0xba489527L, + 0x55533a3aL, 0x20838d87L, 0xfe6ba9b7L, 0xd096954bL, + 0x55a867bcL, 0xa1159a58L, 0xcca92963L, 0x99e1db33L, + 0xa62a4a56L, 0x3f3125f9L, 0x5ef47e1cL, 0x9029317cL, + 0xfdf8e802L, 0x04272f70L, 0x80bb155cL, 0x05282ce3L, + 0x95c11548L, 0xe4c66d22L, 0x48c1133fL, 0xc70f86dcL, + 0x07f9c9eeL, 0x41041f0fL, 0x404779a4L, 0x5d886e17L, + 0x325f51ebL, 0xd59bc0d1L, 0xf2bcc18fL, 0x41113564L, + 0x257b7834L, 0x602a9c60L, 0xdff8e8a3L, 0x1f636c1bL, + 0x0e12b4c2L, 0x02e1329eL, 0xaf664fd1L, 0xcad18115L, + 0x6b2395e0L, 0x333e92e1L, 0x3b240b62L, 0xeebeb922L, + 0x85b2a20eL, 0xe6ba0d99L, 0xde720c8cL, 0x2da2f728L, + 0xd0127845L, 0x95b794fdL, 0x647d0862L, 0xe7ccf5f0L, + 0x5449a36fL, 0x877d48faL, 0xc39dfd27L, 0xf33e8d1eL, + 0x0a476341L, 0x992eff74L, 0x3a6f6eabL, 0xf4f8fd37L, + 0xa812dc60L, 0xa1ebddf8L, 0x991be14cL, 0xdb6e6b0dL, + 0xc67b5510L, 0x6d672c37L, 0x2765d43bL, 0xdcd0e804L, + 0xf1290dc7L, 0xcc00ffa3L, 0xb5390f92L, 0x690fed0bL, + 0x667b9ffbL, 0xcedb7d9cL, 0xa091cf0bL, 0xd9155ea3L, + 0xbb132f88L, 0x515bad24L, 0x7b9479bfL, 0x763bd6ebL, + 0x37392eb3L, 0xcc115979L, 0x8026e297L, 0xf42e312dL, + 0x6842ada7L, 0xc66a2b3bL, 0x12754cccL, 0x782ef11cL, + 0x6a124237L, 0xb79251e7L, 0x06a1bbe6L, 0x4bfb6350L, + 0x1a6b1018L, 0x11caedfaL, 0x3d25bdd8L, 0xe2e1c3c9L, + 0x44421659L, 0x0a121386L, 0xd90cec6eL, 0xd5abea2aL, + 0x64af674eL, 0xda86a85fL, 0xbebfe988L, 0x64e4c3feL, + 0x9dbc8057L, 0xf0f7c086L, 0x60787bf8L, 0x6003604dL, + 0xd1fd8346L, 0xf6381fb0L, 0x7745ae04L, 0xd736fcccL, + 0x83426b33L, 0xf01eab71L, 0xb0804187L, 0x3c005e5fL, + 0x77a057beL, 0xbde8ae24L, 0x55464299L, 0xbf582e61L, + 0x4e58f48fL, 0xf2ddfda2L, 0xf474ef38L, 0x8789bdc2L, + 0x5366f9c3L, 0xc8b38e74L, 0xb475f255L, 0x46fcd9b9L, + 0x7aeb2661L, 0x8b1ddf84L, 0x846a0e79L, 0x915f95e2L, + 0x466e598eL, 0x20b45770L, 0x8cd55591L, 0xc902de4cL, + 0xb90bace1L, 0xbb8205d0L, 0x11a86248L, 0x7574a99eL, + 0xb77f19b6L, 0xe0a9dc09L, 0x662d09a1L, 0xc4324633L, + 0xe85a1f02L, 0x09f0be8cL, 0x4a99a025L, 0x1d6efe10L, + 0x1ab93d1dL, 0x0ba5a4dfL, 0xa186f20fL, 0x2868f169L, + 0xdcb7da83L, 0x573906feL, 0xa1e2ce9bL, 0x4fcd7f52L, + 0x50115e01L, 0xa70683faL, 0xa002b5c4L, 0x0de6d027L, + 0x9af88c27L, 0x773f8641L, 0xc3604c06L, 0x61a806b5L, + 0xf0177a28L, 0xc0f586e0L, 0x006058aaL, 0x30dc7d62L, + 0x11e69ed7L, 0x2338ea63L, 0x53c2dd94L, 0xc2c21634L, + 0xbbcbee56L, 0x90bcb6deL, 0xebfc7da1L, 0xce591d76L, + 0x6f05e409L, 0x4b7c0188L, 0x39720a3dL, 0x7c927c24L, + 0x86e3725fL, 0x724d9db9L, 0x1ac15bb4L, 0xd39eb8fcL, + 0xed545578L, 0x08fca5b5L, 0xd83d7cd3L, 0x4dad0fc4L, + 0x1e50ef5eL, 0xb161e6f8L, 0xa28514d9L, 0x6c51133cL, + 0x6fd5c7e7L, 0x56e14ec4L, 0x362abfceL, 0xddc6c837L, + 0xd79a3234L, 0x92638212L, 0x670efa8eL, 0x406000e0L, + 0x3a39ce37L, 0xd3faf5cfL, 0xabc27737L, 0x5ac52d1bL, + 0x5cb0679eL, 0x4fa33742L, 0xd3822740L, 0x99bc9bbeL, + 0xd5118e9dL, 0xbf0f7315L, 0xd62d1c7eL, 0xc700c47bL, + 0xb78c1b6bL, 0x21a19045L, 0xb26eb1beL, 0x6a366eb4L, + 0x5748ab2fL, 0xbc946e79L, 0xc6a376d2L, 0x6549c2c8L, + 0x530ff8eeL, 0x468dde7dL, 0xd5730a1dL, 0x4cd04dc6L, + 0x2939bbdbL, 0xa9ba4650L, 0xac9526e8L, 0xbe5ee304L, + 0xa1fad5f0L, 0x6a2d519aL, 0x63ef8ce2L, 0x9a86ee22L, + 0xc089c2b8L, 0x43242ef6L, 0xa51e03aaL, 0x9cf2d0a4L, + 0x83c061baL, 0x9be96a4dL, 0x8fe51550L, 0xba645bd6L, + 0x2826a2f9L, 0xa73a3ae1L, 0x4ba99586L, 0xef5562e9L, + 0xc72fefd3L, 0xf752f7daL, 0x3f046f69L, 0x77fa0a59L, + 0x80e4a915L, 0x87b08601L, 0x9b09e6adL, 0x3b3ee593L, + 0xe990fd5aL, 0x9e34d797L, 0x2cf0b7d9L, 0x022b8b51L, + 0x96d5ac3aL, 0x017da67dL, 0xd1cf3ed6L, 0x7c7d2d28L, + 0x1f9f25cfL, 0xadf2b89bL, 0x5ad6b472L, 0x5a88f54cL, + 0xe029ac71L, 0xe019a5e6L, 0x47b0acfdL, 0xed93fa9bL, + 0xe8d3c48dL, 0x283b57ccL, 0xf8d56629L, 0x79132e28L, + 0x785f0191L, 0xed756055L, 0xf7960e44L, 0xe3d35e8cL, + 0x15056dd4L, 0x88f46dbaL, 0x03a16125L, 0x0564f0bdL, + 0xc3eb9e15L, 0x3c9057a2L, 0x97271aecL, 0xa93a072aL, + 0x1b3f6d9bL, 0x1e6321f5L, 0xf59c66fbL, 0x26dcf319L, + 0x7533d928L, 0xb155fdf5L, 0x03563482L, 0x8aba3cbbL, + 0x28517711L, 0xc20ad9f8L, 0xabcc5167L, 0xccad925fL, + 0x4de81751L, 0x3830dc8eL, 0x379d5862L, 0x9320f991L, + 0xea7a90c2L, 0xfb3e7bceL, 0x5121ce64L, 0x774fbe32L, + 0xa8b6e37eL, 0xc3293d46L, 0x48de5369L, 0x6413e680L, + 0xa2ae0810L, 0xdd6db224L, 0x69852dfdL, 0x09072166L, + 0xb39a460aL, 0x6445c0ddL, 0x586cdecfL, 0x1c20c8aeL, + 0x5bbef7ddL, 0x1b588d40L, 0xccd2017fL, 0x6bb4e3bbL, + 0xdda26a7eL, 0x3a59ff45L, 0x3e350a44L, 0xbcb4cdd5L, + 0x72eacea8L, 0xfa6484bbL, 0x8d6612aeL, 0xbf3c6f47L, + 0xd29be463L, 0x542f5d9eL, 0xaec2771bL, 0xf64e6370L, + 0x740e0d8dL, 0xe75b1357L, 0xf8721671L, 0xaf537d5dL, + 0x4040cb08L, 0x4eb4e2ccL, 0x34d2466aL, 0x0115af84L, + 0xe1b00428L, 0x95983a1dL, 0x06b89fb4L, 0xce6ea048L, + 0x6f3f3b82L, 0x3520ab82L, 0x011a1d4bL, 0x277227f8L, + 0x611560b1L, 0xe7933fdcL, 0xbb3a792bL, 0x344525bdL, + 0xa08839e1L, 0x51ce794bL, 0x2f32c9b7L, 0xa01fbac9L, + 0xe01cc87eL, 0xbcc7d1f6L, 0xcf0111c3L, 0xa1e8aac7L, + 0x1a908749L, 0xd44fbd9aL, 0xd0dadecbL, 0xd50ada38L, + 0x0339c32aL, 0xc6913667L, 0x8df9317cL, 0xe0b12b4fL, + 0xf79e59b7L, 0x43f5bb3aL, 0xf2d519ffL, 0x27d9459cL, + 0xbf97222cL, 0x15e6fc2aL, 0x0f91fc71L, 0x9b941525L, + 0xfae59361L, 0xceb69cebL, 0xc2a86459L, 0x12baa8d1L, + 0xb6c1075eL, 0xe3056a0cL, 0x10d25065L, 0xcb03a442L, + 0xe0ec6e0eL, 0x1698db3bL, 0x4c98a0beL, 0x3278e964L, + 0x9f1f9532L, 0xe0d392dfL, 0xd3a0342bL, 0x8971f21eL, + 0x1b0a7441L, 0x4ba3348cL, 0xc5be7120L, 0xc37632d8L, + 0xdf359f8dL, 0x9b992f2eL, 0xe60b6f47L, 0x0fe3f11dL, + 0xe54cda54L, 0x1edad891L, 0xce6279cfL, 0xcd3e7e6fL, + 0x1618b166L, 0xfd2c1d05L, 0x848fd2c5L, 0xf6fb2299L, + 0xf523f357L, 0xa6327623L, 0x93a83531L, 0x56cccd02L, + 0xacf08162L, 0x5a75ebb5L, 0x6e163697L, 0x88d273ccL, + 0xde966292L, 0x81b949d0L, 0x4c50901bL, 0x71c65614L, + 0xe6c6c7bdL, 0x327a140aL, 0x45e1d006L, 0xc3f27b9aL, + 0xc9aa53fdL, 0x62a80f00L, 0xbb25bfe2L, 0x35bdd2f6L, + 0x71126905L, 0xb2040222L, 0xb6cbcf7cL, 0xcd769c2bL, + 0x53113ec0L, 0x1640e3d3L, 0x38abbd60L, 0x2547adf0L, + 0xba38209cL, 0xf746ce76L, 0x77afa1c5L, 0x20756060L, + 0x85cbfe4eL, 0x8ae88dd8L, 0x7aaaf9b0L, 0x4cf9aa7eL, + 0x1948c25cL, 0x02fb8a8cL, 0x01c36ae4L, 0xd6ebe1f9L, + 0x90d4f869L, 0xa65cdea0L, 0x3f09252dL, 0xc208e69fL, + 0xb74e6132L, 0xce77e25bL, 0x578fdfe3L, 0x3ac372e6L, } }; diff --git a/src/os_crypto/blowfish/bf_skey.c b/src/os_crypto/blowfish/bf_skey.c index d3cba58..f38a4ce 100755 --- a/src/os_crypto/blowfish/bf_skey.c +++ b/src/os_crypto/blowfish/bf_skey.c @@ -5,21 +5,21 @@ * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. - * + * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * + * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: @@ -34,10 +34,10 @@ * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from + * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * + * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -49,7 +49,7 @@ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. - * + * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence diff --git a/src/os_crypto/blowfish/blowfish.h b/src/os_crypto/blowfish/blowfish.h index ad6ce95..180442a 100755 --- a/src/os_crypto/blowfish/blowfish.h +++ b/src/os_crypto/blowfish/blowfish.h @@ -5,21 +5,21 @@ * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. - * + * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * + * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: @@ -34,10 +34,10 @@ * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from + * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * + * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -49,7 +49,7 @@ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. - * + * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence @@ -104,7 +104,7 @@ typedef struct bf_key_st BF_LONG S[4*256]; } BF_KEY; - + void BF_set_key(BF_KEY *key, int len, const unsigned char *data); void BF_encrypt(BF_LONG *data,const BF_KEY *key); diff --git a/src/os_crypto/blowfish/main.c b/src/os_crypto/blowfish/main.c index 0b34a02..6a3277c 100755 --- a/src/os_crypto/blowfish/main.c +++ b/src/os_crypto/blowfish/main.c @@ -19,13 +19,13 @@ int main(int argc, char ** argv) printf("%s: string key\n", argv[0]); exit(1); } - + if((strlen(argv[1]) > 1020) || (strlen(argv[2]) > 512)) { printf("%s: size err\n", argv[0]); exit(1); } - + /* Encrypt */ OS_BF_Str(argv[1], output, argv[2], strlen(argv[1]), OS_ENCRYPT); diff --git a/src/os_crypto/md5/main.c b/src/os_crypto/md5/main.c index 8265fa6..5eab951 100755 --- a/src/os_crypto/md5/main.c +++ b/src/os_crypto/md5/main.c @@ -20,21 +20,21 @@ int main(int argc, char ** argv) if(argc < 3) usage(argv); - - + + if(strcmp(argv[1],"file") == 0) { OS_MD5_File(argv[2], filesum); } - + else if(strcmp(argv[1],"str") == 0) { OS_MD5_Str(argv[2], filesum); } - + else usage(argv); - + printf("MD5Sum for \"%s\" is: %s\n",argv[2],filesum); return(0); } diff --git a/src/os_crypto/md5/md5.c b/src/os_crypto/md5/md5.c index f2eb619..769e1fb 100755 --- a/src/os_crypto/md5/md5.c +++ b/src/os_crypto/md5/md5.c @@ -24,7 +24,7 @@ #ifdef __BYTE_ORDER #if __BYTE_ORDER == __BIG_ENDIAN #define HIGHFIRST -#endif /* BIG ENDIAN */ +#endif /* BIG ENDIAN */ #endif /* byte order */ @@ -114,7 +114,7 @@ void MD5Update(struct MD5Context *ctx, unsigned char const *buf, unsigned len) } /* - * Final wrapup - pad to 64-byte boundary with the bit pattern + * Final wrapup - pad to 64-byte boundary with the bit pattern * 1 0* (64-bit count of bits processed, MSB-first) */ void MD5Final(unsigned char digest[16], struct MD5Context *ctx) diff --git a/src/os_crypto/md5/md5_op.c b/src/os_crypto/md5/md5_op.c index 9e3dc5d..6785697 100755 --- a/src/os_crypto/md5/md5_op.c +++ b/src/os_crypto/md5/md5_op.c @@ -29,25 +29,25 @@ int OS_MD5_File(char * fname, char * output) unsigned char buf[1024 +1]; unsigned char digest[16]; int n; - + memset(output,0, 33); buf[1024] = '\0'; - + fp = fopen(fname,"r"); if(!fp) { return(-1); } - + MD5Init(&ctx); while((n = fread(buf, 1, sizeof(buf) -1, fp)) > 0) { buf[n] = '\0'; MD5Update(&ctx,buf,n); } - + MD5Final(digest, &ctx); - + for(n = 0;n < 16; n++) { snprintf(output, 3, "%02x", digest[n]); @@ -56,7 +56,7 @@ int OS_MD5_File(char * fname, char * output) /* Closing it */ fclose(fp); - + return(0); } @@ -64,17 +64,17 @@ int OS_MD5_File(char * fname, char * output) int OS_MD5_Str(char * str, char * output) { unsigned char digest[16]; - + int n; - + MD5_CTX ctx; MD5Init(&ctx); - + MD5Update(&ctx,(unsigned char *)str,strlen(str)); - + MD5Final(digest, &ctx); - + output[32] = '\0'; for(n = 0;n < 16;n++) { diff --git a/src/os_crypto/md5_sha1/main.c b/src/os_crypto/md5_sha1/main.c index 71e3965..12723dc 100755 --- a/src/os_crypto/md5_sha1/main.c +++ b/src/os_crypto/md5_sha1/main.c @@ -8,7 +8,7 @@ void usage(char **argv) { - printf("%s file str\n%s str string\n",argv[0],argv[0]); + printf("%s prefilter_cmd file str\n%s str string\n",argv[0],argv[0]); exit(1); } @@ -21,18 +21,18 @@ int main(int argc, char ** argv) os_md5 filesum1; os_sha1 filesum2; - if(argc < 3) + if(argc < 4) usage(argv); - - - if(strcmp(argv[1],"file") == 0) + + + if(strcmp(argv[2],"file") == 0) { - OS_MD5_SHA1_File(argv[2], filesum1, filesum2); + OS_MD5_SHA1_File(argv[3], argv[1], filesum1, filesum2); } - + else usage(argv); - + printf("MD5Sha1Sum for \"%s\" is: %s - %s\n",argv[2], filesum1, filesum2); return(0); } diff --git a/src/os_crypto/md5_sha1/md5_sha1_op.c b/src/os_crypto/md5_sha1/md5_sha1_op.c index c2a168a..b3471f4 100755 --- a/src/os_crypto/md5_sha1/md5_sha1_op.c +++ b/src/os_crypto/md5_sha1/md5_sha1_op.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_crypto/md5_sha1/md5_sha1_op.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -16,10 +17,11 @@ #include "../md5/md5.h" #include "../sha1/sha.h" +#include "headers/defs.h" + - -int OS_MD5_SHA1_File(char * fname, char *md5output, char *sha1output) +int OS_MD5_SHA1_File(char *fname, char *prefilter_cmd, char *md5output, char *sha1output) { int n; FILE *fp; @@ -27,19 +29,30 @@ int OS_MD5_SHA1_File(char * fname, char *md5output, char *sha1output) unsigned char sha1_digest[SHA_DIGEST_LENGTH]; unsigned char md5_digest[16]; + char cmd[OS_MAXSTR]; + SHA_CTX sha1_ctx; MD5_CTX md5_ctx; - + /* Clearing the memory. */ md5output[0] = '\0'; sha1output[0] = '\0'; buf[2048 +1] = '\0'; - fp = fopen(fname,"r"); - if(!fp) - return(-1); - + /* Use prefilter_cmd if set */ + if (prefilter_cmd == NULL) { + fp = fopen(fname,"r"); + if(!fp) + return(-1); + } else { + strncpy(cmd, prefilter_cmd, sizeof(cmd) - 1); + strcat(cmd, " "); + strncat(cmd, fname, sizeof(cmd) - strlen(cmd) - 1); + fp = popen(cmd, "r"); + if(!fp) + return(-1); + } /* Initializing both hashes */ MD5Init(&md5_ctx); @@ -74,7 +87,11 @@ int OS_MD5_SHA1_File(char * fname, char *md5output, char *sha1output) /* Closing it */ - fclose(fp); + if (prefilter_cmd == NULL) { + fclose(fp); + } else { + pclose(fp); + } return(0); } diff --git a/src/os_crypto/md5_sha1/md5_sha1_op.h b/src/os_crypto/md5_sha1/md5_sha1_op.h index 1e2b725..c29a90a 100755 --- a/src/os_crypto/md5_sha1/md5_sha1_op.h +++ b/src/os_crypto/md5_sha1/md5_sha1_op.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_crypto/md5_sha1/md5_sha1_op.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -17,7 +18,7 @@ #define __MD5SHA1_OP_H -int OS_MD5_SHA1_File(char *fname, char *md5output, char *sha1output); +int OS_MD5_SHA1_File(char *fname, char *prefilter_cmd, char *md5output, char *sha1output); #endif diff --git a/src/os_crypto/sha1/main.c b/src/os_crypto/sha1/main.c index 4373f47..e6dda51 100755 --- a/src/os_crypto/sha1/main.c +++ b/src/os_crypto/sha1/main.c @@ -20,8 +20,8 @@ int main(int argc, char ** argv) if(argc < 2) usage(argv); - - + + if(OS_SHA1_File(argv[1], filesum) == 0) { printf("SHA1Sum for \"%s\" is: %s\n",argv[1],filesum); diff --git a/src/os_crypto/sha1/md32_common.h b/src/os_crypto/sha1/md32_common.h index abb9c78..1f9b1ab 100755 --- a/src/os_crypto/sha1/md32_common.h +++ b/src/os_crypto/sha1/md32_common.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_crypto/sha1/md32_common.h, 2011/09/08 dcid Exp $ + */ /* Included on ossec */ /* crypto/md32_common.h */ @@ -10,7 +11,7 @@ * are met: * * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. + * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in @@ -620,7 +621,7 @@ int HASH_FINAL (unsigned char *md, HASH_CTX *c) * *either* case. Now declaring 'em long excuses the compiler * from keeping 32 MSBs zeroed resulting in 13% performance * improvement under SPARC Solaris7/64 and 5% under AlphaLinux. - * Well, to be honest it should say that this *prevents* + * Well, to be honest it should say that this *prevents* * performance degradation. * * Apparently there're LP64 compilers that generate better @@ -631,4 +632,4 @@ int HASH_FINAL (unsigned char *md, HASH_CTX *c) #endif -#endif /* _MD32_COMMON__H */ +#endif /* _MD32_COMMON__H */ diff --git a/src/os_crypto/sha1/sha.h b/src/os_crypto/sha1/sha.h index 86f4162..be021fa 100755 --- a/src/os_crypto/sha1/sha.h +++ b/src/os_crypto/sha1/sha.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_crypto/sha1/sha.h, 2011/09/08 dcid Exp $ + */ /* Included on ossec */ @@ -9,21 +10,21 @@ * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. - * + * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). - * + * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: @@ -38,10 +39,10 @@ * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). - * 4. If you include any Windows specific code (or a derivative thereof) from + * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" - * + * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -53,7 +54,7 @@ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. - * + * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence diff --git a/src/os_crypto/sha1/sha1_op.c b/src/os_crypto/sha1/sha1_op.c index 159c3cf..99d74ec 100755 --- a/src/os_crypto/sha1/sha1_op.c +++ b/src/os_crypto/sha1/sha1_op.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_crypto/sha1/sha1_op.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -14,20 +15,20 @@ #include #include "sha1_op.h" -/* Openssl sha1 +/* Openssl sha1 * Only use if open ssl is not available. #ifndef USE_OPENSSL #include "sha.h" #include "sha_locl.h" #else -#include +#include #endif */ #include "sha_locl.h" - + int OS_SHA1_File(char * fname, char * output) { SHA_CTX c; @@ -35,32 +36,32 @@ int OS_SHA1_File(char * fname, char * output) unsigned char buf[2048 +2]; unsigned char md[SHA_DIGEST_LENGTH]; int n; - + memset(output,0, 65); buf[2049] = '\0'; - + fp = fopen(fname,"r"); if(!fp) return(-1); - + SHA1_Init(&c); while((n = fread(buf, 1, 2048, fp)) > 0) { buf[n] = '\0'; SHA1_Update(&c,buf,(unsigned long)n); } - + SHA1_Final(&(md[0]),&c); - + for (n=0; n (x|y)&a */ -#define F_00_19(b,c,d) ((((c) ^ (d)) & (b)) ^ (d)) +#define F_00_19(b,c,d) ((((c) ^ (d)) & (b)) ^ (d)) #define F_20_39(b,c,d) ((b) ^ (c) ^ (d)) -#define F_40_59(b,c,d) (((b) & (c)) | (((b)|(c)) & (d))) +#define F_40_59(b,c,d) (((b) & (c)) | (((b)|(c)) & (d))) #define F_60_79(b,c,d) F_20_39(b,c,d) #ifndef OPENSSL_SMALL_FOOTPRINT @@ -344,7 +345,7 @@ void HASH_BLOCK_HOST_ORDER (SHA_CTX *c, const void *d, size_t num) BODY_60_79(78,A,B,C,D,E,T,X(14),X( 0),X( 6),X(11)); BODY_60_79(79,T,A,B,C,D,E,X(15),X( 1),X( 7),X(12)); - c->h0=(c->h0+E)&0xffffffffL; + c->h0=(c->h0+E)&0xffffffffL; c->h1=(c->h1+T)&0xffffffffL; c->h2=(c->h2+A)&0xffffffffL; c->h3=(c->h3+B)&0xffffffffL; @@ -471,7 +472,7 @@ void HASH_BLOCK_DATA_ORDER (SHA_CTX *c, const void *p, size_t num) BODY_60_79(78,A,B,C,D,E,T,X(14),X( 0),X( 6),X(11)); BODY_60_79(79,T,A,B,C,D,E,X(15),X( 1),X( 7),X(12)); - c->h0=(c->h0+E)&0xffffffffL; + c->h0=(c->h0+E)&0xffffffffL; c->h1=(c->h1+T)&0xffffffffL; c->h2=(c->h2+A)&0xffffffffL; c->h3=(c->h3+B)&0xffffffffL; @@ -547,7 +548,7 @@ void HASH_BLOCK_HOST_ORDER (SHA_CTX *c, const void *d, size_t num) for (i=4;i<24;i++) { BODY_60_79(X[(i+8)&15],X[(i+10)&15],X[i&15], X[(i+5)&15]); } - c->h0=(c->h0+A)&0xffffffffL; + c->h0=(c->h0+A)&0xffffffffL; c->h1=(c->h1+B)&0xffffffffL; c->h2=(c->h2+C)&0xffffffffL; c->h3=(c->h3+D)&0xffffffffL; @@ -593,7 +594,7 @@ void HASH_BLOCK_DATA_ORDER (SHA_CTX *c, const void *p, size_t num) for (i=4;i<24;i++) { BODY_60_79(X[(i+8)&15],X[(i+10)&15],X[i&15], X[(i+5)&15]); } - c->h0=(c->h0+A)&0xffffffffL; + c->h0=(c->h0+A)&0xffffffffL; c->h1=(c->h1+B)&0xffffffffL; c->h2=(c->h2+C)&0xffffffffL; c->h3=(c->h3+D)&0xffffffffL; diff --git a/src/os_crypto/shared/keys.c b/src/os_crypto/shared/keys.c index d70aab5..587f083 100755 --- a/src/os_crypto/shared/keys.c +++ b/src/os_crypto/shared/keys.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_crypto/shared/keys.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -23,7 +24,7 @@ -/* __memclear: Clears keys entries. +/* __memclear: Clears keys entries. */ void __memclear(char *id, char *name, char *ip, char *key, int size) { @@ -40,10 +41,10 @@ void __chash(keystore *keys, char *id, char *name, char *ip, char *key) { os_md5 filesum1; os_md5 filesum2; - - char *tmp_str; + + char *tmp_str; char _finalstr[KEYSIZE]; - + /* Allocating for the whole structure */ keys->keyentries =(keyentry **)realloc(keys->keyentries, @@ -53,32 +54,32 @@ void __chash(keystore *keys, char *id, char *name, char *ip, char *key) ErrorExit(MEM_ERROR, __local_name); } os_calloc(1, sizeof(keyentry), keys->keyentries[keys->keysize]); - - + + /* Setting configured values for id */ os_strdup(id, keys->keyentries[keys->keysize]->id); - OSHash_Add(keys->keyhash_id, - keys->keyentries[keys->keysize]->id, + OSHash_Add(keys->keyhash_id, + keys->keyentries[keys->keysize]->id, keys->keyentries[keys->keysize]); - - + + /* agent ip */ os_calloc(1, sizeof(os_ip), keys->keyentries[keys->keysize]->ip); if(OS_IsValidIP(ip, keys->keyentries[keys->keysize]->ip) == 0) { ErrorExit(INVALID_IP, __local_name, ip); } - + /* We need to remove the "/" from the cidr */ if((tmp_str = strchr(keys->keyentries[keys->keysize]->ip->ip, '/')) != NULL) { *tmp_str = '\0'; } - OSHash_Add(keys->keyhash_ip, - keys->keyentries[keys->keysize]->ip->ip, + OSHash_Add(keys->keyhash_ip, + keys->keyentries[keys->keysize]->ip->ip, keys->keyentries[keys->keysize]); - + /* agent name */ os_strdup(name, keys->keyentries[keys->keysize]->name); @@ -90,15 +91,15 @@ void __chash(keystore *keys, char *id, char *name, char *ip, char *key) keys->keyentries[keys->keysize]->fp = NULL; - + /** Generating final symmetric key **/ - + /* MD5 from name, id and key */ OS_MD5_Str(name, filesum1); OS_MD5_Str(id, filesum2); - /* Generating new filesum1 */ + /* Generating new filesum1 */ snprintf(_finalstr, sizeof(_finalstr)-1, "%s%s", filesum1, filesum2); @@ -111,7 +112,7 @@ void __chash(keystore *keys, char *id, char *name, char *ip, char *key) /* Second md is just the key */ OS_MD5_Str(key, filesum2); - + /* Generating final key */ memset(_finalstr,'\0', sizeof(_finalstr)); snprintf(_finalstr, 49, "%s%s", filesum2, filesum1); @@ -127,14 +128,14 @@ void __chash(keystore *keys, char *id, char *name, char *ip, char *key) /* ready for next */ keys->keysize++; - - + + return; } -/* int OS_CheckKeys(): - * Checks if the authentication key file is present +/* int OS_CheckKeys(): + * Checks if the authentication key file is present */ int OS_CheckKeys() { @@ -171,15 +172,15 @@ int OS_CheckKeys() void OS_ReadKeys(keystore *keys) { FILE *fp; - + char buffer[OS_BUFFER_SIZE +1]; - + char name[KEYSIZE +1]; char ip[KEYSIZE +1]; char id[KEYSIZE +1]; char key[KEYSIZE +1]; - - + + /* Checking if the keys file is present and we can read it. */ if((keys->file_change = File_DateofChange(KEYS_FILE)) < 0) { @@ -221,7 +222,7 @@ void OS_ReadKeys(keystore *keys) { char *tmp_str; char *valid_str; - + if((buffer[0] == '#') || (buffer[0] == ' ')) continue; @@ -244,7 +245,7 @@ void OS_ReadKeys(keystore *keys) { continue; } - + /* Getting name */ valid_str = tmp_str; tmp_str = strchr(tmp_str, ' '); @@ -257,7 +258,7 @@ void OS_ReadKeys(keystore *keys) tmp_str++; strncpy(name, valid_str, KEYSIZE -1); - + /* Getting ip address */ valid_str = tmp_str; tmp_str = strchr(tmp_str, ' '); @@ -270,7 +271,7 @@ void OS_ReadKeys(keystore *keys) tmp_str++; strncpy(ip, valid_str, KEYSIZE -1); - + /* Getting key */ valid_str = tmp_str; tmp_str = strchr(tmp_str, '\n'); @@ -287,8 +288,8 @@ void OS_ReadKeys(keystore *keys) /* Clearing the memory */ - __memclear(id, name, ip, key, KEYSIZE +1); - + __memclear(id, name, ip, key, KEYSIZE +1); + /* Checking for maximum agent size */ if(keys->keysize >= (MAX_AGENTS -2)) @@ -296,11 +297,11 @@ void OS_ReadKeys(keystore *keys) merror(AG_MAX_ERROR, __local_name, MAX_AGENTS -2); ErrorExit(CONFIG_ERROR, __local_name, KEYS_FILE); } - + continue; } - - + + /* Closing key file. */ fclose(fp); @@ -343,12 +344,12 @@ void OS_FreeKeys(keystore *keys) keys->keysize = 0; keys->keyhash_id =NULL; keys->keyhash_ip = NULL; - - + + /* Sleeping to give time to other threads to stop using them. */ sleep(1); - - + + /* Freeing the hashes */ OSHash_Free(hashid); OSHash_Free(haship); @@ -363,16 +364,16 @@ void OS_FreeKeys(keystore *keys) free(keys->keyentries[i]->ip->ip); free(keys->keyentries[i]->ip); } - - if(keys->keyentries[i]->id) + + if(keys->keyentries[i]->id) free(keys->keyentries[i]->id); - + if(keys->keyentries[i]->key) free(keys->keyentries[i]->key); if(keys->keyentries[i]->name) free(keys->keyentries[i]->name); - + /* Closing counter */ if(keys->keyentries[i]->fp) fclose(keys->keyentries[i]->fp); @@ -381,7 +382,7 @@ void OS_FreeKeys(keystore *keys) keys->keyentries[i] = NULL; } } - + /* Freeing structure */ free(keys->keyentries); keys->keyentries = NULL; @@ -411,20 +412,20 @@ int OS_UpdateKeys(keystore *keys) { merror(ENCFILE_CHANGED, __local_name); debug1("%s: DEBUG: Freekeys", __local_name); - + OS_FreeKeys(keys); debug1("%s: DEBUG: OS_ReadKeys", __local_name); - + /* Reading keys */ verbose(ENC_READ, __local_name); - + OS_ReadKeys(keys); debug1("%s: DEBUG: OS_StartCounter", __local_name); - + OS_StartCounter(keys); debug1("%s: DEBUG: OS_UpdateKeys completed", __local_name); - + return(1); } return(0); @@ -432,7 +433,7 @@ int OS_UpdateKeys(keystore *keys) /* OS_IsAllowedIP() - * Checks if an IP address is allowed to connect. + * Checks if an IP address is allowed to connect. */ int OS_IsAllowedIP(keystore *keys, char *srcip) { @@ -440,7 +441,7 @@ int OS_IsAllowedIP(keystore *keys, char *srcip) if(srcip == NULL) return(-1); - + entry = OSHash_Get(keys->keyhash_ip, srcip); if(entry) { @@ -476,7 +477,7 @@ int OS_IsAllowedID(keystore *keys, char *id) if(id == NULL) return(-1); - + entry = OSHash_Get(keys->keyhash_id, id); if(entry) { @@ -491,10 +492,10 @@ int OS_IsAllowedID(keystore *keys, char *id) int OS_IsAllowedDynamicID(keystore *keys, char *id, char *srcip) { keyentry *entry; - + if(id == NULL) return(-1); - + entry = OSHash_Get(keys->keyhash_id, id); if(entry) { diff --git a/src/os_crypto/shared/msgs.c b/src/os_crypto/shared/msgs.c index c15297e..eab2a52 100755 --- a/src/os_crypto/shared/msgs.c +++ b/src/os_crypto/shared/msgs.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_crypto/shared/msgs.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -50,11 +51,11 @@ void OS_StartCounter(keystore *keys) char rids_file[OS_FLSIZE +1]; rids_file[OS_FLSIZE] = '\0'; - + debug1("%s: OS_StartCounter: keysize: %d", __local_name, keys->keysize); - - + + /* Starting receiving counter */ for(i = 0; i<=keys->keysize; i++) { @@ -83,7 +84,7 @@ void OS_StartCounter(keystore *keys) if(!keys->keyentries[i]->fp) { int my_error = errno; - + /* Just in case we run out of file descriptiors */ if((keys->keyentries[i -1]->fp) && (i > 10)) { @@ -95,7 +96,7 @@ void OS_StartCounter(keystore *keys) } } - merror("%s: Unable to open agent file. errno: %d", + merror("%s: Unable to open agent file. errno: %d", __local_name, my_error); ErrorExit(FOPEN_ERROR, __local_name, rids_file); } @@ -112,10 +113,10 @@ void OS_StartCounter(keystore *keys) else { verbose("%s: INFO: No previous counter available for '%s'.", - __local_name, + __local_name, keys->keyentries[i]->name); } - + g_c = 0; l_c = 0; } @@ -131,7 +132,7 @@ void OS_StartCounter(keystore *keys) { verbose("%s: INFO: Assigning counter for agent %s: '%d:%d'.", __local_name, keys->keyentries[i]->name, g_c, l_c); - + keys->keyentries[i]->global = g_c; keys->keyentries[i]->local = l_c; } @@ -195,7 +196,7 @@ void StoreCounter(keystore *keys, int id, int global, int local) } -/* CheckSum v0.1: 2005/02/15 +/* CheckSum v0.1: 2005/02/15 * Verify the checksum of the message. * Returns NULL on error or the message on success. */ @@ -216,23 +217,23 @@ char *CheckSum(char *msg) { return(NULL); } - + return(msg); } /* ReadSecMSG v0.2: 2005/02/10 */ -char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, +char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, int id, int buffer_size) { int cmp_size; - unsigned int msg_global; - unsigned int msg_local; + unsigned int msg_global = 0; + unsigned int msg_local = 0; char *f_msg; - - + + if(*buffer == ':') { buffer++; @@ -242,10 +243,10 @@ char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, merror(ENCFORMAT_ERROR, __local_name, keys->keyentries[id]->ip->ip); return(NULL); } - + /* Decrypting message */ - if(!OS_BF_Str(buffer, cleartext, keys->keyentries[id]->key, - buffer_size, OS_DECRYPT)) + if(!OS_BF_Str(buffer, cleartext, keys->keyentries[id]->key, + buffer_size, OS_DECRYPT)) { merror(ENCKEY_ERROR, __local_name, keys->keyentries[id]->ip->ip); return(NULL); @@ -265,7 +266,7 @@ char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, cleartext++; buffer_size--; } - + /* Uncompressing */ cmp_size = os_uncompress(cleartext, buffer, buffer_size, OS_MAXSTR); if(!cmp_size) @@ -301,7 +302,7 @@ char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, msg_local = atoi(f_msg); f_msg+=5; - + /* Returning the message if we don't need to verify the counbter. */ if(!_s_verify_counter) { @@ -311,7 +312,7 @@ char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, if(rcv_count >= _s_recv_flush) { StoreCounter(keys, id, msg_global, msg_local); - rcv_count = 0; + rcv_count = 0; } rcv_count++; return(f_msg); @@ -319,7 +320,7 @@ char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, if((msg_global > keys->keyentries[id]->global)|| - ((msg_global == keys->keyentries[id]->global) && + ((msg_global == keys->keyentries[id]->global) && (msg_local > keys->keyentries[id]->local))) { /* Updating currently counts */ @@ -417,7 +418,7 @@ char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, } /* Checking if it is a duplicated message */ - if((msg_count == keys->keyentries[id]->local) && + if((msg_count == keys->keyentries[id]->local) && (msg_time == keys->keyentries[id]->global)) { return(NULL); @@ -436,7 +437,7 @@ char *ReadSecMSG(keystore *keys, char *buffer, char *cleartext, merror(ENCTIME_ERROR, __local_name, keys->keyentries[id]->name); return(NULL); } - + merror(ENCFORMAT_ERROR, __local_name, keys->keyentries[id]->ip->ip); return(NULL); } @@ -451,24 +452,24 @@ int CreateSecMSG(keystore *keys, char *msg, char *msg_encrypted, int id) int bfsize; int msg_size; int cmp_size; - + u_int16_t rand1; - + char _tmpmsg[OS_MAXSTR + 2]; char _finmsg[OS_MAXSTR + 2]; - + os_md5 md5sum; - + msg_size = strlen(msg); - - + + /* Checking for invalid msg sizes */ if((msg_size > (OS_MAXSTR - OS_HEADER_SIZE))||(msg_size < 1)) { merror(ENCSIZE_ERROR, __local_name, msg); return(0); } - + /* Random number */ rand1 = (u_int16_t)random(); @@ -476,7 +477,7 @@ int CreateSecMSG(keystore *keys, char *msg, char *msg_encrypted, int id) _tmpmsg[OS_MAXSTR +1] = '\0'; _finmsg[OS_MAXSTR +1] = '\0'; msg_encrypted[OS_MAXSTR] = '\0'; - + /* Increasing local and global counters */ if(local_count >= 9997) @@ -485,25 +486,25 @@ int CreateSecMSG(keystore *keys, char *msg, char *msg_encrypted, int id) global_count++; } local_count++; - - + + snprintf(_tmpmsg, OS_MAXSTR,"%05hu%010u:%04hu:%s", rand1, global_count, local_count, msg); - + /* Generating md5sum of the unencrypted string */ OS_MD5_Str(_tmpmsg, md5sum); - + /* Generating final msg to be compressed */ snprintf(_finmsg, OS_MAXSTR,"%s%s",md5sum,_tmpmsg); msg_size = strlen(_finmsg); /* Compressing message. - * We assing the first 8 bytes for padding. + * We assing the first 8 bytes for padding. */ cmp_size = os_compress(_finmsg, _tmpmsg + 8, msg_size, OS_MAXSTR - 12); if(!cmp_size) @@ -512,7 +513,7 @@ int CreateSecMSG(keystore *keys, char *msg, char *msg_encrypted, int id) return(0); } cmp_size++; - + /* Padding the message (needs to be div by 8) */ bfsize = 8 - (cmp_size % 8); if(bfsize == 8) @@ -537,7 +538,7 @@ int CreateSecMSG(keystore *keys, char *msg, char *msg_encrypted, int id) { verbose("%s: INFO: Event count after '%u': %u->%u (%d%%)", __local_name, evt_count, - c_orig_size, + c_orig_size, c_comp_size, (c_comp_size * 100)/c_orig_size); evt_count = 0; @@ -545,10 +546,10 @@ int CreateSecMSG(keystore *keys, char *msg, char *msg_encrypted, int id) c_comp_size = 0; } evt_count++; - + /* If the ip is dynamic (not single host, append agent id * to the message. - */ + */ if(!isSingleHost(keys->keyentries[id]->ip) && isAgent) { snprintf(msg_encrypted, 16, "!%s!:", keys->keyentries[id]->id); @@ -566,13 +567,13 @@ int CreateSecMSG(keystore *keys, char *msg, char *msg_encrypted, int id) * appended to the buffer. On dynamic ips, it will * include the agent id. */ - + /* Encrypting everything */ - OS_BF_Str(_tmpmsg + (7 - bfsize), msg_encrypted + msg_size, - keys->keyentries[id]->key, - cmp_size, + OS_BF_Str(_tmpmsg + (7 - bfsize), msg_encrypted + msg_size, + keys->keyentries[id]->key, + cmp_size, OS_ENCRYPT); - + /* Storing before leaving */ StoreSenderCounter(keys, global_count, local_count); diff --git a/src/os_csyslogd/alert.c b/src/os_csyslogd/alert.c index cef1454..f271cb5 100755 --- a/src/os_csyslogd/alert.c +++ b/src/os_csyslogd/alert.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_csyslogd/alert.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -17,10 +18,6 @@ #include "config/config.h" #include "os_net/os_net.h" - - - - /** int OS_Alert_SendSyslog * Sends an alert via syslog. * Returns 1 on success or 0 on error. @@ -28,21 +25,24 @@ int OS_Alert_SendSyslog(alert_data *al_data, SyslogConfig *syslog_config) { char *tstamp; - char user_msg[256]; - char srcip_msg[256]; - - char syslog_msg[OS_SIZE_2048 +1]; + char syslog_msg[OS_SIZE_2048]; + + /* These will be Malloc'd, so no need to predeclare size, just remember to free! */ + char *json_safe_comment; + char *json_safe_message; + /* padding value */ + int padding = 0; /* Invalid socket. */ if(syslog_config->socket < 0) { return(0); } - + /* Clearing the memory before insert */ - memset(syslog_msg, '\0', OS_SIZE_2048 +1); + memset(syslog_msg, '\0', OS_SIZE_2048); /* Looking if location is set */ @@ -101,7 +101,7 @@ int OS_Alert_SendSyslog(alert_data *al_data, SyslogConfig *syslog_config) } - /* Fixing the timestamp to be syslog compatible. + /* Fixing the timestamp to be syslog compatible. * We have 2008 Jul 10 10:11:23 * Should be: Jul 10 10:11:23 */ @@ -110,60 +110,157 @@ int OS_Alert_SendSyslog(alert_data *al_data, SyslogConfig *syslog_config) { tstamp+=5; - /* Fixing first digit if the day is < 10 */ + /* Fixing first digit if the day is < 10 */ if(tstamp[4] == '0') tstamp[4] = ' '; } - - /* Adding source ip. */ - if(!al_data->srcip || - ((al_data->srcip[0] == '(') && - (al_data->srcip[1] == 'n') && - (al_data->srcip[2] == 'o'))) - { - srcip_msg[0] = '\0'; + + /* Remove the double quotes from "dangerous" fields */ + if( (json_safe_comment = os_strip_char(al_data->comment, '"')) == NULL ) { + return(0); } - else - { - snprintf(srcip_msg, 255, " srcip: %s;", al_data->srcip); + if( (json_safe_message = os_strip_char(al_data->log[0], '"')) == NULL ) { + return(0); } - - /* Adding username. */ - if(!al_data->user || - ((al_data->user[0] == '(') && - (al_data->user[1] == 'n') && - (al_data->user[2] == 'o'))) + /* Inserting data */ + if(syslog_config->format == DEFAULT_CSYSLOG) { - user_msg[0] = '\0'; + /* Building syslog message. */ + snprintf(syslog_msg, OS_SIZE_2048, + "<%d>%s %s ossec: Alert Level: %d; Rule: %d - %s; Location: %s;", + syslog_config->priority, tstamp, __shost, + al_data->level, + al_data->rule, al_data->comment, + al_data->location + ); + field_add_string(syslog_msg, OS_SIZE_2048, " srcip: %s;", al_data->srcip ); +#ifdef GEOIP + field_add_string(syslog_msg, OS_SIZE_2048, " srccity: %s;", al_data->geoipdatasrc ); + field_add_string(syslog_msg, OS_SIZE_2048, " dstcity: %s;", al_data->geoipdatadst ); +#endif + field_add_string(syslog_msg, OS_SIZE_2048, " dstip: %s;", al_data->dstip ); + field_add_string(syslog_msg, OS_SIZE_2048, " user: %s;", al_data->user ); + field_add_string(syslog_msg, OS_SIZE_2048, " Previous MD5: %s;", al_data->old_md5 ); + field_add_string(syslog_msg, OS_SIZE_2048, " Current MD5: %s;", al_data->new_md5 ); + field_add_string(syslog_msg, OS_SIZE_2048, " Previous SHA1: %s;", al_data->old_sha1 ); + field_add_string(syslog_msg, OS_SIZE_2048, " Current SHA1: %s;", al_data->new_sha1 ); + field_add_truncated(syslog_msg, OS_SIZE_2048, " %s", al_data->log[0], 2 ); } - else + else if(syslog_config->format == CEF_CSYSLOG) { - snprintf(user_msg, 255, " user: %s;", al_data->user); + snprintf(syslog_msg, OS_SIZE_2048, + + "<%d>%s CEF:0|%s|%s|%s|%d|%s|%d|dvc=%s cs2=%s cs2Label=Location", + syslog_config->priority, + tstamp, + __author, + __name, + __version, + al_data->rule, + al_data->comment, + (al_data->level > 10) ? 10 : al_data->level, + __shost, al_data->location); + + field_add_string(syslog_msg, OS_SIZE_2048, " src=%s", al_data->srcip ); +#ifdef GEOIP + field_add_string(syslog_msg, OS_SIZE_2048, " cs3Label=SrcCity cs3=%s", al_data->geoipdatasrc ); + field_add_string(syslog_msg, OS_SIZE_2048, " cs4Label=DstCity cs4=%s", al_data->geoipdatadst ); +#endif + field_add_string(syslog_msg, OS_SIZE_2048, " suser=%s", al_data->user ); + field_add_string(syslog_msg, OS_SIZE_2048, " dst=%s", al_data->dstip ); + field_add_truncated(syslog_msg, OS_SIZE_2048, " msg=%s", al_data->log[0], 2 ); + if (al_data->new_md5 && al_data->new_sha1) { + field_add_string(syslog_msg, OS_SIZE_2048, " Previous MD5: %s", al_data->old_md5 ); + field_add_string(syslog_msg, OS_SIZE_2048, " Current MD5: %s", al_data->new_md5 ); + field_add_string(syslog_msg, OS_SIZE_2048, " Previous SHA1: %s", al_data->old_sha1 ); + field_add_string(syslog_msg, OS_SIZE_2048, " Current SHA1: %s", al_data->new_sha1 ); + } } + else if(syslog_config->format == JSON_CSYSLOG) + { + // Padding is two to make sure we can fit closign bracket + padding = 2; + /* Build a JSON Object for logging */ + snprintf(syslog_msg, OS_SIZE_2048 - padding, + "<%d>%s %s ossec: { \"crit\": %d, \"id\": %d, \"description\": \"%s\", \"component\": \"%s\",", + /* syslog header */ + syslog_config->priority, tstamp, __shost, - /* Inserting data */ - if(syslog_config->format == DEFAULT_CSYSLOG) + /* OSSEC metadata */ + al_data->level, al_data->rule, json_safe_comment, + al_data->location + ); + /* Event specifics */ + field_add_string(syslog_msg, OS_SIZE_2048 - padding, " \"classification\": \"%s\",", al_data->group ); + + if( field_add_string(syslog_msg, OS_SIZE_2048 - padding, " \"src_ip\": \"%s\",", al_data->srcip ) > 0 ) + field_add_int(syslog_msg, OS_SIZE_2048 - padding, " \"src_port\": %d,", al_data->srcport ); + +#ifdef GEOIP + field_add_string(syslog_msg, OS_SIZE_2048 - padding, " \"src_city\": \"%s\",", al_data->geoipdatasrc ); + field_add_string(syslog_msg, OS_SIZE_2048 - padding, " \"dst_city\": \"%s\",", al_data->geoipdatadst ); +#endif + + if ( field_add_string(syslog_msg, OS_SIZE_2048 - padding, " \"dst_ip\": \"%s\",", al_data->dstip ) > 0 ) + field_add_int(syslog_msg, OS_SIZE_2048 - padding, " \"dst_port\": %d,", al_data->dstport ); + + field_add_string(syslog_msg, OS_SIZE_2048 - padding, " \"file\": \"%s\",", al_data->filename ); + field_add_string(syslog_msg, OS_SIZE_2048 - padding, " \"acct\": \"%s\",", al_data->user ); + field_add_string(syslog_msg, OS_SIZE_2048 - padding, " \"md5_old\": \"%s\",", al_data->old_md5 ); + field_add_string(syslog_msg, OS_SIZE_2048 - padding, " \"md5_new\": \"%s\",", al_data->new_md5 ); + field_add_string(syslog_msg, OS_SIZE_2048 - padding, " \"sha1_old\": \"%s\",", al_data->old_sha1 ); + field_add_string(syslog_msg, OS_SIZE_2048 - padding, " \"sha1_new\": \"%s\",", al_data->new_sha1 ); + /* Message */ + field_add_truncated(syslog_msg, OS_SIZE_2048 - padding, " \"message\": \"%s\"", json_safe_message, 2 ); + /* Closing brace */ + field_add_string(syslog_msg, OS_SIZE_2048, " }", "" ); + } + else if(syslog_config->format == SPLUNK_CSYSLOG) { - /* Building syslog message. */ + /* Build a Splunk Style Key/Value string for logging */ snprintf(syslog_msg, OS_SIZE_2048, - "<%d>%s %s ossec: Alert Level: %d; Rule: %d - %s; " - "Location: %s;%s%s %s", + "<%d>%s %s ossec: crit=%d id=%d description=\"%s\" component=\"%s\",", + + /* syslog header */ syslog_config->priority, tstamp, __shost, - al_data->level, al_data->rule, al_data->comment, - al_data->location, - /* Source ip. */ - srcip_msg, - user_msg, - al_data->log[0]); + /* OSSEC metadata */ + al_data->level, al_data->rule, json_safe_comment, + al_data->location + ); + /* Event specifics */ + field_add_string(syslog_msg, OS_SIZE_2048, " classification=\"%s\",", al_data->group ); + + if( field_add_string(syslog_msg, OS_SIZE_2048, " src_ip=\"%s\",", al_data->srcip ) > 0 ) + field_add_int(syslog_msg, OS_SIZE_2048, " src_port=%d,", al_data->srcport ); + +#ifdef GEOIP + field_add_string(syslog_msg, OS_SIZE_2048, " src_city=\"%s\",", al_data->geoipdatasrc ); + field_add_string(syslog_msg, OS_SIZE_2048, " dst_city=\"%s\",", al_data->geoipdatadst ); +#endif + + if( field_add_string(syslog_msg, OS_SIZE_2048, " dst_ip=\"%s\",", al_data->dstip ) > 0 ) + field_add_int(syslog_msg, OS_SIZE_2048, " dst_port=%d,", al_data->dstport ); + + field_add_string(syslog_msg, OS_SIZE_2048, " file=\"%s\",", al_data->filename ); + field_add_string(syslog_msg, OS_SIZE_2048, " acct=\"%s\",", al_data->user ); + field_add_string(syslog_msg, OS_SIZE_2048, " md5_old=\"%s\",", al_data->old_md5 ); + field_add_string(syslog_msg, OS_SIZE_2048, " md5_new=\"%s\",", al_data->new_md5 ); + field_add_string(syslog_msg, OS_SIZE_2048, " sha1_old=\"%s\",", al_data->old_sha1 ); + field_add_string(syslog_msg, OS_SIZE_2048, " sha1_new=\"%s\",", al_data->new_sha1 ); + /* Message */ + field_add_truncated(syslog_msg, OS_SIZE_2048, " message=\"%s\"", json_safe_message, 2 ); } OS_SendUDPbySize(syslog_config->socket, strlen(syslog_msg), syslog_msg); - + /* Free the malloc'd variables */ + free(json_safe_comment); + free(json_safe_message); + return(1); } diff --git a/src/os_csyslogd/config.c b/src/os_csyslogd/config.c index c087754..91770e1 100755 --- a/src/os_csyslogd/config.c +++ b/src/os_csyslogd/config.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_csyslogd/config.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -18,11 +19,11 @@ #include "config/config.h" -/** void *OS_SyslogConf(int test_config, char *cfgfile, +/** void *OS_SyslogConf(int test_config, char *cfgfile, SyslogConfig **syslog_config) * Reads configuration. */ -void *OS_ReadSyslogConf(int test_config, char *cfgfile, +void *OS_ReadSyslogConf(int test_config, char *cfgfile, SyslogConfig **syslog_config) { int modules = 0; @@ -33,15 +34,15 @@ void *OS_ReadSyslogConf(int test_config, char *cfgfile, modules|= CSYSLOGD; gen_config.data = syslog_config; - + /* Reading configuration */ if(ReadConfig(modules, cfgfile, &gen_config, NULL) < 0) { ErrorExit(CONFIG_ERROR, ARGV0, cfgfile); return(NULL); - } + } + - syslog_config = gen_config.data; return(syslog_config); diff --git a/src/os_csyslogd/csyslogd.c b/src/os_csyslogd/csyslogd.c index 97d7ff9..696d3fe 100755 --- a/src/os_csyslogd/csyslogd.c +++ b/src/os_csyslogd/csyslogd.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_csyslogd/csyslogd.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,12 +9,17 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ +/* strnlen is a GNU extension */ +#ifdef __linux__ + #define _GNU_SOURCE + #include +#endif #include "csyslogd.h" #include "os_net/os_net.h" @@ -25,8 +31,9 @@ void OS_CSyslogD(SyslogConfig **syslog_config) { int s = 0; - time_t tm; - struct tm *p; + time_t tm; + struct tm *p; + int tries = 0; file_queue *fileq; alert_data *al_data; @@ -34,12 +41,22 @@ void OS_CSyslogD(SyslogConfig **syslog_config) /* Getting currently time before starting */ tm = time(NULL); - p = localtime(&tm); + p = localtime(&tm); /* Initating file queue - to read the alerts */ os_calloc(1, sizeof(file_queue), fileq); - Init_FileQueue(fileq, p, 0); + while( (Init_FileQueue(fileq, p, 0) ) < 0 ) { + tries++; + if( tries > OS_CSYSLOGD_MAX_TRIES ) { + merror("%s: ERROR: Could not open queue after %d tries, exiting!", + ARGV0, tries + ); + exit(1); + } + sleep(1); + } + merror("%s: INFO: File queue connected.", ARGV0 ); /* Connecting to syslog. */ @@ -47,22 +64,22 @@ void OS_CSyslogD(SyslogConfig **syslog_config) while(syslog_config[s]) { syslog_config[s]->socket = OS_ConnectUDP(syslog_config[s]->port, - syslog_config[s]->server); + syslog_config[s]->server, 0); if(syslog_config[s]->socket < 0) { merror(CONNS_ERROR, ARGV0, syslog_config[s]->server); } else { - merror("%s: INFO: Forwarding alerts via syslog to: '%s:%d'.", - ARGV0, syslog_config[s]->server, syslog_config[s]->port); + merror("%s: INFO: Forwarding alerts via syslog to: '%s:%d'.", + ARGV0, syslog_config[s]->server, syslog_config[s]->port); } s++; } - + /* Infinite loop reading the alerts and inserting them. */ while(1) { @@ -93,4 +110,96 @@ void OS_CSyslogD(SyslogConfig **syslog_config) } } +/* Format Field for output */ +int field_add_string(char *dest, int size, const char *format, const char *value ) { + char buffer[OS_SIZE_2048]; + int len = 0; + int dest_sz = size - strnlen(dest, OS_SIZE_2048); + + if(dest_sz <= 0 ) { + // Not enough room in the buffer + return -1; + } + + if(value != NULL && + ( + ((value[0] != '(') && (value[1] != 'n') && (value[2] != 'o')) || + ((value[0] != '(') && (value[1] != 'u') && (value[2] != 'n')) || + ((value[0] != 'u') && (value[1] != 'n') && (value[4] != 'k')) + ) + ) { + len = snprintf(buffer, sizeof(buffer) - dest_sz - 1, format, value); + strncat(dest, buffer, dest_sz); + } + + return len; +} + +/* Add a field, but truncate if too long */ +int field_add_truncated(char *dest, int size, const char *format, const char *value, int fmt_size ) { + char buffer[OS_SIZE_2048]; + + int available_sz = size - strnlen(dest, OS_SIZE_2048); + int total_sz = strlen(value) + strlen(format) - fmt_size; + int field_sz = available_sz - strlen(format) + fmt_size; + + int len = 0; + char trailer[] = "..."; + char *truncated; + + if(available_sz <= 0 ) { + // Not enough room in the buffer + return -1; + } + + if(value != NULL && + ( + ((value[0] != '(') && (value[1] != 'n') && (value[2] != 'o')) || + ((value[0] != '(') && (value[1] != 'u') && (value[2] != 'n')) || + ((value[0] != 'u') && (value[1] != 'n') && (value[4] != 'k')) + ) + ) { + + if( (truncated=malloc(field_sz + 1)) != NULL ) { + if( total_sz > available_sz ) { + // Truncate and add a trailer + os_substr(truncated, value, 0, field_sz - strlen(trailer)); + strcat(truncated, trailer); + } + else { + strncpy(truncated,value,field_sz); + } + + len = snprintf(buffer, available_sz, format, truncated); + strncat(dest, buffer, available_sz); + } + else { + // Memory Error + len = -3; + } + } + // Free the temporary pointer + free(truncated); + + return len; +} + +/* Handle integers in the second position */ +int field_add_int(char *dest, int size, const char *format, const int value ) { + char buffer[255]; + int len = 0; + int dest_sz = size - strnlen(dest, OS_SIZE_2048); + + if(dest_sz <= 0 ) { + // Not enough room in the buffer + return -1; + } + + if( value > 0 ) { + len = snprintf(buffer, sizeof(buffer), format, value); + strncat(dest, buffer, dest_sz); + } + + return len; +} /* EOF */ diff --git a/src/os_csyslogd/csyslogd.h b/src/os_csyslogd/csyslogd.h index 87bfc40..28435c9 100755 --- a/src/os_csyslogd/csyslogd.h +++ b/src/os_csyslogd/csyslogd.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_csyslogd/csyslogd.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -19,6 +20,7 @@ #include "config/csyslogd-config.h" +#define OS_CSYSLOGD_MAX_TRIES 10 /** Prototypes **/ @@ -34,6 +36,10 @@ int OS_Alert_SendSyslog(alert_data *al_data, SyslogConfig *syslog_config); /* Database inserting main function */ void OS_CSyslogD(SyslogConfig **syslog_config); +/* Conditional Field Formatting */ +int field_add_int(char *dest, int size, const char *format, const int value ); +int field_add_string(char *dest, int size, const char *format, const char *value ); +int field_add_truncated(char *dest, int size, const char *format, const char *value, int fmt_size ); /** Global vars **/ diff --git a/src/os_csyslogd/main.c b/src/os_csyslogd/main.c index 1d8a11f..5d110f5 100755 --- a/src/os_csyslogd/main.c +++ b/src/os_csyslogd/main.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_csyslogd/main.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -35,7 +36,7 @@ int main(int argc, char **argv) /* Setting the name */ OS_SetName(ARGV0); - + while((c = getopt(argc, argv, "vVdhtfu:g:D:c:")) != -1){ switch(c){ @@ -44,7 +45,7 @@ int main(int argc, char **argv) break; case 'v': print_version(); - break; + break; case 'h': help(ARGV0); break; @@ -68,13 +69,14 @@ int main(int argc, char **argv) if(!optarg) ErrorExit("%s: -D needs an argument",ARGV0); dir=optarg; + break; case 'c': if(!optarg) ErrorExit("%s: -c needs an argument",ARGV0); cfg = optarg; break; case 't': - test_config = 1; + test_config = 1; break; default: help(ARGV0); @@ -116,14 +118,14 @@ int main(int argc, char **argv) if(ltmp) *ltmp = '\0'; } - + /* Exit here if test config is set */ if(test_config) exit(0); - - - if (!run_foreground) + + + if (!run_foreground) { /* Going on daemon mode */ nowDaemon(); @@ -131,7 +133,7 @@ int main(int argc, char **argv) } - + /* Not configured */ if(!syslog_config || !syslog_config[0]) { @@ -140,13 +142,13 @@ int main(int argc, char **argv) exit(0); } - + /* Privilege separation */ if(Privsep_SetGroup(gid) < 0) ErrorExit(SETGID_ERROR,ARGV0,group); - + /* chrooting */ if(Privsep_Chroot(dir) < 0) ErrorExit(CHROOT_ERROR,ARGV0,dir); @@ -156,8 +158,8 @@ int main(int argc, char **argv) nowChroot(); - - /* Changing user */ + + /* Changing user */ if(Privsep_SetUser(uid) < 0) ErrorExit(SETUID_ERROR,ARGV0,user); @@ -169,15 +171,15 @@ int main(int argc, char **argv) /* Signal manipulation */ StartSIG(ARGV0); - + /* Creating PID files */ if(CreatePID(ARGV0, getpid()) < 0) ErrorExit(PID_ERROR, ARGV0); - + /* Start up message */ verbose(STARTUP_MSG, ARGV0, (int)getpid()); - + /* the real daemon now */ OS_CSyslogD(syslog_config); diff --git a/src/os_dbd/alert.c b/src/os_dbd/alert.c index 517b65c..991157c 100755 --- a/src/os_dbd/alert.c +++ b/src/os_dbd/alert.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_dbd/alert.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -78,7 +79,7 @@ int __DBSelectLocation(char *location, DBConfig *db_config) int __DBInsertLocation(char *location, DBConfig *db_config) { char sql_query[OS_SIZE_1024]; - + memset(sql_query, '\0', OS_SIZE_1024); /* Generating SQL */ @@ -108,6 +109,7 @@ int OS_Alert_InsertDB(alert_data *al_data, DBConfig *db_config) { int i; unsigned int s_ip = 0, d_ip = 0, location_id = 0; + unsigned short s_port = 0, d_port = 0; int *loc_id; char sql_query[OS_SIZE_8192 +1]; char *fulllog = NULL; @@ -116,7 +118,7 @@ int OS_Alert_InsertDB(alert_data *al_data, DBConfig *db_config) /* Clearing the memory before insert */ sql_query[0] = '\0'; sql_query[OS_SIZE_8192] = '\0'; - + /* Converting srcip to int */ if(al_data->srcip) @@ -129,7 +131,24 @@ int OS_Alert_InsertDB(alert_data *al_data, DBConfig *db_config) s_ip = net.s_addr; } } - d_ip = 0; + + /* Converting dstip to int */ + if(al_data->dstip) + { + struct in_addr net; + + /* Extracting ip address */ + if(inet_aton(al_data->dstip, &net)) + { + d_ip = net.s_addr; + } + } + + /* Source Port */ + s_port = al_data->srcport; + + /* Destination Port */ + d_port = al_data->dstport; /* Escaping strings */ @@ -138,8 +157,8 @@ int OS_Alert_InsertDB(alert_data *al_data, DBConfig *db_config) /* We first need to insert the location */ loc_id = OSHash_Get(db_config->location_hash, al_data->location); - - + + /* If we dont have location id, we must select and/or insert in the db */ if(!loc_id) { @@ -153,7 +172,7 @@ int OS_Alert_InsertDB(alert_data *al_data, DBConfig *db_config) if(!location_id) { - merror("%s: Unable to insert location: '%s'.", + merror("%s: Unable to insert location: '%s'.", ARGV0, al_data->location); return(0); } @@ -164,15 +183,30 @@ int OS_Alert_InsertDB(alert_data *al_data, DBConfig *db_config) *loc_id = location_id; OSHash_Add(db_config->location_hash, al_data->location, loc_id); } - + i = 0; while(al_data->log[i]) { - fulllog = os_LoadString(fulllog, al_data->log[i]); + long len = strlen(al_data->log[i]); + char templog[len+2]; + if (al_data->log[i+1]) { + snprintf(templog, len, "%s\n", al_data->log[i]); + } + else { + snprintf(templog, len, "%s", al_data->log[i]); + } + fulllog = os_LoadString(fulllog, templog); +// fulllog = os_LoadString(fulllog, al_data->log[i]); i++; } osdb_escapestr(fulllog); + if(strlen(fulllog) > 7456) + { + fulllog[7454] = '.'; + fulllog[7455] = '.'; + fulllog[7456] = '\0'; + } /* Inserting data */ @@ -183,7 +217,7 @@ int OS_Alert_InsertDB(alert_data *al_data, DBConfig *db_config) "INSERT INTO " "data(id, server_id, \"user\", full_log) " "VALUES ('%u', '%u', '%s', '%s') ", - db_config->alert_id, db_config->server_id, + db_config->alert_id, db_config->server_id, al_data->user, fulllog); } else @@ -192,29 +226,32 @@ int OS_Alert_InsertDB(alert_data *al_data, DBConfig *db_config) "INSERT INTO " "data(id, server_id, user, full_log) " "VALUES ('%u', '%u', '%s', '%s') ", - db_config->alert_id, db_config->server_id, + db_config->alert_id, db_config->server_id, al_data->user, fulllog); } free(fulllog); fulllog = NULL; - - + + /* Inserting into the db */ if(!osdb_query_insert(db_config->conn, sql_query)) { merror(DB_GENERROR, ARGV0); } - + /* Generating final SQL */ snprintf(sql_query, OS_SIZE_8192, "INSERT INTO " - "alert(id,server_id,rule_id,timestamp,location_id,src_ip) " - "VALUES ('%u', '%u', '%u','%u', '%u', '%lu')", + "alert(id,server_id,rule_id,timestamp,location_id,src_ip,src_port,dst_ip,dst_port,alertid) " + "VALUES ('%u', '%u', '%u','%u', '%u', '%lu', '%u', '%lu', '%u', '%s')", db_config->alert_id, db_config->server_id, al_data->rule, - (unsigned int)time(0), *loc_id, (unsigned long)ntohl(s_ip)); + (unsigned int)time(0), *loc_id, + (unsigned long)ntohl(s_ip), (unsigned short)s_port, + (unsigned long)ntohl(d_ip), (unsigned short)d_port, + al_data->alertid); /* Inserting into the db */ @@ -223,7 +260,7 @@ int OS_Alert_InsertDB(alert_data *al_data, DBConfig *db_config) merror(DB_GENERROR, ARGV0); } - + db_config->alert_id++; return(1); } diff --git a/src/os_dbd/config.c b/src/os_dbd/config.c index ee422b6..9fed903 100755 --- a/src/os_dbd/config.c +++ b/src/os_dbd/config.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_dbd/config.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -31,7 +32,7 @@ int OS_ReadDBConf(int test_config, char *cfgfile, DBConfig *db_config) modules|= CDBD; modules|= CRULES; - + /* Allocating config just to get the rules. */ os_calloc(1, sizeof(_Config), tmp_config); @@ -53,7 +54,7 @@ int OS_ReadDBConf(int test_config, char *cfgfile, DBConfig *db_config) if(ReadConfig(modules, cfgfile, tmp_config, db_config) < 0) return(OS_INVALID); - + /* Here, we assign the rules to db_config and free the rest * of the Config. */ @@ -72,7 +73,7 @@ int OS_ReadDBConf(int test_config, char *cfgfile, DBConfig *db_config) { return(0); } - + /* Checking for a valid config. */ if(!db_config->host || @@ -97,7 +98,7 @@ int OS_ReadDBConf(int test_config, char *cfgfile, DBConfig *db_config) osdb_close = mysql_osdb_close; } #endif - + #ifdef UPOSTGRES if(db_config->db_type == POSTGDB) { @@ -116,17 +117,17 @@ int OS_ReadDBConf(int test_config, char *cfgfile, DBConfig *db_config) { #ifndef UMYSQL merror(DB_COMPILED, ARGV0, "mysql"); - return(OS_INVALID); + return(OS_INVALID); #endif } else if(db_config->db_type == POSTGDB) { #ifndef UPOSTGRES merror(DB_COMPILED, ARGV0, "postgresql"); - return(OS_INVALID); + return(OS_INVALID); #endif } - + if(osdb_connect == NULL) { diff --git a/src/os_dbd/db_op.c b/src/os_dbd/db_op.c index f5ff2f6..df73ade 100755 --- a/src/os_dbd/db_op.c +++ b/src/os_dbd/db_op.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_dbd/db_op.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -11,7 +12,7 @@ * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ - + /* Common lib for dealing with databases */ @@ -46,7 +47,7 @@ void osdb_escapestr(char *str) { return; } - + while(*str) { if(*str == '\'') @@ -84,27 +85,27 @@ void osdb_checkerror() ErrorExit(DB_MAINERROR, ARGV0); } - + /* If error count is too large, we try to reconnect. */ if(db_config_pt->error_count > 0) { int i = 0; if(db_config_pt->conn) { - osdb_close(db_config_pt->conn); + osdb_close(db_config_pt->conn); db_config_pt->conn = NULL; } while(i <= db_config_pt->maxreconnect) { merror(DB_ATTEMPT, ARGV0); - db_config_pt->conn = osdb_connect(db_config_pt->host, + db_config_pt->conn = osdb_connect(db_config_pt->host, db_config_pt->user, - db_config_pt->pass, + db_config_pt->pass, db_config_pt->db, db_config_pt->port, db_config_pt->sock); - + /* If we were able to reconnect, keep going. */ if(db_config_pt->conn) { @@ -121,11 +122,11 @@ void osdb_checkerror() { ErrorExit(DB_MAINERROR, ARGV0); } - - + + verbose("%s: Connected to database '%s' at '%s'.", ARGV0, db_config_pt->db, db_config_pt->host); - + } } @@ -182,8 +183,8 @@ void *mysql_osdb_connect(char *host, char *user, char *pass, char *db, unsigned int p_type = MYSQL_PROTOCOL_TCP; mysql_options(conn, MYSQL_OPT_PROTOCOL, (char *)&p_type); } - } - if(mysql_real_connect(conn, host, user, pass, db, + } + if(mysql_real_connect(conn, host, user, pass, db, port, sock, 0) == NULL) { merror(DBCONN_ERROR, ARGV0, host, db, mysql_error(conn)); @@ -208,7 +209,7 @@ void *mysql_osdb_close(void *db_conn) /** int mysql_osdb_query_insert(void *db_conn, char *query) - * Sends insert query to database. + * Sends insert query to database. */ int mysql_osdb_query_insert(void *db_conn, char *query) { @@ -234,7 +235,7 @@ int mysql_osdb_query_select(void *db_conn, char *query) int result_int = 0; MYSQL_RES *result_data; MYSQL_ROW result_row; - + /* Sending the query. It can not fail. */ if(mysql_query(db_conn, query) != 0) @@ -245,7 +246,7 @@ int mysql_osdb_query_select(void *db_conn, char *query) return(0); } - + /* Getting result */ result_data = mysql_use_result(db_conn); if(result_data == NULL) @@ -255,7 +256,7 @@ int mysql_osdb_query_select(void *db_conn, char *query) osdb_seterror(); return(0); } - + /* Getting row. We only care about the first result. */ result_row = mysql_fetch_row(result_data); @@ -263,7 +264,7 @@ int mysql_osdb_query_select(void *db_conn, char *query) { result_int = atoi(result_row[0]); } - + mysql_free_result(result_data); @@ -280,11 +281,11 @@ int mysql_osdb_query_select(void *db_conn, char *query) #if defined UPOSTGRES -/** void *postgresql_osdb_connect(char *host, char *user, char *pass, char *db) - * Create the PostgreSQL database connection. +/** void *postgresql_osdb_connect(char *host, char *user, char *pass, char *db) + * Create the PostgreSQL database connection. * Return NULL on error */ -void *postgresql_osdb_connect(char *host, char *user, char *pass, char *db, +void *postgresql_osdb_connect(char *host, char *user, char *pass, char *db, int port, char *sock) { PGconn *conn; @@ -316,13 +317,13 @@ void *postgresql_osdb_close(void *db_conn) /** int postgresql_osdb_query_insert(void *db_conn, char *query) - * Sends insert query to database. + * Sends insert query to database. */ int postgresql_osdb_query_insert(void *db_conn, char *query) { PGresult *result; - - + + result = PQexec(db_conn,query); if(!result) { @@ -330,8 +331,8 @@ int postgresql_osdb_query_insert(void *db_conn, char *query) osdb_seterror(); return(0); } - - + + if(PQresultStatus(result) != PGRES_COMMAND_OK) { merror(DBQUERY_ERROR, ARGV0, query, PQerrorMessage(db_conn)); @@ -340,7 +341,7 @@ int postgresql_osdb_query_insert(void *db_conn, char *query) return(0); } - + PQclear(result); return(1); } @@ -363,7 +364,7 @@ int postgresql_osdb_query_select(void *db_conn, char *query) osdb_seterror(); return(0); } - + if((PQresultStatus(result) == PGRES_TUPLES_OK)) { if(PQntuples(result) == 1) @@ -395,7 +396,7 @@ int postgresql_osdb_query_select(void *db_conn, char *query) -void *none_osdb_connect(char *host, char *user, char *pass, char *db, +void *none_osdb_connect(char *host, char *user, char *pass, char *db, int port, char *sock) { char *tmp; @@ -403,8 +404,8 @@ void *none_osdb_connect(char *host, char *user, char *pass, char *db, /* Just to avoid warnings. */ tmp = host; tmp = user; tmp = pass; tmp = db; - - + + merror("%s: ERROR: Database support not enabled. Exiting.", ARGV0); return(NULL); } @@ -430,7 +431,7 @@ void *none_osdb_query_select(void *db_conn, char *query) void *tmp; tmp = db_conn; tmp = query; - + merror("%s: ERROR: Database support not enabled. Exiting.", ARGV0); return(0); } diff --git a/src/os_dbd/db_op.h b/src/os_dbd/db_op.h index fdbe101..a6031fc 100755 --- a/src/os_dbd/db_op.h +++ b/src/os_dbd/db_op.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_dbd/db_op.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -11,7 +12,7 @@ * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ - + /* Common API for dealing with databases */ @@ -49,11 +50,12 @@ void osdb_escapestr(char *str); * Available chars: a-z, A-Z, 0-9, -, _, ., %, $, @, (, ), +, *, / * Basically: 040-046 (oct) * 050-176 (oct) + * 8/27/2012: Modified to allow new lines - \012 */ static const unsigned char insert_map[] = { '\000', '\000', '\002', '\003', '\004', '\005', '\006', '\007', - '\010', '\011', '\012', '\013', '\014', '\015', '\016', '\017', + '\010', '\011', '\001', '\013', '\014', '\015', '\016', '\017', '\020', '\021', '\022', '\023', '\024', '\025', '\026', '\027', '\030', '\031', '\032', '\033', '\034', '\035', '\036', '\037', '\001', '\001', '\001', '\001', '\001', '\001', '\001', '\047', diff --git a/src/os_dbd/dbd.c b/src/os_dbd/dbd.c index 925e01b..dff139c 100755 --- a/src/os_dbd/dbd.c +++ b/src/os_dbd/dbd.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_dbd/dbd.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -31,8 +32,8 @@ */ void OS_DBD(DBConfig *db_config) { - time_t tm; - struct tm *p; + time_t tm; + struct tm *p; file_queue *fileq; alert_data *al_data; diff --git a/src/os_dbd/dbd.h b/src/os_dbd/dbd.h index dc4a329..0defbfb 100755 --- a/src/os_dbd/dbd.h +++ b/src/os_dbd/dbd.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_dbd/dbd.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -30,7 +31,7 @@ int OS_ReadDBConf(int test_config, char *cfgfile, DBConfig *db_config); /* Inserts server info to the db. */ int OS_Server_ReadInsertDB(void *db_config); - + /* Insert rules in to the database */ int OS_InsertRulesDB(DBConfig *db_config); diff --git a/src/os_dbd/main.c b/src/os_dbd/main.c index 613ef50..6e0b2a2 100755 --- a/src/os_dbd/main.c +++ b/src/os_dbd/main.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_dbd/main.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -30,7 +31,7 @@ void db_info() { print_out(" "); print_out("%s %s - %s", __name, __version, __author); - + #ifdef UMYSQL print_out("Compiled with MySQL support."); #endif @@ -42,7 +43,7 @@ void db_info() #if !defined(UMYSQL) && !defined(UPOSTGRES) print_out("Compiled without any Database support."); #endif - + print_out(" "); print_out("%s",__license); @@ -70,7 +71,7 @@ int main(int argc, char **argv) /* Setting the name */ OS_SetName(ARGV0); - + while((c = getopt(argc, argv, "vVdhtfu:g:D:c:")) != -1){ switch(c){ @@ -79,7 +80,7 @@ int main(int argc, char **argv) break; case 'v': db_info(); - break; + break; case 'h': help(ARGV0); break; @@ -103,13 +104,14 @@ int main(int argc, char **argv) if(!optarg) ErrorExit("%s: -D needs an argument",ARGV0); dir=optarg; + break; case 'c': if(!optarg) ErrorExit("%s: -c needs an argument",ARGV0); cfg = optarg; break; case 't': - test_config = 1; + test_config = 1; break; default: help(ARGV0); @@ -142,9 +144,9 @@ int main(int argc, char **argv) /* Exit here if test config is set */ if(test_config) exit(0); - - - if(!run_foreground) + + + if(!run_foreground) { /* Going on daemon mode */ nowDaemon(); @@ -152,7 +154,7 @@ int main(int argc, char **argv) } - + /* Not configured */ if(c == 0) { @@ -160,10 +162,10 @@ int main(int argc, char **argv) exit(0); } - + /* Maybe disable this debug? */ debug1("%s: DEBUG: Connecting to '%s', using '%s', '%s', '%s', %d,'%s'.", - ARGV0, db_config.host, db_config.user, + ARGV0, db_config.host, db_config.user, db_config.pass, db_config.db,db_config.port,db_config.sock); @@ -174,13 +176,13 @@ int main(int argc, char **argv) /* Getting maximum reconned attempts */ db_config.maxreconnect = getDefine_Int("dbd", "reconnect_attempts", 1, 9999); - - + + /* Connecting to the database */ c = 0; while(c <= (db_config.maxreconnect * 10)) { - db_config.conn = osdb_connect(db_config.host, db_config.user, + db_config.conn = osdb_connect(db_config.host, db_config.user, db_config.pass, db_config.db, db_config.port,db_config.sock); @@ -192,7 +194,7 @@ int main(int argc, char **argv) c++; sleep(c * 60); - + } @@ -202,18 +204,18 @@ int main(int argc, char **argv) merror(DB_CONFIGERR, ARGV0); ErrorExit(CONFIG_ERROR, ARGV0, cfg); } - + /* We must notify that we connected -- easy debugging */ - verbose("%s: Connected to database '%s' at '%s'.", + verbose("%s: Connected to database '%s' at '%s'.", ARGV0, db_config.db, db_config.host); - + /* Privilege separation */ if(Privsep_SetGroup(gid) < 0) ErrorExit(SETGID_ERROR,ARGV0,group); - + /* chrooting */ if(Privsep_Chroot(dir) < 0) ErrorExit(CHROOT_ERROR,ARGV0,dir); @@ -237,8 +239,8 @@ int main(int argc, char **argv) ErrorExit(CONFIG_ERROR, ARGV0, cfg); } - - /* Changing user */ + + /* Changing user */ if(Privsep_SetUser(uid) < 0) ErrorExit(SETUID_ERROR,ARGV0,user); @@ -250,15 +252,15 @@ int main(int argc, char **argv) /* Signal manipulation */ StartSIG(ARGV0); - + /* Creating PID files */ if(CreatePID(ARGV0, getpid()) < 0) ErrorExit(PID_ERROR,ARGV0); - + /* Start up message */ verbose(STARTUP_MSG, ARGV0, (int)getpid()); - + /* the real daemon now */ OS_DBD(&db_config); diff --git a/src/os_dbd/mysql.schema b/src/os_dbd/mysql.schema index b95ff77..e5f1aeb 100644 --- a/src/os_dbd/mysql.schema +++ b/src/os_dbd/mysql.schema @@ -1,4 +1,4 @@ -# @(#) $Id$ */ +# @(#) $Id: ./src/os_dbd/mysql.schema, 2011/09/08 dcid Exp $ # # Copyright (C) 2009 Trend Micro Inc. # All rights reserved. @@ -92,6 +92,7 @@ CREATE TABLE alert dst_ip INT UNSIGNED, src_port SMALLINT UNSIGNED, dst_port SMALLINT UNSIGNED, + alertid TINYTEXT DEFAULT NULL, PRIMARY KEY (id, server_id), INDEX time (timestamp), INDEX (rule_id), diff --git a/src/os_dbd/postgresql.schema b/src/os_dbd/postgresql.schema index ea098e0..73736a5 100644 --- a/src/os_dbd/postgresql.schema +++ b/src/os_dbd/postgresql.schema @@ -1,4 +1,4 @@ --- @(#) $Id$ */ +-- @(#) $Id: ./src/os_dbd/postgresql.schema, 2011/09/08 dcid Exp $ -- -- Copyright (C) 2009 Trend Micro Inc. -- All rights reserved. @@ -91,6 +91,7 @@ CREATE TABLE alert dst_ip INT8, src_port INT4, dst_port INT4, + alertid TEXT DEFAULT NULL, PRIMARY KEY (id, server_id) ); CREATE INDEX time on alert(timestamp); diff --git a/src/os_dbd/rules.c b/src/os_dbd/rules.c index e1fc23d..bce942a 100755 --- a/src/os_dbd/rules.c +++ b/src/os_dbd/rules.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_dbd/rules.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -51,7 +52,7 @@ int __Groups_SelectGroup(char *group, DBConfig *db_config) int __Groups_InsertGroup(char *group, DBConfig *db_config) { char sql_query[OS_SIZE_1024]; - + memset(sql_query, '\0', OS_SIZE_1024); /* Generating SQL */ @@ -136,7 +137,7 @@ void _Groups_ReadInsertDB(RuleInfo *rule, DBConfig *db_config) char *tmp_group; char *tmp_str; - + debug1("%s: DEBUG: entering _Groups_ReadInsertDB", ARGV0); @@ -145,7 +146,7 @@ void _Groups_ReadInsertDB(RuleInfo *rule, DBConfig *db_config) { return; } - + tmp_str = strchr(rule->group, ','); tmp_group = rule->group; @@ -163,7 +164,7 @@ void _Groups_ReadInsertDB(RuleInfo *rule, DBConfig *db_config) while(*tmp_group == ' ') tmp_group++; - + /* Checking for empty group */ if(*tmp_group == '\0') { @@ -200,7 +201,7 @@ void _Groups_ReadInsertDB(RuleInfo *rule, DBConfig *db_config) } } - + /* Getting next category */ tmp_group = tmp_str; if(tmp_group) @@ -208,7 +209,7 @@ void _Groups_ReadInsertDB(RuleInfo *rule, DBConfig *db_config) tmp_str = strchr(tmp_group, ','); } } - + return; } @@ -223,7 +224,7 @@ void *_Rules_ReadInsertDB(RuleInfo *rule, void *db_config) char sql_query[OS_SIZE_1024]; memset(sql_query, '\0', OS_SIZE_1024); - + /* Escaping strings */ osdb_escapestr(rule->group); osdb_escapestr(rule->comment); @@ -234,11 +235,11 @@ void *_Rules_ReadInsertDB(RuleInfo *rule, void *db_config) rule->level = 20; if(rule->level < 0) rule->level = 0; - - + + debug1("%s: DEBUG: entering _Rules_ReadInsertDB()", ARGV0); - - + + /* Checking rule limit */ if(rule->sigid < 0 || rule->sigid > 9999999) { @@ -249,18 +250,18 @@ void *_Rules_ReadInsertDB(RuleInfo *rule, void *db_config) /* Inserting group into the signature mapping */ _Groups_ReadInsertDB(rule, db_config); - - - + + + debug2("%s: DEBUG: Inserting: %d", ARGV0, rule->sigid); - + /* Generating SQL */ snprintf(sql_query, OS_SIZE_1024 -1, "SELECT id FROM signature " "where rule_id = %u", rule->sigid); - + if(osdb_query_select(dbc->conn, sql_query) == 0) { snprintf(sql_query, OS_SIZE_1024 -1, @@ -277,7 +278,7 @@ void *_Rules_ReadInsertDB(RuleInfo *rule, void *db_config) rule->level, rule->comment,rule->sigid); } - + /* Checking return code. */ if(!osdb_query_insert(dbc->conn, sql_query)) { @@ -291,12 +292,12 @@ void *_Rules_ReadInsertDB(RuleInfo *rule, void *db_config) int OS_InsertRulesDB(DBConfig *db_config) { char **rulesfiles; - + rulesfiles = db_config->includes; while(rulesfiles && *rulesfiles) { debug1("%s: Reading rules file: '%s'", ARGV0, *rulesfiles); - + if(OS_ReadXMLRules(*rulesfiles, _Rules_ReadInsertDB, db_config) < 0) { merror(RULES_ERROR, ARGV0, *rulesfiles); diff --git a/src/os_dbd/server.c b/src/os_dbd/server.c index 8a418b9..0f9f855 100755 --- a/src/os_dbd/server.c +++ b/src/os_dbd/server.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_dbd/server.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -50,14 +51,14 @@ int __DBSelectServer(char *server, DBConfig *db_config) int __DBInsertServer(char *server, char *info, DBConfig *db_config) { char sql_query[OS_SIZE_1024]; - + memset(sql_query, '\0', OS_SIZE_1024); /* Checking if the server is present */ snprintf(sql_query, OS_SIZE_1024 -1, "SELECT id from server where hostname = '%s'", server); - + /* If not present, we insert */ if(osdb_query_select(db_config->conn, sql_query) == 0) { @@ -105,10 +106,10 @@ int OS_Server_ReadInsertDB(void *db_config) int server_id = 0; char *info; - + debug1("%s: DEBUG: entering OS_Server_ReadInsertDB()", ARGV0); - + /* Getting servers hostname */ memset(__shost, '\0', 512); if(gethostname(__shost, 512 -1) != 0) @@ -138,8 +139,8 @@ int OS_Server_ReadInsertDB(void *db_config) /* Getting server id */ server_id = __DBSelectServer(__shost, (DBConfig *)db_config); - - + + return(server_id); } diff --git a/src/os_execd/config.c b/src/os_execd/config.c index f275217..17c1166 100755 --- a/src/os_execd/config.c +++ b/src/os_execd/config.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_execd/config.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -10,7 +11,8 @@ */ -#include "shared.h" +#include "shared.h" +#include "execd.h" /* ExecdConfig v0.1, 2006/03/24 @@ -18,13 +20,17 @@ */ int ExecdConfig(char * cfgfile) { + extern int repeated_offenders_timeout[]; #ifdef WIN32 int is_disabled = 1; #else int is_disabled = 0; #endif char *(xmlf[]) = {"ossec_config", "active-response", "disabled", NULL}; + char *(blocks[]) = {"ossec_config", "active-response", "repeated_offenders", NULL}; char *disable_entry; + char *repeated_t; + char **repeated_a; OS_XML xml; @@ -50,12 +56,54 @@ int ExecdConfig(char * cfgfile) else { merror(XML_VALUEERR, ARGV0, - "disabled", - disable_entry); + "disabled", + disable_entry); return(-1); } } - + + repeated_t = OS_GetOneContentforElement(&xml, blocks); + if(repeated_t) + { + int i = 0; + int j = 0; + repeated_a = OS_StrBreak(',', repeated_t, 5); + if(!repeated_a) + { + merror(XML_VALUEERR, ARGV0, + "repeated_offenders", + disable_entry); + return(-1); + } + + while(repeated_a[i] != NULL) + { + char *tmpt = repeated_a[i]; + while(*tmpt != '\0') + { + if(*tmpt == ' ' || *tmpt == '\t') + tmpt++; + else + break; + } + + if(*tmpt == '\0') + { + i++; + continue; + } + + repeated_offenders_timeout[j] = atoi(tmpt); + verbose("%s: INFO: Adding offenders timeout: %d (for #%d)", + ARGV0, repeated_offenders_timeout[j], j+1); + j++; + repeated_offenders_timeout[j] = 0; + if(j >= 6) break; + i++; + } + } + + OS_ClearXML(&xml); return(is_disabled); } diff --git a/src/os_execd/exec.c b/src/os_execd/exec.c index b90bb40..7b0a673 100755 --- a/src/os_execd/exec.c +++ b/src/os_execd/exec.c @@ -1,11 +1,12 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_execd/exec.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * * This program is a free software; you can redistribute it * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software + * License (version 2) as published by the FSF - Free Software * Foundation */ @@ -21,9 +22,9 @@ int exec_size = 0; int f_time_reading = 1; -/** int ReadExecConfig() v0.1: +/** int ReadExecConfig() v0.1: * Reads the shared exec config. - * Returns 1 on success or 0 on failure. + * Returns 1 on success or 0 on failure. * Format of the file is 'name - command - timeout' */ int ReadExecConfig() @@ -41,8 +42,8 @@ int ReadExecConfig() exec_timeout[i] = 0; } exec_size = 0; - - + + /* Opening file */ fp = fopen(DEFAULTARPATH, "r"); if(!fp) @@ -70,7 +71,7 @@ int ReadExecConfig() *tmp_str = '\0'; tmp_str++; - + /* Searching for ' ' and - */ if(*tmp_str == '-') { @@ -83,12 +84,12 @@ int ReadExecConfig() } - + /* Setting the name */ strncpy(exec_names[exec_size], str_pt, OS_FLSIZE); exec_names[exec_size][OS_FLSIZE] = '\0'; - + str_pt = tmp_str; tmp_str = strchr(tmp_str, ' '); @@ -99,11 +100,11 @@ int ReadExecConfig() } *tmp_str = '\0'; - + /* Writting the full command path */ - snprintf(exec_cmd[exec_size], OS_FLSIZE, - "%s/%s", - AR_BINDIRPATH, + snprintf(exec_cmd[exec_size], OS_FLSIZE, + "%s/%s", + AR_BINDIRPATH, str_pt); process_file = fopen(exec_cmd[exec_size], "r"); if(!process_file) @@ -115,14 +116,14 @@ int ReadExecConfig() ARGV0, exec_cmd[exec_size]); } - exec_cmd[exec_size][0] = '\0'; + exec_cmd[exec_size][0] = '\0'; } else { fclose(process_file); } - + /* Searching for ' ' and - */ tmp_str++; if(*tmp_str == '-') @@ -134,14 +135,14 @@ int ReadExecConfig() merror(EXEC_INV_CONF, ARGV0, DEFAULTARPATH); continue; } - - - str_pt = tmp_str; + + + str_pt = tmp_str; tmp_str = strchr(tmp_str, '\n'); if(tmp_str) *tmp_str = '\0'; - + /* Getting the exec timeout */ exec_timeout[exec_size] = atoi(str_pt); @@ -165,7 +166,7 @@ int ReadExecConfig() } } } - + if(dup_entry) { exec_cmd[exec_size][0] = '\0'; diff --git a/src/os_execd/execd.c b/src/os_execd/execd.c index d1b637c..09b5107 100755 --- a/src/os_execd/execd.c +++ b/src/os_execd/execd.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_execd/execd.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -32,17 +33,19 @@ typedef struct _timeout_data /* Timeout list */ OSList *timeout_list; OSListNode *timeout_node; - +OSHash *repeated_hash; +int repeated_offenders_timeout[] = {0,0,0,0,0,0,0}; + -/** +/** * Shudowns execd properly. */ void execd_shutdown() { /* Removing pending active responses. */ merror(EXEC_SHUTDOWN, ARGV0); - + timeout_node = OSList_GetFirstNode(timeout_list); while(timeout_node) { @@ -82,7 +85,7 @@ int main(int argc, char **argv) /* Setting the name */ OS_SetName(ARGV0); - + while((c = getopt(argc, argv, "Vtdhfu:g:D:c:")) != -1){ switch(c){ @@ -107,6 +110,7 @@ int main(int argc, char **argv) if(!optarg) ErrorExit("%s: -D needs an argument.",ARGV0); dir = optarg; + break; case 'c': if(!optarg) ErrorExit("%s: -c needs an argument.",ARGV0); @@ -114,7 +118,7 @@ int main(int argc, char **argv) break; case 't': test_config = 1; - break; + break; default: help(ARGV0); break; @@ -130,7 +134,7 @@ int main(int argc, char **argv) ErrorExit(USER_ERROR,ARGV0,"",group); - /* Privilege separation */ + /* Privilege separation */ if(Privsep_SetGroup(gid) < 0) ErrorExit(SETGID_ERROR,ARGV0,group); @@ -145,18 +149,18 @@ int main(int argc, char **argv) /* Exit if test_config */ if(test_config) exit(0); - - + + /* Signal manipulation */ StartSIG2(ARGV0, execd_shutdown); - - if (!run_foreground) + + if (!run_foreground) { /* Going daemon */ nowDaemon(); goDaemon(); - } + } /* Active response disabled */ @@ -165,12 +169,12 @@ int main(int argc, char **argv) verbose(EXEC_DISABLED, ARGV0); exit(0); } - + /* Creating the PID file */ if(CreatePID(ARGV0, getpid()) < 0) merror(PID_ERROR, ARGV0); - + /* Starting queue (exec queue) */ if((m_queue = StartMQ(EXECQUEUEPATH,READ)) < 0) ErrorExit(QUEUE_ERROR, ARGV0, EXECQUEUEPATH, strerror(errno)); @@ -178,11 +182,11 @@ int main(int argc, char **argv) /* Start up message */ verbose(STARTUP_MSG, ARGV0, (int)getpid()); - - /* The real daemon Now */ + + /* The real daemon Now */ ExecdStart(m_queue); - + exit(0); } @@ -206,7 +210,7 @@ void FreeTimeoutEntry(void *timeout_entry_pt) { return; } - + tmp_str = timeout_entry->command; /* Clearing the command arguments */ @@ -239,7 +243,7 @@ void ExecdStart(int q) { int i, childcount = 0; time_t curr_time; - + char buffer[OS_MAXSTR + 1]; char *tmp_msg = NULL; char *name; @@ -251,32 +255,43 @@ void ExecdStart(int q) fd_set fdset; struct timeval socket_timeout; - + /* Clearing the buffer */ memset(buffer, '\0', OS_MAXSTR +1); - - + + /* Initializing the cmd arguments */ for(i = 0; i<= MAX_ARGS +1; i++) { cmd_args[i] = NULL; } - - + + /* Creating list for timeout */ - timeout_list = OSList_Create(); + timeout_list = OSList_Create(); if(!timeout_list) { ErrorExit(LIST_ERROR, ARGV0); } - - + + + if(repeated_offenders_timeout[0] != 0) + { + repeated_hash = OSHash_Create(); + } + else + { + repeated_hash = NULL; + } + + + /* Main loop. */ while(1) { int timeout_value; int added_before = 0; - + char **timeout_args; timeout_data *timeout_entry; @@ -289,6 +304,7 @@ void ExecdStart(int q) if (wp < 0) { merror(WAITPID_ERROR, ARGV0); + break; } /* if = 0, we still need to wait for the child process */ @@ -315,13 +331,13 @@ void ExecdStart(int q) timeout_data *list_entry; list_entry = (timeout_data *)timeout_node->data; - + /* Timeouted */ - if((curr_time - list_entry->time_of_addition) > + if((curr_time - list_entry->time_of_addition) > list_entry->time_to_block) { ExecCmd(list_entry->command); - + /* Deletecurrently node already sets the pointer to next */ OSList_DeleteCurrentlyNode(timeout_list); timeout_node = OSList_GetCurrentlyNode(timeout_list); @@ -338,7 +354,7 @@ void ExecdStart(int q) } } - + /* Setting timeout to EXECD_TIMEOUT */ socket_timeout.tv_sec = EXECD_TIMEOUT; socket_timeout.tv_usec= 0; @@ -379,8 +395,8 @@ void ExecdStart(int q) /* Getting application name */ name = buffer; - - + + /* Zeroing the name */ tmp_msg = strchr(buffer, ' '); if(!tmp_msg) @@ -413,10 +429,10 @@ void ExecdStart(int q) /* Allocating memory for the timeout argument */ os_calloc(MAX_ARGS+2, sizeof(char *), timeout_args); - + /* Adding initial variables to the cmd_arg and to the timeout cmd */ - cmd_args[0] = command; + cmd_args[0] = command; cmd_args[1] = ADD_ENTRY; os_strdup(command, timeout_args[0]); os_strdup(DELETE_ENTRY, timeout_args[1]); @@ -447,7 +463,7 @@ void ExecdStart(int q) i++; } - + /* Check this command was already executed. */ timeout_node = OSList_GetFirstNode(timeout_list); @@ -460,14 +476,16 @@ void ExecdStart(int q) added_before = 1; merror("%s: Invalid number of arguments.", ARGV0); } - + + + while(timeout_node) { timeout_data *list_entry; list_entry = (timeout_data *)timeout_node->data; if((strcmp(list_entry->command[3], timeout_args[3]) == 0) && - (strcmp(list_entry->command[0], timeout_args[0]) == 0)) + (strcmp(list_entry->command[0], timeout_args[0]) == 0)) { /* Means we executed this command before * and we don't need to add it again. @@ -477,6 +495,42 @@ void ExecdStart(int q) /* updating the timeout */ list_entry->time_of_addition = curr_time; + + if(repeated_offenders_timeout[0] != 0 && + repeated_hash != NULL && + strncmp(timeout_args[3],"-", 1) != 0) + { + char *ntimes = NULL; + char rkey[256]; + rkey[255] = '\0'; + snprintf(rkey, 255, "%s%s", list_entry->command[0], + timeout_args[3]); + + if((ntimes = OSHash_Get(repeated_hash, rkey))) + { + int ntimes_int = 0; + int i2 = 0; + int new_timeout = 0; + ntimes_int = atoi(ntimes); + while(repeated_offenders_timeout[i2] != 0) + { + i2++; + } + if(ntimes_int >= i2) + { + new_timeout = repeated_offenders_timeout[i2 - 1]*60; + } + else + { + os_calloc(10, sizeof(char), ntimes); + new_timeout = repeated_offenders_timeout[ntimes_int]*60; + ntimes_int++; + snprintf(ntimes, 9, "%d", ntimes_int); + OSHash_Update(repeated_hash,rkey,ntimes); + } + list_entry->time_to_block = new_timeout; + } + } break; } @@ -494,6 +548,48 @@ void ExecdStart(int q) /* We don't need to add to the list if the timeout_value == 0 */ if(timeout_value) { + char *ntimes; + char rkey[256]; + rkey[255] = '\0'; + snprintf(rkey, 255, "%s%s", timeout_args[0], + timeout_args[3]); + + if(repeated_hash != NULL) + { + if((ntimes = OSHash_Get(repeated_hash, rkey))) + { + int ntimes_int = 0; + int i2 = 0; + int new_timeout = 0; + + ntimes_int = atoi(ntimes); + while(repeated_offenders_timeout[i2] != 0) + { + i2++; + } + if(ntimes_int >= i2) + { + new_timeout = repeated_offenders_timeout[i2 - 1]*60; + } + else + { + os_calloc(10, sizeof(char), ntimes); + new_timeout = repeated_offenders_timeout[ntimes_int]*60; + ntimes_int++; + snprintf(ntimes, 9, "%d", ntimes_int); + OSHash_Update(repeated_hash, rkey, ntimes); + } + timeout_value = new_timeout; + } + else + { + /* Adding to the repeated offenders list. */ + OSHash_Add(repeated_hash, + strdup(rkey),strdup("0")); + } + } + + /* Creating the timeout entry */ os_calloc(1, sizeof(timeout_data), timeout_entry); timeout_entry->command = timeout_args; @@ -506,9 +602,9 @@ void ExecdStart(int q) { merror(LIST_ADD_ERROR, ARGV0); FreeTimeoutEntry(timeout_entry); - } + } } - + /* If no timeout, we still need to free it in here */ else { @@ -524,7 +620,7 @@ void ExecdStart(int q) childcount++; } - + /* We didn't add it to the timeout list */ else { diff --git a/src/os_execd/execd.h b/src/os_execd/execd.h index ddc20fa..3eedd30 100755 --- a/src/os_execd/execd.h +++ b/src/os_execd/execd.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_execd/execd.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -14,6 +15,7 @@ #ifndef _EXECD_H +#define _EXECD_H #ifndef ARGV0 #define ARGV0 "ossec-execd" @@ -30,7 +32,7 @@ /* Maximum number of command arguments */ -#define MAX_ARGS 32 +#define MAX_ARGS 32 /* Execd select timeout -- in seconds */ @@ -62,6 +64,7 @@ void FreeTimeoutEntry(void *timeout_entry); + #define _EXECD_H #endif diff --git a/src/os_execd/win_execd.c b/src/os_execd/win_execd.c index c3203af..1af0f1b 100755 --- a/src/os_execd/win_execd.c +++ b/src/os_execd/win_execd.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_execd/win_execd.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -23,9 +24,9 @@ #ifdef ARGV0 #undef ARGV0 #endif - + #define ARGV0 "ossec-execd" - + @@ -41,7 +42,7 @@ typedef struct _timeout_data /* Timeout list */ OSList *timeout_list; OSListNode *timeout_node; - + @@ -66,15 +67,15 @@ int WinExecd_Start() /* Exit if test_config */ if(test_config) return(0); - - + + /* Active response disabled */ if(c == 1) { verbose(EXEC_DISABLED, ARGV0); return(0); } - + /* Creating list for timeout */ timeout_list = OSList_Create(); @@ -82,12 +83,12 @@ int WinExecd_Start() { ErrorExit(LIST_ERROR, ARGV0); } - - + + /* Start up message */ verbose(STARTUP_MSG, ARGV0, getpid()); - + return(1); } @@ -105,7 +106,7 @@ void WinTimeoutRun(int curr_time) list_entry = (timeout_data *)timeout_node->data; /* Timeouted */ - if((curr_time - list_entry->time_of_addition) > + if((curr_time - list_entry->time_of_addition) > list_entry->time_to_block) { ExecCmd_Win32(list_entry->command[0]); @@ -146,7 +147,7 @@ void WinExecdRun(char *exec_msg) char *cmd_user; char *cmd_ip; char buffer[OS_MAXSTR + 1]; - + timeout_data *timeout_entry; @@ -194,7 +195,7 @@ void WinExecdRun(char *exec_msg) } *tmp_msg = '\0'; tmp_msg++; - + /* Getting the command to execute (valid name) */ command = GetCommandbyName(name, &timeout_value); @@ -220,11 +221,11 @@ void WinExecdRun(char *exec_msg) /* Adding initial variables to the timeout cmd */ - snprintf(buffer, OS_MAXSTR, "\"%s\" %s \"%s\" \"%s\" \"%s\"", - command, DELETE_ENTRY, cmd_user, cmd_ip, tmp_msg); + snprintf(buffer, OS_MAXSTR, "\"%s\" %s \"%s\" \"%s\" \"%s\"", + command, DELETE_ENTRY, cmd_user, cmd_ip, tmp_msg); os_strdup(buffer, timeout_args[0]); timeout_args[1] = NULL; - + /* Getting size for the strncmp */ @@ -233,12 +234,12 @@ void WinExecdRun(char *exec_msg) { if(buffer[i] == ' ') j++; - + i++; if(j == 4) break; } - + /* Check this command was already executed. */ timeout_node = OSList_GetFirstNode(timeout_list); @@ -271,7 +272,7 @@ void WinExecdRun(char *exec_msg) /* If it wasn't added before, do it now */ if(!added_before) { - snprintf(buffer, OS_MAXSTR, "\"%s\" %s \"%s\" \"%s\" \"%s\"", command, + snprintf(buffer, OS_MAXSTR, "\"%s\" %s \"%s\" \"%s\" \"%s\"", command, ADD_ENTRY, cmd_user, cmd_ip, tmp_msg); /* executing command */ @@ -292,7 +293,7 @@ void WinExecdRun(char *exec_msg) { merror(LIST_ADD_ERROR, ARGV0); FreeTimeoutEntry(timeout_entry); - } + } } /* If no timeout, we still need to free it in here */ diff --git a/src/os_maild/config.c b/src/os_maild/config.c index 311a87e..a3a20f3 100755 --- a/src/os_maild/config.c +++ b/src/os_maild/config.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_maild/config.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -39,6 +40,9 @@ int MailConf(int test_config, char *cfgfile, MailConfig *Mail) Mail->gran_format = NULL; Mail->groupping = 1; Mail->strict_checking = 0; +#ifdef GEOIP + Mail->geoip = 0; +#endif if(ReadConfig(modules, cfgfile, NULL, Mail) < 0) return(OS_INVALID); @@ -49,7 +53,7 @@ int MailConf(int test_config, char *cfgfile, MailConfig *Mail) { verbose(MAIL_DIS, ARGV0); } - exit(0); + exit(0); } return(0); diff --git a/src/os_maild/mail_list.c b/src/os_maild/mail_list.c index 1e70a9e..b96c8ef 100755 --- a/src/os_maild/mail_list.c +++ b/src/os_maild/mail_list.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_maild/mail_list.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -9,7 +10,7 @@ * Foundation */ - + #include #include #include @@ -35,7 +36,7 @@ void OS_CreateMailList(int maxsize) _memorymaxsize = maxsize; _memoryused = 0; - + return; } @@ -58,13 +59,13 @@ MailNode *OS_PopLastMail() n_node = NULL; return(NULL); } - + _memoryused--; - + lastnode = lastnode->prev; /* Remove the last */ - return(oldlast); + return(oldlast); } @@ -72,14 +73,14 @@ void FreeMailMsg(MailMsg *ml) { if(ml == NULL) return; - + if(ml->subject) free(ml->subject); - + if(ml->body) free(ml->body); - - free(ml); + + free(ml); } @@ -90,11 +91,11 @@ void FreeMail(MailNode *ml) return; if(ml->mail->subject) free(ml->mail->subject); - + if(ml->mail->body) free(ml->mail->body); - free(ml->mail); + free(ml->mail); free(ml); } @@ -103,32 +104,32 @@ void FreeMail(MailNode *ml) void OS_AddMailtoList(MailMsg *ml) { MailNode *tmp_node = n_node; - + if(tmp_node) { MailNode *new_node; new_node = (MailNode *)calloc(1,sizeof(MailNode)); - + if(new_node == NULL) { ErrorExit(MEM_ERROR,ARGV0); } - /* Always adding to the beginning of the list + /* Always adding to the beginning of the list * The new node will become the first node and * new_node->next will be the previous first node */ new_node->next = tmp_node; new_node->prev = NULL; tmp_node->prev = new_node; - + n_node = new_node; /* Adding the event to the node */ new_node->mail = ml; _memoryused++; - + /* Need to remove the last node */ if(_memoryused > _memorymaxsize) { @@ -136,14 +137,14 @@ void OS_AddMailtoList(MailMsg *ml) oldlast = lastnode; lastnode = lastnode->prev; - + /* free last node */ FreeMail(oldlast); - + _memoryused--; } } - + else { /* Adding first node */ @@ -156,8 +157,8 @@ void OS_AddMailtoList(MailMsg *ml) n_node->prev = NULL; n_node->next = NULL; n_node->mail = ml; - - lastnode = n_node; + + lastnode = n_node; } return; diff --git a/src/os_maild/mail_list.h b/src/os_maild/mail_list.h index fde0381..6d2587a 100755 --- a/src/os_maild/mail_list.h +++ b/src/os_maild/mail_list.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_maild/mail_list.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,8 +9,8 @@ * License (version 2) as published by the FSF - Free Software * Foundation */ - - + + #ifndef _MAILIST__H #define _MAILIST__H @@ -26,7 +27,7 @@ typedef struct _MailNode /* Add an email to the list */ void OS_AddMailtoList(MailMsg *ml); -/* Return the last event from the Event list +/* Return the last event from the Event list * removing it from there */ MailNode *OS_PopLastMail(); diff --git a/src/os_maild/maild.c b/src/os_maild/maild.c index 0f6501a..15bfc30 100755 --- a/src/os_maild/maild.c +++ b/src/os_maild/maild.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_maild/maild.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -25,7 +26,6 @@ #include "maild.h" #include "mail_list.h" - void OS_Run(MailConfig *mail); int main(int argc, char **argv) @@ -43,7 +43,7 @@ int main(int argc, char **argv) /* Setting the name */ OS_SetName(ARGV0); - + while((c = getopt(argc, argv, "Vdhtfu:g:D:c:")) != -1){ switch(c){ @@ -73,13 +73,14 @@ int main(int argc, char **argv) if(!optarg) ErrorExit("%s: -D needs an argument",ARGV0); dir=optarg; + break; case 'c': if(!optarg) ErrorExit("%s: -c needs an argument",ARGV0); cfg = optarg; break; case 't': - test_config = 1; + test_config = 1; break; default: help(ARGV0); @@ -97,7 +98,6 @@ int main(int argc, char **argv) if((uid < 0)||(gid < 0)) ErrorExit(USER_ERROR,ARGV0,user,group); - /* Reading configuration */ if(MailConf(test_config, cfg, &mail) < 0) ErrorExit(CONFIG_ERROR, ARGV0, cfg); @@ -107,35 +107,42 @@ int main(int argc, char **argv) mail.strict_checking = getDefine_Int("maild", "strict_checking", 0, 1); - + /* Get groupping */ mail.groupping = getDefine_Int("maild", "groupping", 0, 1); - + /* Getting subject type */ mail.subject_full = getDefine_Int("maild", "full_subject", 0, 1); - - + +#ifdef GEOIP + /* Get GeoIP */ + mail.geoip = getDefine_Int("maild", + "geoip", + 0, 1); +#endif + + /* Exit here if test config is set */ if(test_config) exit(0); - - if(!run_foreground) + + if(!run_foreground) { nowDaemon(); goDaemon(); } - + /* Privilege separation */ if(Privsep_SetGroup(gid) < 0) ErrorExit(SETGID_ERROR,ARGV0,group); - + /* chrooting */ if(Privsep_Chroot(dir) < 0) ErrorExit(CHROOT_ERROR,ARGV0,dir); @@ -143,8 +150,8 @@ int main(int argc, char **argv) nowChroot(); - - /* Changing user */ + + /* Changing user */ if(Privsep_SetUser(uid) < 0) ErrorExit(SETUID_ERROR,ARGV0,user); @@ -156,16 +163,16 @@ int main(int argc, char **argv) /* Signal manipulation */ StartSIG(ARGV0); - + /* Creating PID files */ if(CreatePID(ARGV0, getpid()) < 0) ErrorExit(PID_ERROR, ARGV0); - + /* Start up message */ verbose(STARTUP_MSG, ARGV0, (int)getpid()); - + /* the real daemon now */ OS_Run(&mail); @@ -182,13 +189,13 @@ void OS_Run(MailConfig *mail) MailMsg *s_msg = NULL; MailMsg *msg_sms = NULL; - time_t tm; - struct tm *p; + time_t tm; + struct tm *p; int i = 0; int mailtosend = 0; int childcount = 0; - int today = 0; + int today = 0; int thishour = 0; int n_errs = 0; @@ -211,13 +218,13 @@ void OS_Run(MailConfig *mail) /* Creating the list */ - OS_CreateMailList(MAIL_LIST_SIZE); - - + OS_CreateMailList(MAIL_LIST_SIZE); + + /* Setting default timeout */ mail_timeout = DEFAULT_TIMEOUT; - + /* Clearing global vars */ _g_subject_level = 0; memset(_g_subject, '\0', SUBJECT_SIZE +2); @@ -228,14 +235,14 @@ void OS_Run(MailConfig *mail) tm = time(NULL); p = localtime(&tm); - + /* SMS messages are sent without delay */ if(msg_sms) { pid_t pid; - + pid = fork(); - + if(pid < 0) { merror("%s: Fork failed. cause: %d - %s", ARGV0, errno, strerror(errno)); @@ -260,7 +267,7 @@ void OS_Run(MailConfig *mail) /* Increasing child count */ childcount++; } - + /* If mail_timeout == NEXTMAIL_TIMEOUT, we will try to get * more messages, before sending anything @@ -269,9 +276,9 @@ void OS_Run(MailConfig *mail) { /* getting more messages */ } - - - /* Hour changed. Send all supressed mails */ + + + /* Hour changed. Send all supressed mails */ else if(((mailtosend < mail->maxperhour) && (mailtosend != 0))|| ((p->tm_hour != thishour) && (childcount < MAXCHILDPROCESS))) { @@ -298,29 +305,29 @@ void OS_Run(MailConfig *mail) { if(OS_Sendmail(mail, p) < 0) merror(SNDMAIL_ERROR,ARGV0,mail->smtpserver); - - exit(0); + + exit(0); } - + /* Cleaning the memory */ - mailmsg = OS_PopLastMail(); + mailmsg = OS_PopLastMail(); do { - FreeMail(mailmsg); + FreeMail(mailmsg); mailmsg = OS_PopLastMail(); }while(mailmsg); - - - /* Increasing child count */ - childcount++; + + + /* Increasing child count */ + childcount++; /* Clearing global vars */ _g_subject[0] = '\0'; _g_subject[SUBJECT_SIZE -1] = '\0'; _g_subject_level = 0; - - + + /* Cleaning up set values */ if(mail->gran_to) { @@ -343,12 +350,12 @@ void OS_Run(MailConfig *mail) /* If we sent everything */ if(p->tm_hour != thishour) { - thishour = p->tm_hour; + thishour = p->tm_hour; mailtosend = 0; } } - + /* Saved message for the do_not_group option. */ if(s_msg) @@ -368,15 +375,15 @@ void OS_Run(MailConfig *mail) i++; } } - + OS_AddMailtoList(s_msg); s_msg = NULL; mailtosend++; continue; } - - + + /* Receive message from queue */ if((msg = OS_RecvMailQ(fileq, p, mail, &msg_sms)) != NULL) { @@ -393,7 +400,7 @@ void OS_Run(MailConfig *mail) { OS_AddMailtoList(msg); } - + /* Change timeout to see if any new message is coming shortly */ if(mail->groupping) @@ -436,24 +443,25 @@ void OS_Run(MailConfig *mail) /* Waiting for the childs .. */ - while (childcount) + while (childcount) { int wp; int p_status; wp = waitpid((pid_t) -1, &p_status, WNOHANG); if (wp < 0) { - merror(WAITPID_ERROR, ARGV0); + merror(WAITPID_ERROR, ARGV0); n_errs++; } - /* if = 0, we still need to wait for the child process */ - else if (wp == 0) + /* if = 0, we still need to wait for the child process */ + else if (wp == 0) break; else { if(p_status != 0) { + merror(CHLDWAIT_ERROR,ARGV0,p_status); merror(SNDMAIL_ERROR,ARGV0,mail->smtpserver); n_errs++; } @@ -463,11 +471,12 @@ void OS_Run(MailConfig *mail) /* Too many errors */ if(n_errs > 6) { + merror(TOOMANY_WAIT_ERROR,ARGV0); merror(SNDMAIL_ERROR,ARGV0,mail->smtpserver); exit(1); } } - + } } diff --git a/src/os_maild/maild.h b/src/os_maild/maild.h index e11a48d..efa09fd 100755 --- a/src/os_maild/maild.h +++ b/src/os_maild/maild.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_maild/maild.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -21,7 +22,7 @@ /* Each timeout is x * 5 */ #define NEXTMAIL_TIMEOUT 2 /* Time to check for next msg - 5 */ -#define DEFAULT_TIMEOUT 18 /* socket read timeout - 18 (*5)*/ +#define DEFAULT_TIMEOUT 18 /* socket read timeout - 18 (*5)*/ #define SUBJECT_SIZE 128 /* Maximum subject size */ /* Maximum body size */ @@ -36,13 +37,23 @@ #define MAIL_SUBJECT_FULL2 "%d - %s - %s" #endif +#ifdef GEOIP #define MAIL_BODY "\r\nOSSEC HIDS Notification.\r\n" \ "%s\r\n\r\n" \ "Received From: %s\r\n" \ "Rule: %d fired (level %d) -> \"%s\"\r\n" \ + "%s" \ + "%s" \ "Portion of the log(s):\r\n\r\n%s\r\n" \ "\r\n\r\n --END OF NOTIFICATION\r\n\r\n\r\n" - +#else +#define MAIL_BODY "\r\nOSSEC HIDS Notification.\r\n" \ + "%s\r\n\r\n" \ + "Received From: %s\r\n" \ + "Rule: %d fired (level %d) -> \"%s\"\r\n" \ + "Portion of the log(s):\r\n\r\n%s\r\n" \ + "\r\n\r\n --END OF NOTIFICATION\r\n\r\n\r\n" +#endif /* Mail msg structure */ typedef struct _MailMsg @@ -55,7 +66,7 @@ typedef struct _MailMsg #include "config/mail-config.h" -/* Config function */ +/* Config function */ int MailConf(int test_config, char *cfgfile, MailConfig *Mail); diff --git a/src/os_maild/os_maild_client.c b/src/os_maild/os_maild_client.c index 99a1fb7..641b0cd 100755 --- a/src/os_maild/os_maild_client.c +++ b/src/os_maild/os_maild_client.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_maild/os_maild_client.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -13,19 +14,27 @@ #include "shared.h" #include "maild.h" +/* GeoIP Stuff */ +#ifdef GEOIP +#include "config/config.h" +#endif -/* OS_RecvMailQ, +/* OS_RecvMailQ, * v0.1, 2005/03/15 * Receive a Message on the Mail queue * v0,2: Using the new file-queue. */ -MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, +MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, MailConfig *Mail, MailMsg **msg_sms) { int i = 0, body_size = OS_MAXSTR -3, log_size, sms_set = 0,donotgroup = 0; char logs[OS_MAXSTR + 1]; char *subject_host; - +#ifdef GEOIP + char geoip_msg_src[OS_SIZE_1024 +1]; + char geoip_msg_dst[OS_SIZE_1024 +1]; +#endif + MailMsg *mail; alert_data *al_data; @@ -47,23 +56,68 @@ MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, /* Generating the logs */ logs[0] = '\0'; logs[OS_MAXSTR] = '\0'; - + while(al_data->log[i]) { log_size = strlen(al_data->log[i]) + 4; - + /* If size left is small than the size of the log, stop it */ if(body_size <= log_size) { break; } - + strncat(logs, al_data->log[i], body_size); strncat(logs, "\r\n", body_size); body_size -= log_size; i++; } + if (al_data->old_md5) + { + log_size = strlen(al_data->old_md5) + 16 + 4; + if(body_size > log_size) + { + strncat(logs, "Old md5sum was: ", 16); + strncat(logs, al_data->old_md5, body_size); + strncat(logs, "\r\n", 4); + body_size -= log_size; + } + } + if (al_data->new_md5) + { + log_size = strlen(al_data->new_md5) + 16 + 4; + if(body_size > log_size) + { + strncat(logs, "New md5sum is : ", 16); + strncat(logs, al_data->new_md5, body_size); + strncat(logs, "\r\n", 4); + body_size -= log_size; + } + } + if (al_data->old_sha1) + { + log_size = strlen(al_data->old_sha1) + 17 + 4; + if(body_size > log_size) + { + strncat(logs, "Old sha1sum was: ", 17); + strncat(logs, al_data->old_sha1, body_size); + strncat(logs, "\r\n", 4); + body_size -= log_size; + } + } + if (al_data->new_sha1) + { + log_size = strlen(al_data->new_sha1) + 17 + 4; + if(body_size > log_size) + { + strncat(logs, "New sha1sum is : ", 17); + strncat(logs, al_data->new_sha1, body_size); + strncat(logs, "\r\n", 4); + body_size -= log_size; + } + } + /* Subject */ subject_host = strchr(al_data->location, '>'); @@ -78,12 +132,12 @@ MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, { /* Option for a clean full subject (without ossec in the name) */ #ifdef CLEANFULL - snprintf(mail->subject, SUBJECT_SIZE -1, MAIL_SUBJECT_FULL2, + snprintf(mail->subject, SUBJECT_SIZE -1, MAIL_SUBJECT_FULL2, al_data->level, al_data->comment, al_data->location); #else - snprintf(mail->subject, SUBJECT_SIZE -1, MAIL_SUBJECT_FULL, + snprintf(mail->subject, SUBJECT_SIZE -1, MAIL_SUBJECT_FULL, al_data->location, al_data->level, al_data->comment); @@ -91,28 +145,59 @@ MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, } else { - snprintf(mail->subject, SUBJECT_SIZE -1, MAIL_SUBJECT, + snprintf(mail->subject, SUBJECT_SIZE -1, MAIL_SUBJECT, al_data->location, al_data->level); } - + /* fixing subject back */ if(subject_host) { *subject_host = '-'; } - +#ifdef GEOIP + /* Get GeoIP information */ + if (Mail->geoip) { + if (al_data->geoipdatasrc) { + snprintf(geoip_msg_src, OS_SIZE_1024, "Src Location: %s\r\n", al_data->geoipdatasrc); + } else { + geoip_msg_src[0] = '\0'; + } + if (al_data->geoipdatadst) { + snprintf(geoip_msg_dst, OS_SIZE_1024, "Dst Location: %s\r\n", al_data->geoipdatadst); + } else { + geoip_msg_dst[0] = '\0'; + } + } + else { + geoip_msg_src[0] = '\0'; + geoip_msg_dst[0] = '\0'; + } +#endif + /* Body */ +#ifdef GEOIP snprintf(mail->body, BODY_SIZE -1, MAIL_BODY, al_data->date, al_data->location, al_data->rule, al_data->level, al_data->comment, + geoip_msg_src, + geoip_msg_dst, logs); - +#else + snprintf(mail->body, BODY_SIZE -1, MAIL_BODY, + al_data->date, + al_data->location, + al_data->rule, + al_data->level, + al_data->comment, + logs); +#endif + debug2("OS_RecvMailQ: mail->body[%s]", mail->body); /* Checking for granular email configs */ if(Mail->gran_to) @@ -121,7 +206,7 @@ MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, while(Mail->gran_to[i] != NULL) { int gr_set = 0; - + /* Looking if location is set */ if(Mail->gran_location[i]) { @@ -137,7 +222,7 @@ MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, continue; } } - + /* Looking for the level */ if(Mail->gran_level[i]) { @@ -177,7 +262,7 @@ MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, continue; } } - + /* Looking for the group */ if(Mail->gran_group[i]) @@ -251,13 +336,13 @@ MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, _g_subject_level = al_data->level; } } - - + + /* If sms is set, create the sms output */ if(sms_set) { MailMsg *msg_sms_tmp; - + /* Allocate memory for sms */ os_calloc(1,sizeof(MailMsg), msg_sms_tmp); os_calloc(BODY_SIZE, sizeof(char), msg_sms_tmp->body); @@ -271,17 +356,17 @@ MailMsg *OS_RecvMailQ(file_queue *fileq, struct tm *p, strncpy(msg_sms_tmp->body, logs, 128); msg_sms_tmp->body[127] = '\0'; - + /* Assigning msg_sms */ *msg_sms = msg_sms_tmp; } - - - + + + /* Clearing the memory */ FreeAlertData(al_data); - + return(mail); } diff --git a/src/os_maild/sendcustomemail.c b/src/os_maild/sendcustomemail.c index ea2b203..a597fcc 100755 --- a/src/os_maild/sendcustomemail.c +++ b/src/os_maild/sendcustomemail.c @@ -1,11 +1,12 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_maild/sendcustomemail.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * * This program is a free software; you can redistribute it * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software + * License (version 2) as published by the FSF - Free Software * Foundation */ @@ -67,7 +68,7 @@ int OS_SendCustomEmail(char **to, char *subject, char *smtpserver, char *from, F /* Connecting to the smtp server */ - socket = OS_ConnectTCP(SMTP_DEFAULT_PORT, smtpserver); + socket = OS_ConnectTCP(SMTP_DEFAULT_PORT, smtpserver, 0); if(socket < 0) { return(socket); @@ -112,7 +113,7 @@ int OS_SendCustomEmail(char **to, char *subject, char *smtpserver, char *from, F if(msg) free(msg); close(socket); - return(OS_INVALID); + return(OS_INVALID); } } else @@ -209,7 +210,7 @@ int OS_SendCustomEmail(char **to, char *subject, char *smtpserver, char *from, F { break; } - + memset(snd_msg,'\0',128); snprintf(snd_msg,127, TO, to[i]); OS_SendTCP(socket,snd_msg); @@ -229,7 +230,7 @@ int OS_SendCustomEmail(char **to, char *subject, char *smtpserver, char *from, F #else strftime(snd_msg, 127, "Date: %a, %d %b %Y %T %z\r\n",p); #endif - + OS_SendTCP(socket,snd_msg); @@ -246,7 +247,7 @@ int OS_SendCustomEmail(char **to, char *subject, char *smtpserver, char *from, F while(fgets(buffer, 2048, fp) != NULL) { OS_SendTCP(socket,buffer); - } + } /* Sending end of data \r\n.\r\n */ diff --git a/src/os_maild/sendmail.c b/src/os_maild/sendmail.c index 92157a7..5b0fd6f 100755 --- a/src/os_maild/sendmail.c +++ b/src/os_maild/sendmail.c @@ -1,11 +1,12 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_maild/sendmail.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * * This program is a free software; you can redistribute it * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software + * License (version 2) as published by the FSF - Free Software * Foundation */ @@ -64,7 +65,7 @@ int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg) /* Connecting to the smtp server */ - socket = OS_ConnectTCP(SMTP_DEFAULT_PORT, mail->smtpserver); + socket = OS_ConnectTCP(SMTP_DEFAULT_PORT, mail->smtpserver, 0); if(socket < 0) { return(socket); @@ -109,7 +110,7 @@ int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg) if(msg) free(msg); close(socket); - return(OS_INVALID); + return(OS_INVALID); } } else @@ -152,7 +153,7 @@ int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg) /* Additional RCPT to */ final_to[0] = '\0'; final_to_sz = sizeof(final_to) -2; - + if(mail->gran_to) { i = 0; @@ -185,7 +186,7 @@ int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg) snprintf(snd_msg,127, TO, mail->gran_to[i]); strncat(final_to, snd_msg, final_to_sz); final_to_sz -= strlen(snd_msg) +2; - + i++; continue; } @@ -218,7 +219,7 @@ int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg) /* Sending date */ memset(snd_msg,'\0',128); - + /* Solaris doesn't have the "%z", so we set the timezone to 0. */ #ifdef SOLARIS @@ -226,7 +227,7 @@ int OS_Sendsms(MailConfig *mail, struct tm *p, MailMsg *sms_msg) #else strftime(snd_msg, 127, "Date: %a, %d %b %Y %T %z\r\n",p); #endif - + OS_SendTCP(socket,snd_msg); @@ -287,7 +288,7 @@ int OS_Sendmail(MailConfig *mail, struct tm *p) MailNode *mailmsg; additional_to[0] = '\0'; - + /* If there is no sms message, we attempt to get from the * email list. */ @@ -297,10 +298,10 @@ int OS_Sendmail(MailConfig *mail, struct tm *p) { merror("%s: No email to be sent. Inconsistent state.",ARGV0); } - + /* Connecting to the smtp server */ - socket = OS_ConnectTCP(SMTP_DEFAULT_PORT, mail->smtpserver); + socket = OS_ConnectTCP(SMTP_DEFAULT_PORT, mail->smtpserver, 0); if(socket < 0) { return(socket); @@ -345,7 +346,7 @@ int OS_Sendmail(MailConfig *mail, struct tm *p) if(msg) free(msg); close(socket); - return(OS_INVALID); + return(OS_INVALID); } } else @@ -438,9 +439,9 @@ int OS_Sendmail(MailConfig *mail, struct tm *p) free(msg); i++; - continue; + continue; } - + MAIL_DEBUG("DEBUG: Sent '%s', received: '%s'", snd_msg, msg); free(msg); i++; @@ -484,7 +485,7 @@ int OS_Sendmail(MailConfig *mail, struct tm *p) { break; } - + memset(snd_msg,'\0',128); snprintf(snd_msg,127, TO, mail->to[i]); OS_SendTCP(socket,snd_msg); @@ -525,7 +526,7 @@ int OS_Sendmail(MailConfig *mail, struct tm *p) #else strftime(snd_msg, 127, "Date: %a, %d %b %Y %T %z\r\n",p); #endif - + OS_SendTCP(socket,snd_msg); diff --git a/src/os_net/os_err.h b/src/os_net/os_err.h index 85a2798..78fcb92 100755 --- a/src/os_net/os_err.h +++ b/src/os_net/os_err.h @@ -1,11 +1,12 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_net/os_err.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. * * This program is a free software; you can redistribute it * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software + * License (version 2) as published by the FSF - Free Software * Foundation */ diff --git a/src/os_net/os_net.c b/src/os_net/os_net.c index 1921609..c282b9f 100755 --- a/src/os_net/os_net.c +++ b/src/os_net/os_net.c @@ -1,30 +1,29 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_net/os_net.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. * * This program is a free software; you can redistribute it * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software + * License (version 2) as published by the FSF - Free Software * Foundation * * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ -/* OS_net Library. +/* OS_net Library. * APIs for many network operations. */ - - + + #include "shared.h" #include "os_net.h" -struct sockaddr_in _c; /* Client socket */ -socklen_t _cl; /* Client socket length */ /* Unix socket -- not for windows */ @@ -47,15 +46,21 @@ int ENOBUFS = 0; * Bind a specific port * v0.2: Added REUSEADDR. */ -int OS_Bindport(unsigned int _port, unsigned int _proto, char *_ip) +int OS_Bindport(unsigned int _port, unsigned int _proto, char *_ip, int ipv6) { int ossock; struct sockaddr_in server; - + #ifndef WIN32 + struct sockaddr_in6 server6; + #else + ipv6 = 0; + #endif + + if(_proto == IPPROTO_UDP) { - if((ossock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) + if((ossock = socket(ipv6 == 1?PF_INET6:PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) { return OS_SOCKTERR; } @@ -63,12 +68,12 @@ int OS_Bindport(unsigned int _port, unsigned int _proto, char *_ip) else if(_proto == IPPROTO_TCP) { int flag = 1; - if((ossock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) + if((ossock = socket(ipv6 == 1?PF_INET6:PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { return(int)(OS_SOCKTERR); } - - if(setsockopt(ossock, SOL_SOCKET, SO_REUSEADDR, + + if(setsockopt(ossock, SOL_SOCKET, SO_REUSEADDR, (char *)&flag, sizeof(flag)) < 0) { return(OS_SOCKTERR); @@ -79,20 +84,42 @@ int OS_Bindport(unsigned int _port, unsigned int _proto, char *_ip) return(OS_INVALID); } - memset(&server, 0, sizeof(server)); - server.sin_family = AF_INET; - server.sin_port = htons( _port ); + if(ipv6) + { + #ifndef WIN32 + memset(&server6, 0, sizeof(server6)); + server6.sin6_family = AF_INET6; + server6.sin6_port = htons( _port ); + server6.sin6_addr = in6addr_any; - if((_ip == NULL)||(_ip[0] == '\0')) - server.sin_addr.s_addr = htonl(INADDR_ANY); - else - server.sin_addr.s_addr = inet_addr(_ip); - if(bind(ossock, (struct sockaddr *) &server, sizeof(server)) < 0) + if(bind(ossock, (struct sockaddr *) &server6, sizeof(server6)) < 0) + { + return(OS_SOCKTERR); + } + #endif + } + else { - return(OS_SOCKTERR); + memset(&server, 0, sizeof(server)); + server.sin_family = AF_INET; + server.sin_port = htons( _port ); + + + if((_ip == NULL)||(_ip[0] == '\0')) + server.sin_addr.s_addr = htonl(INADDR_ANY); + else + server.sin_addr.s_addr = inet_addr(_ip); + + + if(bind(ossock, (struct sockaddr *) &server, sizeof(server)) < 0) + { + return(OS_SOCKTERR); + } } + + if(_proto == IPPROTO_TCP) { if(listen(ossock, 32) < 0) @@ -100,9 +127,8 @@ int OS_Bindport(unsigned int _port, unsigned int _proto, char *_ip) return(OS_SOCKTERR); } } - - - _cl = sizeof(_c); + + return(ossock); } @@ -110,18 +136,18 @@ int OS_Bindport(unsigned int _port, unsigned int _proto, char *_ip) /* OS_Bindporttcp v 0.1 * Bind a TCP port, using the OS_Bindport */ -int OS_Bindporttcp(unsigned int _port, char *_ip) +int OS_Bindporttcp(unsigned int _port, char *_ip, int ipv6) { - return(OS_Bindport(_port, IPPROTO_TCP, _ip)); + return(OS_Bindport(_port, IPPROTO_TCP, _ip, ipv6)); } /* OS_Bindportudp v 0.1 * Bind a UDP port, using the OS_Bindport */ -int OS_Bindportudp(unsigned int _port, char *_ip) +int OS_Bindportudp(unsigned int _port, char *_ip, int ipv6) { - return(OS_Bindport(_port, IPPROTO_UDP, _ip)); + return(OS_Bindport(_port, IPPROTO_UDP, _ip, ipv6)); } #ifndef WIN32 @@ -136,7 +162,7 @@ int OS_BindUnixDomain(char * path, int mode, int max_msg_size) /* Making sure the path isn't there */ unlink(path); - + memset(&n_us, 0, sizeof(n_us)); n_us.sun_family = AF_UNIX; strncpy(n_us.sun_path, path, sizeof(n_us.sun_path)-1); @@ -149,23 +175,23 @@ int OS_BindUnixDomain(char * path, int mode, int max_msg_size) close(ossock); return(OS_SOCKTERR); } - + /* Changing permissions */ chmod(path,mode); - - + + /* Getting current maximum size */ if(getsockopt(ossock, SOL_SOCKET, SO_RCVBUF, &len, &optlen) == -1) return(OS_SOCKTERR); - - + + /* Setting socket opt */ if(len < max_msg_size) { len = max_msg_size; setsockopt(ossock, SOL_SOCKET, SO_RCVBUF, &len, optlen); } - + return(ossock); } @@ -209,8 +235,8 @@ int OS_ConnectUnixDomain(char * path, int max_msg_size) len = max_msg_size; setsockopt(ossock, SOL_SOCKET, SO_SNDBUF, &len, optlen); } - - + + /* Returning the socket */ return(ossock); } @@ -224,46 +250,79 @@ int OS_getsocketsize(int ossock) /* Getting current maximum size */ if(getsockopt(ossock, SOL_SOCKET, SO_SNDBUF, &len, &optlen) == -1) return(OS_SOCKTERR); - - return(len); + + return(len); } #endif /* OS_Connect v 0.1, 2004/07/21 - * Open a TCP/UDP client socket + * Open a TCP/UDP client socket */ -int OS_Connect(unsigned int _port, unsigned int protocol, char *_ip) +int OS_Connect(unsigned int _port, unsigned int protocol, char *_ip, int ipv6) { int ossock; struct sockaddr_in server; + #ifndef WIN32 + struct sockaddr_in6 server6; + #else + ipv6 = 0; + #endif + if(protocol == IPPROTO_TCP) { - if((ossock = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP)) < 0) + if((ossock = socket(ipv6 == 1?PF_INET6:PF_INET,SOCK_STREAM,IPPROTO_TCP)) < 0) return(OS_SOCKTERR); } else if(protocol == IPPROTO_UDP) { - if((ossock = socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP)) < 0) + if((ossock = socket(ipv6 == 1?PF_INET6:PF_INET,SOCK_DGRAM,IPPROTO_UDP)) < 0) return(OS_SOCKTERR); } else return(OS_INVALID); - _cl = sizeof(server); - memset(&server, 0, _cl); - server.sin_family = AF_INET; - server.sin_port = htons( _port ); + + #ifdef HPUX + { + int flags; + flags = fcntl(ossock,F_GETFL,0); + fcntl(ossock, F_SETFL, flags | O_NONBLOCK); + } + #endif + + if((_ip == NULL)||(_ip[0] == '\0')) - return(OS_INVALID); + return(OS_INVALID); - server.sin_addr.s_addr = inet_addr(_ip); - if(connect(ossock,(struct sockaddr *)&server, _cl) < 0) - return(OS_SOCKTERR); + if(ipv6 == 1) + { + #ifndef WIN32 + memset(&server6, 0, sizeof(server6)); + server6.sin6_family = AF_INET6; + server6.sin6_port = htons( _port ); + inet_pton(AF_INET6, _ip, &server6.sin6_addr.s6_addr); + + if(connect(ossock,(struct sockaddr *)&server6, sizeof(server6)) < 0) + return(OS_SOCKTERR); + #endif + } + else + { + memset(&server, 0, sizeof(server)); + server.sin_family = AF_INET; + server.sin_port = htons( _port ); + server.sin_addr.s_addr = inet_addr(_ip); + + + if(connect(ossock,(struct sockaddr *)&server, sizeof(server)) < 0) + return(OS_SOCKTERR); + } + return(ossock); } @@ -272,18 +331,18 @@ int OS_Connect(unsigned int _port, unsigned int protocol, char *_ip) /* OS_ConnectTCP, v0.1 * Open a TCP socket */ -int OS_ConnectTCP(unsigned int _port, char *_ip) +int OS_ConnectTCP(unsigned int _port, char *_ip, int ipv6) { - return(OS_Connect(_port, IPPROTO_TCP,_ip)); + return(OS_Connect(_port, IPPROTO_TCP, _ip, ipv6)); } /* OS_ConnectUDP, v0.1 - * Open a UDP socket + * Open a UDP socket */ -int OS_ConnectUDP(unsigned int _port, char *_ip) +int OS_ConnectUDP(unsigned int _port, char *_ip, int ipv6) { - return(OS_Connect(_port, IPPROTO_UDP,_ip)); + return(OS_Connect(_port, IPPROTO_UDP, _ip, ipv6)); } /* OS_SendTCP v0.1, 2004/07/21 @@ -304,7 +363,7 @@ int OS_SendTCPbySize(int socket, int size, char *msg) { if((send(socket, msg, size, 0)) < size) return (OS_SOCKTERR); - + return(0); } @@ -324,11 +383,11 @@ int OS_SendUDPbySize(int socket, int size, char *msg) return(OS_SOCKTERR); } - i++; + i++; merror("%s: INFO: Remote socket busy, waiting %d s.", __local_name, i); - sleep(i); + sleep(i); } - + return(0); } @@ -342,7 +401,7 @@ int OS_AcceptTCP(int socket, char *srcip, int addrsize) int clientsocket; struct sockaddr_in _nc; socklen_t _ncl; - + memset(&_nc, 0, sizeof(_nc)); _ncl = sizeof(_nc); @@ -369,7 +428,7 @@ char *OS_RecvTCP(int socket, int sizet) ret = (char *) calloc((sizet), sizeof(char)); if(ret == NULL) return(NULL); - + if((retsize = recv(socket, ret, sizet-1,0)) <= 0) return(NULL); @@ -406,12 +465,12 @@ int OS_RecvTCPBuffer(int socket, char *buffer, int sizet) char *OS_RecvUDP(int socket, int sizet) { char *ret; - + ret = (char *) calloc((sizet), sizeof(char)); if(ret == NULL) return(NULL); - if((recvfrom(socket,ret,sizet-1,0,(struct sockaddr *)&_c,&_cl))<0) + if((recv(socket,ret,sizet-1,0))<0) return(NULL); return(ret); @@ -428,8 +487,8 @@ int OS_RecvConnUDP(int socket, char *buffer, int buffer_size) recv_b = recv(socket, buffer, buffer_size, 0); if(recv_b < 0) return(0); - - return(recv_b); + + return(recv_b); } @@ -440,7 +499,7 @@ int OS_RecvConnUDP(int socket, char *buffer, int buffer_size) int OS_RecvUnix(int socket, int sizet, char *ret) { ssize_t recvd; - if((recvd = recvfrom(socket, ret, sizet -1, 0, + if((recvd = recvfrom(socket, ret, sizet -1, 0, (struct sockaddr*)&n_us,&us_l)) < 0) return(0); @@ -451,13 +510,13 @@ int OS_RecvUnix(int socket, int sizet, char *ret) /* OS_SendUnix, v0.1, 2004/07/29 * Send a message using a Unix socket. - * Returns the OS_SOCKETERR if it - */ + * Returns the OS_SOCKETERR if it + */ int OS_SendUnix(int socket, char * msg, int size) { if(size == 0) size = strlen(msg)+1; - + if(send(socket, msg, size,0) < size) { if(errno == ENOBUFS) @@ -465,7 +524,7 @@ int OS_SendUnix(int socket, char * msg, int size) return(OS_SOCKTERR); } - + return(OS_SUCCESS); } #endif @@ -478,13 +537,13 @@ char *OS_GetHost(char *host, int attempts) { int i = 0; int sz; - + char *ip; struct hostent *h; if(host == NULL) return(NULL); - + while(i <= attempts) { if((h = gethostbyname(host)) == NULL) diff --git a/src/os_net/os_net.h b/src/os_net/os_net.h index 88c2b80..33d27fb 100755 --- a/src/os_net/os_net.h +++ b/src/os_net/os_net.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_net/os_net.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -23,23 +24,23 @@ * If the IP is not set, it is going to use ADDR_ANY * Return the socket. */ -int OS_Bindporttcp(unsigned int _port, char *_ip); -int OS_Bindportudp(unsigned int _port, char *_ip); +int OS_Bindporttcp(unsigned int _port, char *_ip, int ipv6); +int OS_Bindportudp(unsigned int _port, char *_ip, int ipv6); /* OS_BindUnixDomain * Bind to a specific file, using the "mode" permissions in * a Unix Domain socket. - */ + */ int OS_BindUnixDomain(char * path, int mode, int max_msg_size); -int OS_ConnectUnixDomain(char * path, int max_msg_size); +int OS_ConnectUnixDomain(char * path, int max_msg_size); int OS_getsocketsize(int ossock); /* OS_Connect * Connect to a TCP/UDP socket */ -int OS_ConnectTCP(unsigned int _port, char *_ip); -int OS_ConnectUDP(unsigned int _port, char *_ip); +int OS_ConnectTCP(unsigned int _port, char *_ip, int ipv6); +int OS_ConnectUDP(unsigned int _port, char *_ip, int ipv6); /* OS_RecvUDP * Receive a UDP packet. Return NULL if failed @@ -51,7 +52,7 @@ int OS_RecvConnUDP(int socket, char *buffer, int buffer_size); /* OS_RecvUnix * Receive a message via a Unix socket */ -int OS_RecvUnix(int socket, int sizet, char *ret); +int OS_RecvUnix(int socket, int sizet, char *ret); /* OS_RecvTCP @@ -60,9 +61,9 @@ int OS_RecvUnix(int socket, int sizet, char *ret); int OS_AcceptTCP(int socket, char *srcip, int addrsize); char *OS_RecvTCP(int socket, int sizet); int OS_RecvTCPBuffer(int socket, char *buffer, int sizet); - -/* OS_SendTCP + +/* OS_SendTCP * Send a TCP/UDP/UnixSocket packet (in a open socket) */ int OS_SendTCP(int socket, char *msg); @@ -72,7 +73,7 @@ int OS_SendUnix(int socket, char * msg, int size); int OS_SendUDP(int socket, char *msg); int OS_SendUDPbySize(int socket, int size, char *msg); - + /* OS_GetHost * Calls gethostbyname diff --git a/src/os_regex/examples/match.c b/src/os_regex/examples/match.c index d63ffe7..2579dd1 100755 --- a/src/os_regex/examples/match.c +++ b/src/os_regex/examples/match.c @@ -2,7 +2,7 @@ * Under the public domain. It is just an example. * Some examples of the usage for the os_regex library. */ - + #include #include #include diff --git a/src/os_regex/examples/regex.c b/src/os_regex/examples/regex.c index 6200e33..a26eb9f 100755 --- a/src/os_regex/examples/regex.c +++ b/src/os_regex/examples/regex.c @@ -2,7 +2,7 @@ * Under the public domain. It is just an example. * Some examples of the usage for the os_regex library. */ - + #include #include #include diff --git a/src/os_regex/examples/regex_str.c b/src/os_regex/examples/regex_str.c index c28346f..08e6044 100755 --- a/src/os_regex/examples/regex_str.c +++ b/src/os_regex/examples/regex_str.c @@ -2,12 +2,12 @@ * Under the public domain. It is just an example. * Some examples of usage for the os_regex library. */ - + #include #include #include - -/* Must be included */ + +/* Must be included */ #include "os_regex.h" int main(int argc,char **argv) @@ -17,7 +17,7 @@ int main(int argc,char **argv) /* OSRegex structure */ OSRegex reg; - + /* checking for arguments */ if(argc != 3) { @@ -33,7 +33,7 @@ int main(int argc,char **argv) if(OSRegex_Compile(argv[1], ®, OS_RETURN_SUBSTRING)) { char *retv; - /* If the execution succeeds, the substrings will be + /* If the execution succeeds, the substrings will be * at reg.sub_strings */ if((retv = OSRegex_Execute(argv[2], ®))) @@ -45,7 +45,7 @@ int main(int argc,char **argv) printf("next pt: '%s'\n", retv); /* Assigning reg.sub_strings to ret */ ret = reg.sub_strings; - + printf("substrings:\n"); while(*ret) { @@ -63,13 +63,13 @@ int main(int argc,char **argv) OSRegex_FreePattern(®); } - + /* Compilation error */ else { printf("Error: Regex Compile Error: %d\n", reg.error); } - + return(r_code); } /* EOF */ diff --git a/src/os_regex/os_match.c b/src/os_regex/os_match.c index cd40136..3687523 100755 --- a/src/os_regex/os_match.c +++ b/src/os_regex/os_match.c @@ -13,10 +13,10 @@ #include #include #include - #include "os_regex.h" + /** int OS_Match2(char *pattern, char *str) v0.4 * * This function is a wrapper around the compile/execute @@ -39,9 +39,50 @@ int OS_Match2(char *pattern, char *str) OSMatch_FreePattern(®); } - + + return(r_code); +} + + +#ifdef NOTHINGEMPTY +/** int OS_Match3(char *pattern, char *str) v2.6 + * + * This function is used + * to match any values from a delimited string + * e.g. match pattern "abc" from string "123,abc,xyz" + */ +int OS_Match3(char *pattern, char *str, char *delimiter) +{ + int r_code = 0; + char *token = NULL; + char *dupstr = NULL; + char *saveptr = NULL; + + /* debug2("1. str [%s], dupstr [%s], token[%s], delim [%s]", str, dupstr, token, delimiter); */ + + os_strdup(str, dupstr); + /* debug2("2. str [%s], dupstr [%s], token[%s], delim [%s]", str, dupstr, token, delimiter); */ + + token = strtok_r(dupstr, delimiter, &saveptr); + /* debug2("3. str [%s], dupstr [%s], token[%s], delim [%s]", str, dupstr, token, delimiter); */ + + while (token != NULL) + { + debug2("Matching [%s] with [%s]", pattern, token); + if (!strcmp(pattern, token)) + { + r_code = 1; + break; + } + + token = strtok_r(NULL, delimiter, &saveptr); + } + + /* debug2("4. str [%s], dupstr [%s], token[%s], delim [%s]", str, dupstr, token, delimiter); */ + free(dupstr); return(r_code); } +#endif /* EOF */ diff --git a/src/os_regex/os_match_compile.c b/src/os_regex/os_match_compile.c index 366e79e..2fc552a 100755 --- a/src/os_regex/os_match_compile.c +++ b/src/os_regex/os_match_compile.c @@ -40,18 +40,18 @@ int OSMatch_Compile(char *pattern, OSMatch *reg, int flags) int i = 0; int count = 0; int end_of_string = 0; - + char *pt; char *new_str; char *new_str_free = NULL; - + /* Checking for references not initialized */ if(reg == NULL) { return(0); } - + /* Initializing OSRegex structure */ reg->error = 0; @@ -73,8 +73,8 @@ int OSMatch_Compile(char *pattern, OSMatch *reg, int flags) reg->error = OS_REGEX_MAXSIZE; goto compile_error; } - - + + /* Duping the pattern for our internal work */ new_str = strdup(pattern); if(!new_str) @@ -84,21 +84,21 @@ int OSMatch_Compile(char *pattern, OSMatch *reg, int flags) } new_str_free = new_str; pt = new_str; - - + + /* Getting the number of sub patterns */ while(*pt != '\0') { - /* The pattern must be always lower case if + /* The pattern must be always lower case if * case sensitive is set */ if(!(flags & OS_CASE_SENSITIVE)) { *pt = charmap[(uchar)*pt]; } - - /* Number of sub patterns */ + + /* Number of sub patterns */ if(*pt == OR) { count++; @@ -107,17 +107,17 @@ int OSMatch_Compile(char *pattern, OSMatch *reg, int flags) { usstrstr = 1; } - pt++; + pt++; } - - + + /* For the last pattern */ count++; reg->patterns = calloc(count +1, sizeof(char *)); reg->size = calloc(count +1, sizeof(int)); reg->match_fp = calloc(count +1, sizeof(void *)); - - + + /* Memory allocation error check */ if(!reg->patterns || !reg->size || !reg->match_fp) { @@ -134,12 +134,12 @@ int OSMatch_Compile(char *pattern, OSMatch *reg, int flags) reg->size[i] = 0; } i = 0; - - + + /* Reassigning pt to the beginning of the string */ pt = new_str; - + /* Getting the sub patterns */ do { @@ -155,7 +155,7 @@ int OSMatch_Compile(char *pattern, OSMatch *reg, int flags) /* Dupping the string */ if(*new_str == BEGINREGEX) reg->patterns[i] = strdup(new_str +1); - else + else reg->patterns[i] = strdup(new_str); /* Memory error */ @@ -199,7 +199,7 @@ int OSMatch_Compile(char *pattern, OSMatch *reg, int flags) reg->match_fp[i] = _os_strstr; reg->size[i] = strlen(reg->patterns[i]); } - + else { reg->match_fp[i] = _OS_Match; @@ -223,16 +223,16 @@ int OSMatch_Compile(char *pattern, OSMatch *reg, int flags) /* Success return */ free(new_str_free); return(1); - - + + /* Error handling */ compile_error: - + if(new_str_free) { free(new_str_free); } - + OSMatch_FreePattern(reg); return(0); diff --git a/src/os_regex/os_match_execute.c b/src/os_regex/os_match_execute.c index d61f0cb..8977484 100755 --- a/src/os_regex/os_match_execute.c +++ b/src/os_regex/os_match_execute.c @@ -39,10 +39,10 @@ int _OS_Match(char *pattern, char *str, int str_len, int size) { if(str[j] == '\0') return(FALSE); - + else if(*pt != charmap[(uchar)str[j]]) { - pt = pattern; + pt = pattern; goto nnext; } j++;pt++; @@ -62,8 +62,8 @@ int _os_strncmp(char *pattern, char *str, int str_len, int size) { if(strncasecmp(pattern, str, size) == 0) return(TRUE); - - return(FALSE); + + return(FALSE); } /** Internal matching **/ @@ -71,8 +71,8 @@ int _os_strcmp(char *pattern, char *str, int str_len, int size) { if(strcasecmp(pattern, str) == 0) return(TRUE); - - return(FALSE); + + return(FALSE); } int _os_strmatch(char *pattern, char *str, int str_len, int size) @@ -96,11 +96,11 @@ int _os_strcmp_last(char *pattern, char *str, int str_len, int size) /* Size of the string must be bigger */ if((str_len - size) < 0) return(FALSE); - + if(strcasecmp(pattern, str + (str_len - size)) == 0) return(TRUE); - - return(FALSE); + + return(FALSE); } @@ -113,7 +113,7 @@ int _os_strcmp_last(char *pattern, char *str, int str_len, int size) int OSMatch_Execute(char *str, int str_len, OSMatch *reg) { short int i = 0; - + /* The string can't be NULL */ if(str == NULL) { @@ -125,9 +125,9 @@ int OSMatch_Execute(char *str, int str_len, OSMatch *reg) /* Looping on all sub patterns */ while(reg->patterns[i]) { - if(reg->match_fp[i](reg->patterns[i], - str, - str_len, + if(reg->match_fp[i](reg->patterns[i], + str, + str_len, reg->size[i]) == TRUE) { return(1); @@ -136,7 +136,7 @@ int OSMatch_Execute(char *str, int str_len, OSMatch *reg) } return(0); -} +} /* EOF */ diff --git a/src/os_regex/os_match_free_pattern.c b/src/os_regex/os_match_free_pattern.c index 7131f08..a9939f3 100755 --- a/src/os_regex/os_match_free_pattern.c +++ b/src/os_regex/os_match_free_pattern.c @@ -33,7 +33,7 @@ void OSMatch_FreePattern(OSMatch *reg) { if(*pattern) free(*pattern); - pattern++; + pattern++; } free(reg->patterns); diff --git a/src/os_regex/os_regex.c b/src/os_regex/os_regex.c index c429271..8e871ad 100755 --- a/src/os_regex/os_regex.c +++ b/src/os_regex/os_regex.c @@ -39,7 +39,7 @@ int OS_Regex(char *pattern, char *str) OSRegex_FreePattern(®); } - + return(r_code); } diff --git a/src/os_regex/os_regex.h b/src/os_regex/os_regex.h index 24a600f..0d68c8c 100755 --- a/src/os_regex/os_regex.h +++ b/src/os_regex/os_regex.h @@ -22,12 +22,12 @@ /* Pattern maximum size */ -#define OS_PATTERN_MAXSIZE 2048 +#define OS_PATTERN_MAXSIZE 2048 /* Error codes */ #define OS_REGEX_REG_NULL 1 -#define OS_REGEX_PATTERN_NULL 2 +#define OS_REGEX_PATTERN_NULL 2 #define OS_REGEX_MAXSIZE 3 #define OS_REGEX_OUTOFMEMORY 4 #define OS_REGEX_STR_NULL 5 @@ -70,7 +70,7 @@ typedef struct _OSMatch * The error code is set on reg->error. */ int OSRegex_Compile(char *pattern, OSRegex *reg, int flags); - + /** char *OSRegex_Execute(char *str, OSRegex *reg) v0.1 * Compare an already compiled regular expression with @@ -93,7 +93,7 @@ void OSRegex_FreePattern(OSRegex *reg); * Release all the memory created to store the sub strings. * Returns void. */ -void OSRegex_FreeSubStrings(OSRegex *reg); +void OSRegex_FreeSubStrings(OSRegex *reg); /** int OS_Regex(char *pattern, char *str) v0.4 @@ -105,7 +105,7 @@ void OSRegex_FreeSubStrings(OSRegex *reg); int OS_Regex(char *pattern, char *str); - + /** int OSMatch_Compile(char *pattern, OSMatch *reg, int flags) v0.1 * Compile a pattern to be used later. * Allowed flags are: @@ -135,7 +135,9 @@ void OSMatch_FreePattern(OSMatch *reg); int OS_Match2(char *pattern, char *str); - +int OS_Match3(char *pattern, char *str, char* delimiter); + + /* OS_WordMatch v0.3: * Searches for pattern in the string */ @@ -148,7 +150,7 @@ int OS_WordMatch(char *pattern, char *str); * Returns a NULL terminated array on success or NULL on error. */ char **OS_StrBreak(char match, char *str, int size); - + /** int OS_StrHowClosedMatch(char *str1, char *str2) v0.1 * Returns the number of characters that both strings @@ -156,7 +158,7 @@ char **OS_StrBreak(char match, char *str, int size); */ int OS_StrHowClosedMatch(char *str1, char *str2); - + /** Inline prototypes **/ @@ -179,7 +181,7 @@ int OS_StrIsNum(char *str); * Checks if a specified char is in the following range: * a-z, A-Z, 0-9, _-. */ -#include "os_regex_maps.h" +#include "os_regex_maps.h" #define isValidChar(x) (hostname_map[(unsigned char)x]) diff --git a/src/os_regex/os_regex_compile.c b/src/os_regex/os_regex_compile.c index 12b04cd..10ae154 100755 --- a/src/os_regex/os_regex_compile.c +++ b/src/os_regex/os_regex_compile.c @@ -35,18 +35,18 @@ int OSRegex_Compile(char *pattern, OSRegex *reg, int flags) int parenthesis = 0; int prts_size = 0; int max_prts_size = 0; - + char *pt; char *new_str; char *new_str_free = NULL; - + /* Checking for references not initialized */ if(reg == NULL) { return(0); } - + /* Initializing OSRegex structure */ reg->error = 0; @@ -71,8 +71,8 @@ int OSRegex_Compile(char *pattern, OSRegex *reg, int flags) reg->error = OS_REGEX_MAXSIZE; goto compile_error; } - - + + /* Duping the pattern for our internal work */ new_str = strdup(pattern); if(!new_str) @@ -82,8 +82,8 @@ int OSRegex_Compile(char *pattern, OSRegex *reg, int flags) } new_str_free = new_str; pt = new_str; - - + + /* Getting the number of sub patterns */ do { @@ -91,12 +91,12 @@ int OSRegex_Compile(char *pattern, OSRegex *reg, int flags) { pt++; if(!((*pt == 'w') || - (*pt == 'W') || - (*pt == 's') || - (*pt == 'S') || - (*pt == 'd') || - (*pt == 'D') || - (*pt == '.') || + (*pt == 'W') || + (*pt == 's') || + (*pt == 'S') || + (*pt == 'd') || + (*pt == 'D') || + (*pt == '.') || (*pt == '(') || (*pt == ')') || (*pt == 'p') || @@ -144,22 +144,22 @@ int OSRegex_Compile(char *pattern, OSRegex *reg, int flags) parenthesis--; prts_size++; } - + /* We only allow one level of parenthesis */ if(parenthesis != 0 && parenthesis != 1) { reg->error = OS_REGEX_BADPARENTHESIS; goto compile_error; } - - /* The pattern must be always lower case if + + /* The pattern must be always lower case if * case sensitive is set */ if(!(flags & OS_CASE_SENSITIVE)) { *pt = charmap[(uchar)*pt]; } - + if(*pt == OR) { /* Each sub pattern must be closed on parenthesis */ @@ -170,9 +170,9 @@ int OSRegex_Compile(char *pattern, OSRegex *reg, int flags) } count++; } - pt++; + pt++; }while(*pt != '\0'); - + /* After the whole pattern is read, the parenthesis must all be closed */ if(parenthesis != 0) @@ -180,14 +180,14 @@ int OSRegex_Compile(char *pattern, OSRegex *reg, int flags) reg->error = OS_REGEX_BADPARENTHESIS; goto compile_error; } - - + + /* Allocating the memory for the sub patterns */ count++; reg->patterns = calloc(count +1, sizeof(char *)); reg->flags = calloc(count +1, sizeof(int)); - - + + /* For the substrings */ if((prts_size > 0) && (flags & OS_RETURN_SUBSTRING)) { @@ -199,8 +199,8 @@ int OSRegex_Compile(char *pattern, OSRegex *reg, int flags) goto compile_error; } } - - + + /* Memory allocation error check */ if(!reg->patterns || !reg->flags) { @@ -222,12 +222,12 @@ int OSRegex_Compile(char *pattern, OSRegex *reg, int flags) } } i = 0; - - + + /* Reassigning pt to the beginning of the string */ pt = new_str; - + /* Getting the sub patterns */ do { @@ -297,7 +297,7 @@ int OSRegex_Compile(char *pattern, OSRegex *reg, int flags) { max_prts_size = prts_size; } - + /* Allocating the memory */ reg->prts_closure[i] = calloc(prts_size + 1, sizeof(char *)); reg->prts_str[i] = calloc(prts_size + 1, sizeof(char *)); @@ -351,20 +351,20 @@ int OSRegex_Compile(char *pattern, OSRegex *reg, int flags) reg->error = OS_REGEX_OUTOFMEMORY; goto compile_error; } - + /* Success return */ free(new_str_free); return(1); - - + + /* Error handling */ compile_error: - + if(new_str_free) { free(new_str_free); } - + OSRegex_FreePattern(reg); return(0); diff --git a/src/os_regex/os_regex_execute.c b/src/os_regex/os_regex_execute.c index 03277a9..5fef327 100755 --- a/src/os_regex/os_regex_execute.c +++ b/src/os_regex/os_regex_execute.c @@ -34,7 +34,7 @@ char *OSRegex_Execute(char *str, OSRegex *reg) { char *ret; int i = 0; - + /* The string can't be NULL */ if(str == NULL) { @@ -52,6 +52,7 @@ char *OSRegex_Execute(char *str, OSRegex *reg) while(reg->patterns[i]) { /* Cleaning the prts_str */ + j = 0; while(reg->prts_closure[i][j]) { reg->prts_str[i][j] = NULL; @@ -76,7 +77,7 @@ char *OSRegex_Execute(char *str, OSRegex *reg) OSRegex_FreeSubStrings(reg); return(NULL); } - + /* Set the next one to null */ reg->prts_str[i][j+1][0] = str_char; k++; @@ -94,13 +95,13 @@ char *OSRegex_Execute(char *str, OSRegex *reg) return(0); } - + /* If we don't need the sub strings */ - + /* Looping on all sub patterns */ while(reg->patterns[i]) { - if((ret = _OS_Regex(reg->patterns[i], str, NULL, NULL, reg->flags[i]))) + if((ret = _OS_Regex(reg->patterns[i], str, NULL, NULL, reg->flags[i]))) { return(ret); } @@ -108,7 +109,7 @@ char *OSRegex_Execute(char *str, OSRegex *reg) } return(NULL); -} +} #define PRTS(x) ((prts(*x) && x++) || 1) #define ENDOFFILE(x) ( PRTS(x) && (*x == '\0')) @@ -119,26 +120,26 @@ char *OSRegex_Execute(char *str, OSRegex *reg) * Returns 1 on success and 0 on failure. * If prts_closure is set, the parenthesis locations will be * written on prts_str (which must not be NULL) - */ -char *_OS_Regex(char *pattern, char *str, char **prts_closure, + */ +char *_OS_Regex(char *pattern, char *str, char **prts_closure, char **prts_str, int flags) { char *r_code = NULL; - + int ok_here; int _regex_matched = 0; - + int prts_int; char *st = str; char *st_error = NULL; - + char *pt = pattern; char *next_pt; char *pt_error[4] = {NULL, NULL, NULL, NULL}; char *pt_error_str[4]; - + /* Will loop the whole string, trying to find a match */ do @@ -182,7 +183,7 @@ char *_OS_Regex(char *pattern, char *str, char **prts_closure, if(Regex((uchar)*(pt+1), (uchar)*st)) { next_pt = pt+2; - + /* If we don't have a '+' or '*', we should skip * searching using this pattern. */ @@ -201,7 +202,7 @@ char *_OS_Regex(char *pattern, char *str, char **prts_closure, r_code = st; continue; } - + /* If it is a '*', we need to set the _regex_matched * for the first pattern even. */ @@ -212,7 +213,7 @@ char *_OS_Regex(char *pattern, char *str, char **prts_closure, /* If our regex matches and we have a "+" set, we will - * try the next one to see if it matches. If yes, we + * try the next one to see if it matches. If yes, we * can jump to it, but saving our currently location * in case of error. * _regex_matched will set set to true after the first @@ -230,7 +231,7 @@ char *_OS_Regex(char *pattern, char *str, char **prts_closure, { next_pt++; } - + if(*next_pt == '\0') { ok_here = 1; @@ -271,7 +272,7 @@ char *_OS_Regex(char *pattern, char *str, char **prts_closure, { if(*(st+1) == '\0') prts_str[prts_int] = st+1; - else + else prts_str[prts_int] = st; break; } @@ -286,14 +287,14 @@ char *_OS_Regex(char *pattern, char *str, char **prts_closure, continue; } - + /* Each "if" will increment the amount * necessary for the next pattern in ok_here */ - if(ok_here) + if(ok_here) next_pt+=ok_here; - - + + if(!pt_error[0]) { pt_error[0] = pt; @@ -344,18 +345,18 @@ char *_OS_Regex(char *pattern, char *str, char **prts_closure, _regex_matched = 1; } - + r_code = st; continue; } - + else if((*(pt+3) == '\0') && (_regex_matched == 1)&&(r_code)) { r_code = st; if(!(flags & END_SET) || (flags & END_SET && (*st == '\0'))) return(r_code); } - + /* If we didn't match regex, but _regex_matched == 1, jump * to the next available pattern */ @@ -437,7 +438,7 @@ char *_OS_Regex(char *pattern, char *str, char **prts_closure, } pt = pattern; r_code = NULL; - + }while(*(++st) != '\0'); @@ -449,9 +450,9 @@ char *_OS_Regex(char *pattern, char *str, char **prts_closure, if(*pt == BACKSLASH && *(pt+2) == '*') pt+=3; else - break; + break; } - + if(prts(*pt)) { prts_int = 0; @@ -468,28 +469,28 @@ char *_OS_Regex(char *pattern, char *str, char **prts_closure, } /* Cleaning up */ - if(ENDOFFILE(pt) || - (*pt == BACKSLASH && - _regex_matched && - (pt+=2) && - isPlus(*pt) && + if(ENDOFFILE(pt) || + (*pt == BACKSLASH && + _regex_matched && + (pt+=2) && + isPlus(*pt) && + (pt++) && + ((ENDOFFILE(pt)) || + ((*pt == BACKSLASH) && + (pt+=2) && + (*pt == '*') && (pt++) && - ((ENDOFFILE(pt)) || - ((*pt == BACKSLASH) && - (pt+=2) && - (*pt == '*') && - (pt++) && (ENDOFFILE(pt)) ))) || (*pt == BACKSLASH && (pt+=2) && (*pt == '*') && (pt++) && ENDOFFILE(pt)) - ) + ) { return(r_code); } - + return(NULL); } diff --git a/src/os_regex/os_regex_free_pattern.c b/src/os_regex/os_regex_free_pattern.c index 305dde3..6ee085e 100755 --- a/src/os_regex/os_regex_free_pattern.c +++ b/src/os_regex/os_regex_free_pattern.c @@ -35,7 +35,7 @@ void OSRegex_FreePattern(OSRegex *reg) { if(*pattern) free(*pattern); - pattern++; + pattern++; } free(reg->patterns); @@ -74,7 +74,7 @@ void OSRegex_FreePattern(OSRegex *reg) /* Freeing the sub strings */ if(reg->sub_strings) { - OSRegex_FreeSubStrings(reg); + OSRegex_FreeSubStrings(reg); free(reg->sub_strings); reg->sub_strings = NULL; } diff --git a/src/os_regex/os_regex_internal.h b/src/os_regex/os_regex_internal.h index dde3ac3..299e5c2 100755 --- a/src/os_regex/os_regex_internal.h +++ b/src/os_regex/os_regex_internal.h @@ -25,13 +25,13 @@ #define OR '|' #define AND '&' -#define TRUE 1 +#define TRUE 1 #define FALSE 0 /* Pattern flags */ #define BEGIN_SET 0000200 -#define END_SET 0000400 +#define END_SET 0000400 /* uchar */ @@ -48,7 +48,7 @@ typedef unsigned char uchar; */ #define _IsW(x) ((x >= 48 && x <= 57 )|| \ (x >= 65 && x <= 90 )|| \ - (x >= 97 && x <= 122)) + (x >= 97 && x <= 122)) /* Is it a ' ' (blank) @@ -133,25 +133,25 @@ static const uchar charmap[] = { -/* Regex mapping +/* Regex mapping * 0 = none * 1 = \d * 2 = \w * 3 = \s * 4 = \p - * 5 = \( + * 5 = \( * 6 = \) * 7 = \\ * 8 = \D * 9 = \W * 10 = \S - * 11 = \. + * 11 = \. * 12 = \t * 13 = \$ * 14 = | * 15 = < */ -static const uchar regexmap[][256] = +static const uchar regexmap[][256] = { { '\000', '\000', '\000', '\000', '\000', '\000', '\000', '\000', @@ -252,8 +252,8 @@ static const uchar regexmap[][256] = '\330', '\331', '\332', '\333', '\334', '\335', '\336', '\337', '\340', '\341', '\342', '\343', '\344', '\345', '\346', '\347', '\350', '\351', '\352', '\353', '\354', '\355', '\356', '\357', - '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367', - '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367', + '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367', + '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367', }, { '\000', '\000', '\002', '\003', '\004', '\005', '\006', '\007', @@ -294,7 +294,7 @@ static const uchar regexmap[][256] = '\010', '\011', '\012', '\013', '\014', '\015', '\016', '\017', '\020', '\021', '\022', '\023', '\024', '\025', '\026', '\027', '\030', '\031', '\032', '\033', '\034', '\035', '\036', '\037', - '\040', '\041', '\042', '\043', '\044', '\045', '\046', '\047', + '\040', '\001', '\001', '\001', '\001', '\001', '\001', '\001', '\001', '\001', '\001', '\001', '\001', '\001', '\001', '\057', '\060', '\061', '\062', '\063', '\064', '\065', '\066', '\067', '\070', '\071', '\001', '\001', '\001', '\001', '\001', '\001', @@ -305,7 +305,7 @@ static const uchar regexmap[][256] = '\140', '\141', '\142', '\143', '\144', '\145', '\146', '\147', '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157', '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167', - '\170', '\171', '\172', '\173', '\174', '\175', '\176', '\177', + '\170', '\171', '\172', '\001', '\001', '\001', '\176', '\177', '\200', '\201', '\202', '\203', '\204', '\205', '\206', '\207', '\210', '\211', '\212', '\213', '\214', '\215', '\216', '\217', '\220', '\221', '\222', '\223', '\224', '\225', '\226', '\227', @@ -707,4 +707,4 @@ static const uchar regexmap[][256] = #endif -/* EOF */ +/* EOF */ diff --git a/src/os_regex/os_regex_maps.h b/src/os_regex/os_regex_maps.h index 9396637..13286af 100644 --- a/src/os_regex/os_regex_maps.h +++ b/src/os_regex/os_regex_maps.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_regex/os_regex_maps.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -50,12 +51,12 @@ static const unsigned char hostname_map[] = '\330', '\331', '\332', '\333', '\334', '\335', '\336', '\337', '\340', '\341', '\342', '\343', '\344', '\345', '\346', '\347', '\350', '\351', '\352', '\353', '\354', '\355', '\356', '\357', - '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367', - '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367', + '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367', + '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367', }; #endif -/* EOF */ +/* EOF */ diff --git a/src/os_regex/os_regex_match.c b/src/os_regex/os_regex_match.c index 8932cff..dfc24af 100755 --- a/src/os_regex/os_regex_match.c +++ b/src/os_regex/os_regex_match.c @@ -18,7 +18,7 @@ /* Algorithm: * Go as faster as you can :) - * + * * Supports: * '|' to separate multiple OR patterns * '^' to match the begining of a string @@ -29,8 +29,8 @@ int _InternalMatch(char *pattern, char *str,int count); -/* OS_WordMatch v0.3: - * Searches for pattern in the string +/* OS_WordMatch v0.3: + * Searches for pattern in the string */ int OS_WordMatch(char *pattern, char *str) { @@ -57,9 +57,9 @@ int OS_WordMatch(char *pattern, char *str) continue; } } - + count++; - + }while(pattern[count] != '\0'); /* Last check until end of string */ @@ -73,19 +73,19 @@ int _InternalMatch(char *pattern, char *str, int pattern_size) uchar *st = (uchar *)str; uchar last_char = pattern[pattern_size]; - - /* Return true for some odd expressions */ + + /* Return true for some odd expressions */ if(*pattern == '\0') return(TRUE); - + /* If '^' specified, just do a strncasecmp */ else if(*pattern == '^') { pattern++; pattern_size --; - + /* Compare two string */ if(strncasecmp(pattern,str,pattern_size) == 0) return(TRUE); @@ -96,8 +96,8 @@ int _InternalMatch(char *pattern, char *str, int pattern_size) /* Null line */ else if(*st == '\0') return(FALSE); - - + + /* Look to match the first pattern */ do { @@ -106,27 +106,27 @@ int _InternalMatch(char *pattern, char *str, int pattern_size) { str = (char *)st++; pt++; - + while(*pt != last_char) { if(*st == '\0') return(FALSE); - + else if(charmap[*pt] != charmap[*st]) goto error; - - st++;pt++; + + st++;pt++; } /* Return here if pt == last_char */ return(TRUE); - + error: st = (uchar *)str; pt = (uchar *)pattern; - + } - + st++; }while(*st != '\0'); diff --git a/src/os_regex/os_regex_str.c b/src/os_regex/os_regex_str.c index 4b5ddbc..2bc2212 100755 --- a/src/os_regex/os_regex_str.c +++ b/src/os_regex/os_regex_str.c @@ -23,12 +23,12 @@ int OS_StrIsNum(char *str) { if(str == NULL) return(FALSE); - + while(*str != '\0') { if(!_IsD(*str)) return(FALSE); /* 0 */ - str++; + str++; } return(TRUE); @@ -37,12 +37,12 @@ int OS_StrIsNum(char *str) /** int OS_StrHowClosedMatch(char *str1, char *str2) v0.1 * Returns the number of characters that both strings - * have in similar. + * have in similar. */ int OS_StrHowClosedMatch(char *str1, char *str2) { int count = 0; - + /* They don't match if any of them is null */ if(!str1 || !str2) { @@ -58,7 +58,7 @@ int OS_StrHowClosedMatch(char *str1, char *str2) count++; }while((str1[count] != '\0') && (str2[count] != '\0')); - + return(count); } @@ -68,7 +68,7 @@ int OS_StrHowClosedMatch(char *str1, char *str2) * Verifies if a string starts with the provided pattern. * Returns 1 on success or 0 on failure. */ -#define startswith(x,y) (strncmp(x,y,strlen(y)) == 0?1:0) -#define OS_StrStartsWith startswith +#define startswith(x,y) (strncmp(x,y,strlen(y)) == 0?1:0) +#define OS_StrStartsWith startswith /* EOF */ diff --git a/src/os_regex/os_regex_strbreak.c b/src/os_regex/os_regex_strbreak.c index 2294c2c..e6905c0 100755 --- a/src/os_regex/os_regex_strbreak.c +++ b/src/os_regex/os_regex_strbreak.c @@ -24,7 +24,7 @@ char **OS_StrBreak(char match, char *str, int size) { int count = 0; int i = 0; - + char *tmp_str = str; char **ret; @@ -40,7 +40,7 @@ char **OS_StrBreak(char match, char *str, int size) /* Memory error. Should provice a better way to detect it */ return(NULL); } - + /* Allocating memory to null */ while(i <= size) { @@ -62,13 +62,13 @@ char **OS_StrBreak(char match, char *str, int size) goto error; } - /* Copying the string */ + /* Copying the string */ ret[count][i-1] = '\0'; strncpy(ret[count],tmp_str,i-1); tmp_str = ++str; count++; - i=0; + i=0; continue; } diff --git a/src/os_xml/examples/mem_test.c b/src/os_xml/examples/mem_test.c index 437eb3d..d6938db 100755 --- a/src/os_xml/examples/mem_test.c +++ b/src/os_xml/examples/mem_test.c @@ -15,13 +15,13 @@ int main(int argc, char ** argv) printf("usage: %s file\n",argv[0]); return(-1); } - + while(1) { usleep(10); printf("."); fflush(stdout); - + if(OS_ReadXML(argv[1],&xml) < 0) { printf("Error reading XML!%s\n",xml.err); @@ -36,7 +36,7 @@ int main(int argc, char ** argv) } i = 0; - + while(node[i]) { xml_node **cnode = NULL; @@ -52,15 +52,15 @@ int main(int argc, char ** argv) /* */ j++; } - + OS_ClearNode(cnode); i++; } - + OS_ClearNode(node); - + node = NULL; - + OS_ClearXML(&xml); } return(0); diff --git a/src/os_xml/examples/test.c b/src/os_xml/examples/test.c index 89369d5..166a2b6 100755 --- a/src/os_xml/examples/test.c +++ b/src/os_xml/examples/test.c @@ -10,7 +10,7 @@ int main(int argc, char ** argv) OS_XML xml; XML_NODE node = NULL; - + /* File name must be given */ if(argc < 2) { @@ -18,8 +18,8 @@ int main(int argc, char ** argv) return(-1); } - - /* Reading the XML. Printing error and line number */ + + /* Reading the XML. Printing error and line number */ if(OS_ReadXML(argv[1],&xml) < 0) { printf("OS_ReadXML error: %s, line :%d\n",xml.err, xml.err_line); @@ -46,17 +46,17 @@ int main(int argc, char ** argv) { int j = 0; XML_NODE cnode; - + cnode = OS_GetElementsbyNode(&xml, node[i]); if(cnode == NULL) { i++; continue; } - + while(cnode[j]) { - printf("Element: %s -> %s\n", + printf("Element: %s -> %s\n", cnode[j]->element, cnode[j]->content); if(cnode[j]->attributes && cnode[j]->values) diff --git a/src/os_xml/os_xml.c b/src/os_xml/os_xml.c index c370d58..9a3f959 100755 --- a/src/os_xml/os_xml.c +++ b/src/os_xml/os_xml.c @@ -51,8 +51,8 @@ int _xml_fgetc(FILE *fp) if(c == '\n') /* add new line */ _line++; - - return(c); + + return(c); } #define FGETC(fp) _xml_fgetc(fp) @@ -75,7 +75,7 @@ void xml_error(OS_XML *_lxml, const char *msg,...) vfprintf(stderr, msg, args); fprintf(stderr, "\n\n"); #endif - + memset(_lxml->err,'\0', 128); vsnprintf(_lxml->err,127,msg,args); va_end(args); @@ -106,9 +106,9 @@ void OS_ClearXML(OS_XML *_lxml) free(_lxml->ck); free(_lxml->ln); memset(_lxml->err,'\0', 128); - + return; - + } @@ -160,7 +160,7 @@ int OS_ReadXML(char *file, OS_XML *_lxml) return(-1); } } - + fclose(fp); return(0); } @@ -213,7 +213,7 @@ int _ReadElem(FILE *fp, int position, int parent, OS_XML *_lxml) char closedelem[XML_MAXSIZE +1]; - + memset(elem,'\0',XML_MAXSIZE +1); memset(cont,'\0',XML_MAXSIZE +1); memset(closedelem,'\0',XML_MAXSIZE +1); @@ -249,7 +249,7 @@ int _ReadElem(FILE *fp, int position, int parent, OS_XML *_lxml) else if(r == 1) continue; } - + /* real checking */ if((location == -1) && (prevv == 0)) { @@ -268,7 +268,7 @@ int _ReadElem(FILE *fp, int position, int parent, OS_XML *_lxml) else continue; } - + else if((location == 0) && ((c == _R_CONFE) || (c == ' '))) { int _ge = 0; @@ -281,7 +281,7 @@ int _ReadElem(FILE *fp, int position, int parent, OS_XML *_lxml) _ge = '/'; elem[count -1] = '\0'; } - + _writememory(elem, XML_ELEM, count+1, parent, _lxml); _currentlycont=_lxml->cur-1; if(c == ' ') @@ -298,11 +298,11 @@ int _ReadElem(FILE *fp, int position, int parent, OS_XML *_lxml) _currentlycont = 0; count = 0; location = -1; - + memset(elem,'\0',XML_MAXSIZE); memset(closedelem,'\0',XML_MAXSIZE); memset(cont,'\0',XML_MAXSIZE); - + if(parent > 0) return(0); } @@ -310,9 +310,9 @@ int _ReadElem(FILE *fp, int position, int parent, OS_XML *_lxml) { count = 0; location = 1; - } + } } - + else if((location == 2) &&(c == _R_CONFE)) { closedelem[count]='\0'; @@ -400,7 +400,7 @@ int _writememory(char *str, short int type, unsigned int size, /* Allocating for the line */ _lxml->ln = realloc(_lxml->ln,(_lxml->cur+1)*sizeof(int)); _lxml->ln[_lxml->cur] = _line; - + /* Attributes does not need to be closed */ if(type == XML_ATTR) _lxml->ck[_lxml->cur] = 1; @@ -452,7 +452,7 @@ int _getattributes(FILE *fp,int parent,OS_XML *_lxml) int count = 0; int c; int c_to_match = 0; - + char attr[XML_MAXSIZE+1]; char value[XML_MAXSIZE+1]; @@ -464,7 +464,7 @@ int _getattributes(FILE *fp,int parent,OS_XML *_lxml) if(count >= XML_MAXSIZE) { attr[count-1] = '\0'; - xml_error(_lxml, + xml_error(_lxml, "XMLERR: Overflow attempt at attribute '%s'.",attr); return(-1); } @@ -521,11 +521,11 @@ int _getattributes(FILE *fp,int parent,OS_XML *_lxml) else if((location == 1)&&(c == c_to_match)) { value[count]='\0'; - + location = 0; c_to_match = 0; - - _writememory(attr, XML_ATTR, strlen(attr)+1, + + _writememory(attr, XML_ATTR, strlen(attr)+1, parent, _lxml); _writecontent(value,count+1,_lxml->cur-1,_lxml); c = FGETC(fp); @@ -548,7 +548,7 @@ int _getattributes(FILE *fp,int parent,OS_XML *_lxml) value[count++]=c; } - + xml_error(_lxml, "XMLERR: End of file while reading an attribute."); return(-1); } diff --git a/src/os_xml/os_xml.h b/src/os_xml/os_xml.h index f0099b0..9462694 100755 --- a/src/os_xml/os_xml.h +++ b/src/os_xml/os_xml.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_xml/os_xml.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. diff --git a/src/os_xml/os_xml_access.c b/src/os_xml/os_xml_access.c index 61ed5cd..5a6d529 100755 --- a/src/os_xml/os_xml_access.c +++ b/src/os_xml/os_xml_access.c @@ -26,7 +26,7 @@ char **_GetElementContent(OS_XML *_lxml, char **element_name, char *attr); /* OS_ElementExist: v1.0: 2005/02/26 - * Check if a element exists + * Check if a element exists * The element_name must be NULL terminated (last char) */ int OS_ElementExist(OS_XML *_lxml, char **element_name) @@ -66,7 +66,7 @@ int OS_ElementExist(OS_XML *_lxml, char **element_name) /* RootElementExist: v1.0: 2005/02/26 - * Check if a root element exists + * Check if a root element exists */ int OS_RootElementExist(OS_XML *_lxml, char *element_name) { @@ -201,7 +201,7 @@ char *OS_GetOneContentforElement(OS_XML *_lxml, char **element_name) { uniqret = ret[0]; } - + /* Freeing memory */ while(ret[i]) { @@ -210,7 +210,7 @@ char *OS_GetOneContentforElement(OS_XML *_lxml, char **element_name) i++; } free(ret); - + return(uniqret); } @@ -242,7 +242,7 @@ char **OS_GetContents(OS_XML *_lxml, char **element_name) /* OS_GetAttributeContent: v0.1: 2005/03/01 - * Get one value for a specific attribute + * Get one value for a specific attribute */ char *OS_GetAttributeContent(OS_XML *_lxml, char **element_name, char *attribute_name) @@ -279,7 +279,7 @@ char *OS_GetAttributeContent(OS_XML *_lxml, char **element_name, } if(success) return(uniqret); - + return(NULL); } @@ -312,7 +312,7 @@ char **_GetElementContent(OS_XML *_lxml, char **element_name, char *attr) } i = _lxml->fol; } - else + else { i = 0; } @@ -326,7 +326,7 @@ char **_GetElementContent(OS_XML *_lxml, char **element_name, char *attr) if(matched !=1) break; } - + /* Setting maximum depth of 16. */ if(j > 16) return(NULL); @@ -352,7 +352,7 @@ char **_GetElementContent(OS_XML *_lxml, char **element_name, char *attr) } } - + /* If the element name matches what we are looking for. */ else if(strcmp(_lxml->el[i], element_name[j]) == 0) { @@ -372,7 +372,7 @@ char **_GetElementContent(OS_XML *_lxml, char **element_name, char *attr) { break; } - + if(strcmp(attr, _lxml->el[k]) == 0) { i = k; @@ -389,7 +389,7 @@ char **_GetElementContent(OS_XML *_lxml, char **element_name, char *attr) { return(NULL); } - + /* Adding new entry. */ ret[k] = strdup(_lxml->ct[i]); ret[k + 1] = NULL; @@ -398,15 +398,15 @@ char **_GetElementContent(OS_XML *_lxml, char **element_name, char *attr) free(ret); return(NULL); } - + matched = 1; k++; - + if(attr != NULL) { - break; + break; } - + else if(_lxml->fol != 0) { _lxml->fol = i+1; @@ -429,7 +429,7 @@ char **_GetElementContent(OS_XML *_lxml, char **element_name, char *attr) matched = 0; } } - + if(ret == NULL) return(NULL); diff --git a/src/os_xml/os_xml_node_access.c b/src/os_xml/os_xml_node_access.c index dc71798..6fba555 100755 --- a/src/os_xml/os_xml_node_access.c +++ b/src/os_xml/os_xml_node_access.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_xml/os_xml_node_access.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -22,12 +23,12 @@ /* OS_ClearNode v0,1 - * Clear the Node structure + * Clear the Node structure */ void OS_ClearNode(xml_node **node) { if(node) - { + { int i=0; while(node[i]) { @@ -66,7 +67,7 @@ void OS_ClearNode(xml_node **node) node[i]->values=NULL; free(node[i]); node[i]=NULL; - i++; + i++; } free(node); node=NULL; @@ -92,8 +93,8 @@ xml_node **OS_GetElementsbyNode(OS_XML *_lxml, xml_node *node) i = node->key; j = _lxml->rl[i++]; } - - + + for(;i<_lxml->cur;i++) { if(_lxml->tp[i] == XML_ELEM) @@ -105,17 +106,17 @@ xml_node **OS_GetElementsbyNode(OS_XML *_lxml, xml_node *node) ret = (xml_node**)realloc(ret,(k+1)*sizeof(xml_node*)); if(ret == NULL) return(NULL); - + /* Allocating for the xml_node * */ ret[k] = (xml_node *)calloc(1,sizeof(xml_node)); if(ret[k] == NULL) return(NULL); - + ret[k]->element = NULL; ret[k]->content = NULL; ret[k]->attributes = NULL; ret[k]->values = NULL; - + /* Getting the element */ ret[k]->element=strdup(_lxml->el[i]); if(ret[k]->element == NULL) @@ -123,7 +124,7 @@ xml_node **OS_GetElementsbyNode(OS_XML *_lxml, xml_node *node) free(ret); return(NULL); } - + /* Getting the content */ if(_lxml->ct[i]) { @@ -140,13 +141,13 @@ xml_node **OS_GetElementsbyNode(OS_XML *_lxml, xml_node *node) if((_lxml->tp[l] == XML_ATTR)&&(_lxml->rl[l] == j+1)&& (_lxml->el[l]) && (_lxml->ct[l])) { - ret[k]->attributes = + ret[k]->attributes = (char**)realloc(ret[k]->attributes, (l-i+1)*sizeof(char*)); - ret[k]->values = + ret[k]->values = (char**)realloc(ret[k]->values, (l-i+1)*sizeof(char*)); - if(!(ret[k]->attributes) || + if(!(ret[k]->attributes) || !(ret[k]->values)) return(NULL); ret[k]->attributes[l-i-1]=strdup(_lxml->el[l]); @@ -154,7 +155,7 @@ xml_node **OS_GetElementsbyNode(OS_XML *_lxml, xml_node *node) if(!(ret[k]->attributes[l-i-1]) || !(ret[k]->values[l-i-1])) return(NULL); - l++; + l++; } else { @@ -178,7 +179,7 @@ xml_node **OS_GetElementsbyNode(OS_XML *_lxml, xml_node *node) break; } } - + if(ret ==NULL) return(NULL); diff --git a/src/os_xml/os_xml_variables.c b/src/os_xml/os_xml_variables.c index b5a7e09..2fd8069 100755 --- a/src/os_xml/os_xml_variables.c +++ b/src/os_xml/os_xml_variables.c @@ -51,19 +51,19 @@ int OS_ApplyVariables(OS_XML *_lxml) { if(!_lxml->ct[j]) break; - - /* If not used, it will be cleaned latter */ + + /* If not used, it will be cleaned latter */ snprintf(_lxml->err, 128, "XML_ERR: Memory error"); - + var = (char**)realloc(var,(s+1)*sizeof(char *)); if(var == NULL) return (-1); - + var[s] = strdup(_lxml->ct[j]); if(var[s] == NULL) return(-1); - - /* Cleaning the lxml->err */ + + /* Cleaning the lxml->err */ strncpy(_lxml->err," ", 3); _found_var = 1; @@ -71,46 +71,46 @@ int OS_ApplyVariables(OS_XML *_lxml) } else { - snprintf(_lxml->err, 128, + snprintf(_lxml->err, 128, "XML_ERR: Only \"name\" is allowed" " as an attribute for a variable"); return(-1); } } } /* Attribute FOR */ - - + + if((_found_var == 0)||(!_lxml->ct[i])) { - snprintf(_lxml->err,128, + snprintf(_lxml->err,128, "XML_ERR: Bad formed variable. No value set"); return(-1); } - - + + snprintf(_lxml->err,128, "XML_ERR: Memory error"); - + value = (char**)realloc(value,(s+1)*sizeof(char *)); if (value == NULL) return(-1); - + value[s] = strdup(_lxml->ct[i]); if(value[s] == NULL) - return(-1); - + return(-1); + strncpy(_lxml->err," ", 3); s++; } } /* initial FOR to get the variables */ - - + + /* No variable */ if(s == 0) return(0); /* Looping again and modifying where found the variables */ - i = 0; + i = 0; for(;i<_lxml->cur;i++) { if(((_lxml->tp[i] == XML_ELEM) || (_lxml->tp[i] == XML_ATTR))&& @@ -120,23 +120,23 @@ int OS_ApplyVariables(OS_XML *_lxml) char *p = NULL; char *p2= NULL; char lvar[256]; /* MAX Var size */ - - + + if(strlen(_lxml->ct[i]) <= 2) continue; - - - /* Duplicating string */ + + + /* Duplicating string */ p = strdup(_lxml->ct[i]); p2= p; - + if(p == NULL) { snprintf(_lxml->err, 128, "XML_ERR: Memory error"); return(-1); } - - + + /* Reading the whole string */ while(*p != '\0') { @@ -145,7 +145,7 @@ int OS_ApplyVariables(OS_XML *_lxml) tp = 0; p++; memset(lvar, '\0', 256); - + while(1) { if((*p == XML_VARIABLE_BEGIN) @@ -158,7 +158,7 @@ int OS_ApplyVariables(OS_XML *_lxml) lvar[tp]='\0'; final = init+tp; - + /* Looking for var */ for(j=0; jct[i]) + + tsize = strlen(_lxml->ct[i]) + strlen(value[j]) - tp + 1; var_placeh = strdup(_lxml->ct[i]); free(_lxml->ct[i]); - _lxml->ct[i] = (char*)calloc(tsize +2, + _lxml->ct[i] = (char*)calloc(tsize +2, sizeof(char)); - + if(_lxml->ct[i] == NULL || var_placeh == NULL) { snprintf(_lxml->err,128, "XML_ERR: Memory " @@ -196,26 +196,26 @@ int OS_ApplyVariables(OS_XML *_lxml) strncpy(_lxml->ct[i], var_placeh, tsize); - + _lxml->ct[i][init] = '\0'; strncat(_lxml->ct[i], value[j],tsize - init); init = strlen(_lxml->ct[i]); - strncat(_lxml->ct[i], p, + strncat(_lxml->ct[i], p, tsize - strlen(_lxml->ct[i])); - + free(var_placeh); break; } - + /* Variale not found */ if((j == s) && (strlen(lvar) >= 1)) { - snprintf(_lxml->err,128, + snprintf(_lxml->err,128, "XML_ERR: Unknown variable" ": %s", lvar); return(-1); @@ -224,10 +224,10 @@ int OS_ApplyVariables(OS_XML *_lxml) { init++; } - + goto go_next; } - + /* Maximum size for a variable */ if(tp >= 255) { @@ -236,21 +236,21 @@ int OS_ApplyVariables(OS_XML *_lxml) return(-1); } - + lvar[tp] = *p; tp++; p++; } } /* IF XML_VAR_BEGIN */ - + p++; init++; go_next: continue; - + } /* WHILE END */ - + if(p2 != NULL) { free(p2); @@ -271,11 +271,11 @@ int OS_ApplyVariables(OS_XML *_lxml) } if((value)&&(value[i])) { - free(value[i]); + free(value[i]); value[i] = NULL; } } - + if(var != NULL) { free(var); @@ -283,7 +283,7 @@ int OS_ApplyVariables(OS_XML *_lxml) } if(value != NULL) { - free(value); + free(value); value = NULL; } diff --git a/src/os_xml/os_xml_writer.c b/src/os_xml/os_xml_writer.c index 45d3f25..0e460e4 100755 --- a/src/os_xml/os_xml_writer.c +++ b/src/os_xml/os_xml_writer.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_xml/os_xml_writer.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -33,7 +34,7 @@ /* Internal functions */ int _oswcomment(FILE *fp_in, FILE *fp_out); -int _WReadElem(FILE *fp_in, FILE *fp_out, int position, int parent, +int _WReadElem(FILE *fp_in, FILE *fp_out, int position, int parent, char **node, char *value, int node_pos); @@ -55,8 +56,8 @@ int _xml_wfgetc(FILE *fp_in, FILE *fp_out) if(c == '\n') /* add new line */ _line++; - - return(c); + + return(c); } #define FWGETC(fp_in, fp_out) _xml_wfgetc(fp_in, fp_out) @@ -111,10 +112,10 @@ int OS_WriteXML(char *infile, char *outfile, char **nodes, char *attr, { int r = 0; int rwidth = 0; - + fseek(fp_out, 0, SEEK_END); fprintf(fp_out, "\n"); - + /* Printing each node. */ while(nodes[r]) { @@ -125,13 +126,13 @@ int OS_WriteXML(char *infile, char *outfile, char **nodes, char *attr, if(nodes[r]) fprintf(fp_out, "\n"); } - + /* Printing val. */ r--; rwidth -=6; fprintf(fp_out, "%s\n", newval, nodes[r]); r--; - + /* Closing each node. */ while(r >= 0) @@ -141,7 +142,7 @@ int OS_WriteXML(char *infile, char *outfile, char **nodes, char *attr, rwidth -= 3; } } - + fclose(fp_in); fclose(fp_out); return(0); @@ -201,7 +202,7 @@ int _oswcomment(FILE *fp_in, FILE *fp_out) -int _WReadElem(FILE *fp_in, FILE *fp_out, +int _WReadElem(FILE *fp_in, FILE *fp_out, int position, int parent, char **nodes, char *val, int node_pos) { int c; @@ -239,8 +240,8 @@ int _WReadElem(FILE *fp_in, FILE *fp_out, continue; } } - - + + /* Real checking */ if(location == -1) { @@ -262,7 +263,7 @@ int _WReadElem(FILE *fp_in, FILE *fp_out, continue; } } - + /* Looking for the closure */ else if((location == 0) && ((c == _R_CONFE) || (c == ' '))) @@ -277,7 +278,7 @@ int _WReadElem(FILE *fp_in, FILE *fp_out, _ge = '/'; elem[count -1] = '\0'; } - + /* If we may have more attributes */ if(c == ' ') @@ -298,11 +299,11 @@ int _WReadElem(FILE *fp_in, FILE *fp_out, { count = 0; location = -1; - + memset(elem,'\0',XML_MAXSIZE); memset(closedelem,'\0',XML_MAXSIZE); memset(cont,'\0',XML_MAXSIZE); - + if(parent > 0) { return(ret_code); @@ -313,7 +314,7 @@ int _WReadElem(FILE *fp_in, FILE *fp_out, { count = 0; location = 1; - } + } /* Checking position of the node */ @@ -323,7 +324,7 @@ int _WReadElem(FILE *fp_in, FILE *fp_out, } /* Checking if the element name matches */ - if(node_pos == position && + if(node_pos == position && nodes[node_pos] && strcmp(elem, nodes[node_pos]) == 0) { node_pos++; @@ -345,7 +346,7 @@ int _WReadElem(FILE *fp_in, FILE *fp_out, } } } - + else if((location == 2) &&(c == _R_CONFE)) { closedelem[count]='\0'; @@ -357,7 +358,7 @@ int _WReadElem(FILE *fp_in, FILE *fp_out, memset(elem,'\0',XML_MAXSIZE); memset(closedelem,'\0',XML_MAXSIZE); memset(cont,'\0',XML_MAXSIZE); - + count = 0; location = -1; if(parent > 0) @@ -395,7 +396,7 @@ int _WReadElem(FILE *fp_in, FILE *fp_out, { ret_code = 1; } - + count = 0; } } @@ -415,7 +416,7 @@ int _WReadElem(FILE *fp_in, FILE *fp_out, } } } - + if(location == -1) { return(ret_code); diff --git a/src/os_xml/os_xml_writer.h b/src/os_xml/os_xml_writer.h index bd4b81a..ce413c6 100755 --- a/src/os_xml/os_xml_writer.h +++ b/src/os_xml/os_xml_writer.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_xml/os_xml_writer.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -37,7 +38,7 @@ */ int OS_WriteXML(char *infile, char *outfile, char **nodes, char *attr, char *oldval, char *newval, int type); - + #endif diff --git a/src/os_zlib/os_zlib.c b/src/os_zlib/os_zlib.c index 21b1784..ad208fb 100755 --- a/src/os_zlib/os_zlib.c +++ b/src/os_zlib/os_zlib.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_zlib/os_zlib.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation */ - + #include "shared.h" #include "os_zlib.h" @@ -16,10 +17,10 @@ int os_compress(char *src, char *dst, int src_size, int dst_size) { unsigned long int zl_dst = dst_size; - + /* We make sure to do not allow long sizes */ - if(compress2((unsigned char *)dst, - &zl_dst, + if(compress2((unsigned char *)dst, + &zl_dst, (unsigned char *)src, (unsigned long int)src_size, 9) == Z_OK) { @@ -35,10 +36,10 @@ int os_compress(char *src, char *dst, int src_size, int dst_size) int os_uncompress(char *src, char *dst, int src_size, int dst_size) { unsigned long int zl_dst = dst_size; - - if(uncompress((unsigned char *)dst, + + if(uncompress((unsigned char *)dst, &zl_dst, - (unsigned char *)src, + (unsigned char *)src, (unsigned long int)src_size) == Z_OK) { dst[zl_dst] = '\0'; diff --git a/src/os_zlib/os_zlib.h b/src/os_zlib/os_zlib.h index a24205e..17d8d0b 100755 --- a/src/os_zlib/os_zlib.h +++ b/src/os_zlib/os_zlib.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_zlib/os_zlib.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation */ - + #ifndef __OS_ZLIB_H #define __OS_ZLIB_H diff --git a/src/os_zlib/zlib-test.c b/src/os_zlib/zlib-test.c index 587d56b..fcbaabe 100755 --- a/src/os_zlib/zlib-test.c +++ b/src/os_zlib/zlib-test.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/os_zlib/zlib-test.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -9,7 +10,7 @@ * Foundation */ - + #include "shared.h" #include "os_zlib.h" @@ -20,7 +21,7 @@ /* Zlib test */ int main(int argc, char **argv) { - int ret, srcsize, dstsize = 2010; + int ret, srcsize, dstsize = 2010; char dst[2048]; char dst2[2048]; @@ -32,7 +33,7 @@ int main(int argc, char **argv) printf("%s: string\n", argv[0]); exit(1); } - + srcsize = strlen(argv[1]); if(srcsize > 2000) { @@ -40,7 +41,7 @@ int main(int argc, char **argv) exit(1); } - + if((ret = os_compress(argv[1], dst, srcsize, dstsize))) { printf("Compressed, from %d->%d\n",srcsize, ret); @@ -53,11 +54,11 @@ int main(int argc, char **argv) /* Setting new srcsize for decompression */ srcsize = ret; - + if((ret = os_uncompress(dst, dst2, srcsize, dstsize))) { - printf("Uncompressed ok. String: '%s', size %d->%d\n", - dst2, srcsize, ret); + printf("Uncompressed ok. String: '%s', size %d->%d\n", + dst2, srcsize, ret); } else { diff --git a/src/remoted/ar-forward.c b/src/remoted/ar-forward.c index 1e6bc1c..df76769 100755 --- a/src/remoted/ar-forward.c +++ b/src/remoted/ar-forward.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/remoted/ar-forward.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -28,9 +29,9 @@ void *AR_Forward(void *arg) int arq = 0; int agent_id = 0; int ar_location = 0; - + char msg_to_send[OS_SIZE_1024 +1]; - + char msg[OS_SIZE_1024 +1]; char *location = NULL; char *ar_location_str = NULL; @@ -53,8 +54,8 @@ void *AR_Forward(void *arg) { /* Always zeroing the location */ ar_location = 0; - - + + /* Getting the location */ location = msg; @@ -104,8 +105,8 @@ void *AR_Forward(void *arg) { ar_location|=SPECIFIC_AGENT; } - - + + /*** Extracting the active response location ***/ tmp_str = strchr(ar_location_str, ' '); if(!tmp_str) @@ -127,28 +128,28 @@ void *AR_Forward(void *arg) } *tmp_str = '\0'; tmp_str++; - - + + /*** Creating the new message ***/ if(ar_location & NO_AR_MSG) { - snprintf(msg_to_send, OS_SIZE_1024, "%s%s", + snprintf(msg_to_send, OS_SIZE_1024, "%s%s", CONTROL_HEADER, tmp_str); } else { - snprintf(msg_to_send, OS_SIZE_1024, "%s%s%s", + snprintf(msg_to_send, OS_SIZE_1024, "%s%s%s", CONTROL_HEADER, EXECD_HEADER, tmp_str); } - + /* Lock use of keys */ key_lock(); - - + + /* Sending to ALL agents */ if(ar_location & ALL_AGENTS) { @@ -168,7 +169,7 @@ void *AR_Forward(void *arg) merror(AR_NOAGENT_ERROR, ARGV0, location); continue; } - + send_msg(agent_id, msg_to_send); } @@ -178,7 +179,7 @@ void *AR_Forward(void *arg) ar_location++; agent_id = OS_IsAllowedID(&keys, ar_agent_id); - + if(agent_id < 0) { key_unlock(); @@ -195,6 +196,6 @@ void *AR_Forward(void *arg) } } - + /* EOF */ diff --git a/src/remoted/config.c b/src/remoted/config.c index 59c2717..3328023 100755 --- a/src/remoted/config.c +++ b/src/remoted/config.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/remoted/config.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -25,7 +26,7 @@ * v0.2: New OS_XML * v0.3: Some improvements and cleanup * v0.4: Move everything to the global config validator. - */ + */ int RemotedConfig(char *cfgfile, remoted *logr) { int modules = 0; diff --git a/src/remoted/main.c b/src/remoted/main.c index 2f83a8d..008eacd 100755 --- a/src/remoted/main.c +++ b/src/remoted/main.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/remoted/main.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -20,17 +21,17 @@ int main(int argc, char **argv) int i = 0,c = 0; int uid = 0, gid = 0; int test_config = 0,run_foreground = 0; - + char *cfg = DEFAULTCPATH; char *dir = DEFAULTDIR; char *user = REMUSER; char *group = GROUPGLOBAL; - + /* Setting the name -- must be done ASAP */ OS_SetName(ARGV0); - + while((c = getopt(argc, argv, "Vdthfu:g:c:D:")) != -1){ switch(c){ case 'V': @@ -56,7 +57,7 @@ int main(int argc, char **argv) group = optarg; break; case 't': - test_config = 1; + test_config = 1; break; case 'c': if (!optarg) @@ -71,8 +72,8 @@ int main(int argc, char **argv) } debug1(STARTED_MSG,ARGV0); - - + + /* Return 0 if not configured */ if(RemotedConfig(cfg, &logr) < 0) { @@ -84,7 +85,12 @@ int main(int argc, char **argv) if(test_config) exit(0); - + if(logr.conn == NULL) + { + /* Not configured. */ + exit(0); + } + /* Check if the user and group given are valid */ uid = Privsep_GetUser(user); gid = Privsep_GetGroup(group); @@ -96,13 +102,13 @@ int main(int argc, char **argv) i = getpid(); - if(!run_foreground) + if(!run_foreground) { nowDaemon(); goDaemon(); } - + /* Setting new group */ if(Privsep_SetGroup(gid) < 0) ErrorExit(SETGID_ERROR, ARGV0, group); @@ -125,21 +131,21 @@ int main(int argc, char **argv) #else srandom( time(0) + getpid()+ i); #endif - + random(); - + /* Start up message */ verbose(STARTUP_MSG, ARGV0, (int)getpid()); /* Really starting the program. */ - i = 0; + i = 0; while(logr.conn[i] != 0) { /* Forking for each connection handler */ if(fork() == 0) - { + { /* On the child */ debug1("%s: DEBUG: Forking remoted: '%d'.",ARGV0, i); HandleRemote(i, uid); diff --git a/src/remoted/manager.c b/src/remoted/manager.c index d5f9e2d..3008401 100755 --- a/src/remoted/manager.c +++ b/src/remoted/manager.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/remoted/manager.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -62,7 +63,7 @@ void save_controlmsg(int agentid, char *r_msg) { char msg_ack[OS_FLSIZE +1]; - + /* Replying to the agent. */ snprintf(msg_ack, OS_FLSIZE, "%s%s", CONTROL_HEADER, HC_ACK); send_msg(agentid, msg_ack); @@ -74,16 +75,17 @@ void save_controlmsg(int agentid, char *r_msg) { utimes(_keep_alive[agentid], NULL); } - + else if(strcmp(r_msg, HC_STARTUP) == 0) { return; } - + else { FILE *fp; char *uname = r_msg; + char *random_leftovers; /* locking mutex. */ @@ -121,6 +123,11 @@ void save_controlmsg(int agentid, char *r_msg) *r_msg = '\0'; + random_leftovers = strchr(r_msg, '\n'); + if(random_leftovers) + { + *random_leftovers = '\0'; + } /* Updating the keep alive. */ @@ -137,7 +144,7 @@ void save_controlmsg(int agentid, char *r_msg) os_strdup(agent_file, _keep_alive[agentid]); } - + /* Writing to the file. */ fp = fopen(_keep_alive[agentid], "w"); @@ -148,7 +155,7 @@ void save_controlmsg(int agentid, char *r_msg) } } - + /* Locking now to notify of change. */ if(pthread_mutex_lock(&lastmsg_mutex) != 0) { @@ -156,7 +163,7 @@ void save_controlmsg(int agentid, char *r_msg) return; } - + /* Assign new values */ _changed[agentid] = 1; modified_agentid = agentid; @@ -165,7 +172,7 @@ void save_controlmsg(int agentid, char *r_msg) /* Signal that new data is available */ pthread_cond_signal(&awake_mutex); - + /* Unlocking mutex */ if(pthread_mutex_unlock(&lastmsg_mutex) != 0) { @@ -173,9 +180,9 @@ void save_controlmsg(int agentid, char *r_msg) return; } - + return; -} +} @@ -186,14 +193,14 @@ void f_files() int i; if(!f_sum) return; - for(i = 0;;i++) + for(i = 0;;i++) { if(f_sum[i] == NULL) break; - + if(f_sum[i]->name) free(f_sum[i]->name); - + free(f_sum[i]); f_sum[i] = NULL; } @@ -212,9 +219,9 @@ void c_files() DIR *dp; struct dirent *entry; - + os_md5 md5sum; - + int f_size = 0; @@ -234,21 +241,21 @@ void c_files() /* Opening the directory given */ dp = opendir(SHAREDCFG_DIR); - if(!dp) + if(!dp) { merror("%s: Error opening directory: '%s': %s ", ARGV0, SHAREDCFG_DIR, strerror(errno)); return; - } + } /* Reading directory */ while((entry = readdir(dp)) != NULL) { char tmp_dir[512]; - + /* Just ignore . and .. */ if((strcmp(entry->d_name,".") == 0) || (strcmp(entry->d_name,"..") == 0)) @@ -265,14 +272,14 @@ void c_files() continue; } - + if(OS_MD5_File(tmp_dir, md5sum) != 0) { merror("%s: Error accessing file '%s'",ARGV0, tmp_dir); continue; } - - + + f_sum = (file_sum **)realloc(f_sum, (f_size +2) * sizeof(file_sum *)); if(!f_sum) { @@ -285,7 +292,7 @@ void c_files() ErrorExit(MEM_ERROR,ARGV0); } - + strncpy(f_sum[f_size]->sum, md5sum, 32); os_strdup(entry->d_name, f_sum[f_size]->name); f_sum[f_size]->mark = 0; @@ -294,7 +301,7 @@ void c_files() MergeAppendFile(SHAREDCFG_FILE, tmp_dir); f_size++; } - + if(f_sum != NULL) f_sum[f_size] = NULL; @@ -306,15 +313,15 @@ void c_files() merror("%s: Error accessing file '%s'",ARGV0, SHAREDCFG_FILE); f_sum[0]->sum[0] = '\0'; } - strncpy(f_sum[0]->sum, md5sum, 32); + strncpy(f_sum[0]->sum, md5sum, 32); os_strdup(SHAREDCFG_FILENAME, f_sum[0]->name); - return; + return; } - + /* send_file_toagent: Sends a file to the agent. * Returns -1 on error @@ -324,10 +331,10 @@ int send_file_toagent(int agentid, char *name, char *sum) int i = 0, n = 0; char file[OS_SIZE_1024 +1]; char buf[OS_SIZE_1024 +1]; - + FILE *fp; - + snprintf(file, OS_SIZE_1024, "%s/%s",SHAREDCFG_DIR, name); fp = fopen(file, "r"); if(!fp) @@ -338,7 +345,7 @@ int send_file_toagent(int agentid, char *name, char *sum) /* Sending the file name first */ - snprintf(buf, OS_SIZE_1024, "%s%s%s %s\n", + snprintf(buf, OS_SIZE_1024, "%s%s%s %s\n", CONTROL_HEADER, FILE_UPDATE_HEADER, sum, name); if(send_msg(agentid, buf) == -1) @@ -370,7 +377,7 @@ int send_file_toagent(int agentid, char *name, char *sum) i++; } - + /* Sending the message to close the file */ snprintf(buf, OS_SIZE_1024, "%s%s", CONTROL_HEADER, FILE_CLOSE_HEADER); if(send_msg(agentid, buf) == -1) @@ -379,10 +386,10 @@ int send_file_toagent(int agentid, char *name, char *sum) fclose(fp); return(-1); } - + fclose(fp); - + return(0); } @@ -393,7 +400,7 @@ int send_file_toagent(int agentid, char *name, char *sum) * the agent. */ void read_controlmsg(int agentid, char *msg) -{ +{ int i; @@ -417,7 +424,7 @@ void read_controlmsg(int agentid, char *msg) } - /* Parse message */ + /* Parse message */ while(*msg != '\0') { char *md5; @@ -430,7 +437,7 @@ void read_controlmsg(int agentid, char *msg) if(!msg) { merror("%s: Invalid message from '%s' (strchr \\n)", - ARGV0, + ARGV0, keys.keyentries[agentid]->ip->ip); break; } @@ -442,7 +449,7 @@ void read_controlmsg(int agentid, char *msg) if(!file) { merror("%s: Invalid message from '%s' (strchr ' ')", - ARGV0, + ARGV0, keys.keyentries[agentid]->ip->ip); break; } @@ -456,7 +463,7 @@ void read_controlmsg(int agentid, char *msg) { if(strcmp(f_sum[0]->sum, md5) != 0) { - debug1("%s: DEBUG Sending file '%s' to agent.", ARGV0, + debug1("%s: DEBUG Sending file '%s' to agent.", ARGV0, f_sum[0]->name); if(send_file_toagent(agentid,f_sum[0]->name,f_sum[0]->sum)<0) { @@ -469,7 +476,7 @@ void read_controlmsg(int agentid, char *msg) i = 0; while(f_sum[i]) { - f_sum[i]->mark = 0; + f_sum[i]->mark = 0; i++; } @@ -492,7 +499,7 @@ void read_controlmsg(int agentid, char *msg) { f_sum[i]->mark = 2; } - break; + break; } } @@ -506,7 +513,7 @@ void read_controlmsg(int agentid, char *msg) if((f_sum[i]->mark == 1) || (f_sum[i]->mark == 0)) { - + debug1("%s: Sending file '%s' to agent.", ARGV0, f_sum[i]->name); if(send_file_toagent(agentid,f_sum[i]->name,f_sum[i]->sum) < 0) { @@ -516,11 +523,11 @@ void read_controlmsg(int agentid, char *msg) } } - f_sum[i]->mark = 0; + f_sum[i]->mark = 0; } - - return; + + return; } @@ -533,17 +540,17 @@ void *wait_for_msgs(void *none) { int id, i; char msg[OS_SIZE_1024 +2]; - + /* Initializing the memory */ memset(msg, '\0', OS_SIZE_1024 +2); - + /* should never leave this loop */ while(1) { /* Every NOTIFY * 30 minutes, re read the files. - * If something changed, notify all agents + * If something changed, notify all agents */ _ctime = time(0); if((_ctime - _stime) > (NOTIFY_TIME*30)) @@ -553,8 +560,8 @@ void *wait_for_msgs(void *none) _stime = _ctime; } - - + + /* locking mutex */ if(pthread_mutex_lock(&lastmsg_mutex) != 0) { @@ -584,9 +591,9 @@ void *wait_for_msgs(void *none) { continue; } - + id = 0; - + /* locking mutex */ if(pthread_mutex_lock(&lastmsg_mutex) != 0) { @@ -607,7 +614,7 @@ void *wait_for_msgs(void *none) id = 1; } - + /* Unlocking mutex */ if(pthread_mutex_unlock(&lastmsg_mutex) != 0) { @@ -651,7 +658,7 @@ void manager_init(int isUpdate) pthread_mutex_init(&lastmsg_mutex, NULL); pthread_cond_init(&awake_mutex, NULL); } - + modified_agentid = -1; return; diff --git a/src/remoted/remoted.c b/src/remoted/remoted.c index 4930aba..0800f1c 100755 --- a/src/remoted/remoted.c +++ b/src/remoted/remoted.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/remoted/remoted.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,14 +9,14 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ /* remote daemon. - * Listen to remote packets and forward them to the analysis + * Listen to remote packets and forward them to the analysis * system */ @@ -54,13 +55,13 @@ void HandleRemote(int position, int uid) } } } - - /* Bind TCP */ + + /* Bind TCP */ if(logr.proto[position] == TCP_PROTO) { - if((logr.sock = - OS_Bindporttcp(logr.port[position],logr.lip[position])) < 0) + if((logr.sock = + OS_Bindporttcp(logr.port[position],logr.lip[position], logr.ipv6[position])) < 0) { ErrorExit(BIND_ERROR, ARGV0, logr.port[position]); } @@ -68,22 +69,22 @@ void HandleRemote(int position, int uid) else { /* Using UDP. Fast, unreliable.. perfect */ - if((logr.sock = - OS_Bindportudp(logr.port[position], logr.lip[position])) < 0) + if((logr.sock = + OS_Bindportudp(logr.port[position], logr.lip[position], logr.ipv6[position])) < 0) { ErrorExit(BIND_ERROR, ARGV0, logr.port[position]); } } - - + + /* Revoking the privileges */ if(Privsep_SetUser(uid) < 0) { ErrorExit(SETUID_ERROR,ARGV0, REMUSER); } - - + + /* Creating PID */ if(CreatePID(ARGV0, getpid()) < 0) { @@ -93,25 +94,25 @@ void HandleRemote(int position, int uid) /* Start up message */ verbose(STARTUP_MSG, ARGV0, (int)getpid()); - + /* If Secure connection, deal with it */ if(logr.conn[position] == SECURE_CONN) { HandleSecure(); } - + else if(logr.proto[position] == TCP_PROTO) { HandleSyslogTCP(); } - + /* If not, deal with syslog */ else { HandleSyslog(); } - + return; } diff --git a/src/remoted/remoted.h b/src/remoted/remoted.h index 5666d0c..d26e289 100755 --- a/src/remoted/remoted.h +++ b/src/remoted/remoted.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/remoted/remoted.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -28,7 +29,7 @@ int RemotedConfig(char *cfgfile, remoted *logr); /* Handle Remote connections */ -void HandleRemote(int position, int uid); +void HandleRemote(int position, int uid); /* Handle Syslog */ void HandleSyslog(); diff --git a/src/remoted/secure.c b/src/remoted/secure.c index 9f40f12..39f4269 100755 --- a/src/remoted/secure.c +++ b/src/remoted/secure.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/remoted/secure.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -26,7 +27,7 @@ void HandleSecure() int agentid; char buffer[OS_MAXSTR +1]; - char cleartext_msg[OS_MAXSTR +1]; + char cleartext_msg[OS_MAXSTR +1]; char srcip[IPSIZE +1]; char *tmp_msg; char srcmsg[OS_FLSIZE +1]; @@ -55,7 +56,7 @@ void HandleSecure() { ErrorExit(THREAD_ERROR, ARGV0); } - + /* Creating wait_for_msgs thread */ if(CreateThread(wait_for_msgs, (void *)NULL) != 0) { @@ -70,16 +71,16 @@ void HandleSecure() { ErrorExit(QUEUE_FATAL, ARGV0, DEFAULTQUEUE); } - - - verbose(AG_AX_AGENTS, ARGV0, MAX_AGENTS); - + + verbose(AG_AX_AGENTS, ARGV0, MAX_AGENTS); + + /* Reading authentication keys */ verbose(ENC_READ, ARGV0); - + OS_ReadKeys(&keys); - + debug1("%s: DEBUG: OS_StartCounter.", ARGV0); OS_StartCounter(&keys); debug1("%s: DEBUG: OS_StartCounter completed.", ARGV0); @@ -95,14 +96,14 @@ void HandleSecure() memset(cleartext_msg, '\0', OS_MAXSTR +1); memset(srcmsg, '\0', OS_FLSIZE +1); tmp_msg = NULL; - - - + + + /* loop in here */ while(1) { /* Receiving message */ - recv_b = recvfrom(logr.sock, buffer, OS_MAXSTR, 0, + recv_b = recvfrom(logr.sock, buffer, OS_MAXSTR, 0, (struct sockaddr *)&peer_info, &peer_size); @@ -119,13 +120,13 @@ void HandleSecure() - /* Getting a valid agentid */ + /* Getting a valid agentid */ if(buffer[0] == '!') { tmp_msg = buffer; tmp_msg++; - - + + /* We need to make sure that we have a valid id * and that we reduce the recv buffer size. */ @@ -166,7 +167,7 @@ void HandleSecure() } else { - agentid = OS_IsAllowedIP(&keys, srcip); + agentid = OS_IsAllowedIP(&keys, srcip); if(agentid < 0) { if(check_keyupdate()) @@ -186,9 +187,9 @@ void HandleSecure() } tmp_msg = buffer; } - - /* Decrypting the message */ + + /* Decrypting the message */ tmp_msg = ReadSecMSG(&keys, tmp_msg, cleartext_msg, agentid, recv_b -1); if(tmp_msg == NULL) @@ -198,7 +199,7 @@ void HandleSecure() } - /* Check if it is a control message */ + /* Check if it is a control message */ if(IsValidHeader(tmp_msg)) { /* We need to save the peerinfo if it is a control msg */ @@ -212,14 +213,14 @@ void HandleSecure() /* Generating srcmsg */ - snprintf(srcmsg, OS_FLSIZE,"(%s) %s",keys.keyentries[agentid]->name, + snprintf(srcmsg, OS_FLSIZE,"(%s) %s",keys.keyentries[agentid]->name, keys.keyentries[agentid]->ip->ip); - + /* If we can't send the message, try to connect to the * socket again. If it not exit. */ - if(SendMSG(logr.m_queue, tmp_msg, srcmsg, + if(SendMSG(logr.m_queue, tmp_msg, srcmsg, SECURE_MQ) < 0) { merror(QUEUE_ERROR, ARGV0, DEFAULTQUEUE, strerror(errno)); diff --git a/src/remoted/sendmsg.c b/src/remoted/sendmsg.c index 12556db..0c6e2ad 100755 --- a/src/remoted/sendmsg.c +++ b/src/remoted/sendmsg.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/remoted/sendmsg.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -64,9 +65,9 @@ int check_keyupdate() { return(0); } - + key_lock(); - + /* Locking before using */ if(pthread_mutex_lock(&sendmsg_mutex) != 0) { @@ -74,7 +75,7 @@ int check_keyupdate() merror(MUTEX_ERROR, ARGV0); return(0); } - + if(OS_UpdateKeys(&keys)) { if(pthread_mutex_unlock(&sendmsg_mutex) != 0) @@ -90,7 +91,7 @@ int check_keyupdate() merror(MUTEX_ERROR, ARGV0); } key_unlock(); - + return(0); } @@ -105,7 +106,7 @@ void send_msg_init() } -/* send_msg() +/* send_msg() * Send message to an agent. * Returns -1 on error */ @@ -121,7 +122,7 @@ int send_msg(int agentid, char *msg) return(-1); } - + msg_size = CreateSecMSG(&keys, msg, crypt_msg, agentid); if(msg_size == 0) { @@ -129,7 +130,7 @@ int send_msg(int agentid, char *msg) return(-1); } - + /* Locking before using */ if(pthread_mutex_lock(&sendmsg_mutex) != 0) { @@ -141,19 +142,19 @@ int send_msg(int agentid, char *msg) /* Sending initial message */ if(sendto(logr.sock, crypt_msg, msg_size, 0, (struct sockaddr *)&keys.keyentries[agentid]->peer_info, - logr.peer_size) < 0) + logr.peer_size) < 0) { merror(SEND_ERROR,ARGV0, keys.keyentries[agentid]->id); } - - + + /* Unlocking mutex */ if(pthread_mutex_unlock(&sendmsg_mutex) != 0) { merror(MUTEX_ERROR, ARGV0); return(-1); } - + return(0); } diff --git a/src/remoted/syslog.c b/src/remoted/syslog.c index fd08c35..7011aa8 100755 --- a/src/remoted/syslog.c +++ b/src/remoted/syslog.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/remoted/syslog.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -18,7 +19,7 @@ -/* OS_IPNotAllowed, v0.1, 2005/02/11 +/* OS_IPNotAllowed, v0.1, 2005/02/11 * Checks if an IP is not allowed. */ static int OS_IPNotAllowed(char *srcip) @@ -66,7 +67,7 @@ void HandleSyslog() /* Initializing some variables */ memset(buffer, '\0', OS_SIZE_1024 +2); - + /* Connecting to the message queue * Exit if it fails. */ @@ -74,13 +75,13 @@ void HandleSyslog() { ErrorExit(QUEUE_FATAL,ARGV0, DEFAULTQUEUE); } - + /* Infinite loop in here */ while(1) { /* Receiving message */ - recv_b = recvfrom(logr.sock, buffer, OS_SIZE_1024, 0, + recv_b = recvfrom(logr.sock, buffer, OS_SIZE_1024, 0, (struct sockaddr *)&peer_info, &peer_size); /* Nothing received */ @@ -119,7 +120,7 @@ void HandleSyslog() else { buffer_pt = buffer; - } + } /* Checking if IP is allowed here */ if(OS_IPNotAllowed(srcip)) diff --git a/src/remoted/syslogtcp.c b/src/remoted/syslogtcp.c index 46b2ead..cce947f 100755 --- a/src/remoted/syslogtcp.c +++ b/src/remoted/syslogtcp.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/remoted/syslogtcp.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -18,7 +19,7 @@ -/* OS_IPNotAllowed, v0.1, 2005/02/11 +/* OS_IPNotAllowed, v0.1, 2005/02/11 * Checks if an IP is not allowed. */ static int OS_IPNotAllowed(char *srcip) @@ -50,14 +51,14 @@ static void HandleClient(int client_socket, char *srcip) { int sb_size = OS_MAXSTR; int r_sz = 0; - + char buffer[OS_MAXSTR +2]; char storage_buffer[OS_MAXSTR +2]; char tmp_buffer[OS_MAXSTR +2]; char *buffer_pt = NULL; - + /* Initializing some variables */ memset(buffer, '\0', OS_MAXSTR +2); memset(storage_buffer, '\0', OS_MAXSTR +2); @@ -85,12 +86,12 @@ static void HandleClient(int client_socket, char *srcip) storage_buffer[0] = '\0'; continue; } - + strncat(storage_buffer, buffer, sb_size); sb_size -= r_sz; - continue; + continue; } - + /* Seeing if we received more then just one message */ if(*(buffer_pt +1) != '\0') { @@ -111,14 +112,14 @@ static void HandleClient(int client_socket, char *srcip) } strncat(storage_buffer, buffer, sb_size); - + /* Removing carriage returns too */ buffer_pt = strchr(storage_buffer, '\r'); if(buffer_pt) *buffer_pt = '\0'; - + /* Removing syslog header */ if(storage_buffer[0] == '<') { @@ -172,13 +173,13 @@ void HandleSyslogTCP() int client_socket = 0; int st_errors = 0; int childcount = 0; - + char srcip[IPSIZE +1]; /* Initializing some variables */ memset(srcip, '\0', IPSIZE + 1); - + /* Connecting to the message queue * Exit if it fails. */ @@ -186,7 +187,7 @@ void HandleSyslogTCP() { ErrorExit(QUEUE_FATAL,ARGV0, DEFAULTQUEUE); } - + /* Infinit loop in here */ while(1) @@ -222,7 +223,7 @@ void HandleSyslogTCP() } - /* Forking to deal with new client */ + /* Forking to deal with new client */ if(fork() == 0) { HandleClient(client_socket, srcip); diff --git a/src/rootcheck/check_open_ports.c b/src/rootcheck/check_open_ports.c index 37ead35..97091ee 100755 --- a/src/rootcheck/check_open_ports.c +++ b/src/rootcheck/check_open_ports.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/rootcheck/check_open_ports.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -9,7 +10,7 @@ * Foundation */ - + #include "shared.h" #include "headers/defs.h" #include "headers/debug_op.h" @@ -25,7 +26,7 @@ char open_ports_str[OS_SIZE_1024 + 1]; int connect_to_port(int proto, int port) { int rc = 0; - + int ossock; struct sockaddr_in server; @@ -49,10 +50,10 @@ int connect_to_port(int proto, int port) { rc = 1; } - - close(ossock); - return(rc); + close(ossock); + + return(rc); } /* try_to_access_ports */ @@ -75,7 +76,7 @@ void try_to_access_ports() snprintf(port_proto, 64, "%d (tcp),", i); } strncat(open_ports_str, port_proto, open_ports_size); - open_ports_size -= strlen(port_proto) +1; + open_ports_size -= strlen(port_proto) +1; _ports_open++; } @@ -115,18 +116,18 @@ void check_open_ports() memset(open_ports_str, '\0', OS_SIZE_1024 +1); open_ports_size = OS_SIZE_1024 - 1; _ports_open = 0; - + #ifndef OSSECHIDS snprintf(open_ports_str, OS_SIZE_1024, "The following ports are open:"); open_ports_size-=strlen(open_ports_str) +1; - - /* Testing All ports */ + + /* Testing All ports */ try_to_access_ports(); open_ports_str[strlen(open_ports_str) -1] = '\0'; notify_rk(ALERT_OK, open_ports_str); - + #endif return; } diff --git a/src/rootcheck/check_rc_dev.c b/src/rootcheck/check_rc_dev.c index 09f6cf6..071b470 100755 --- a/src/rootcheck/check_rc_dev.c +++ b/src/rootcheck/check_rc_dev.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/rootcheck/check_rc_dev.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -9,7 +10,7 @@ * Foundation */ - + #ifndef WIN32 #include "shared.h" #include "rootcheck.h" @@ -23,12 +24,12 @@ int read_dev_dir(char *dir_name); int read_dev_file(char *file_name) { struct stat statbuf; - + if(lstat(file_name, &statbuf) < 0) { return(-1); } - + if(S_ISDIR(statbuf.st_mode)) { #ifdef DEBUG @@ -37,7 +38,7 @@ int read_dev_file(char *file_name) return(read_dev_dir(file_name)); } - + else if(S_ISREG(statbuf.st_mode)) { char op_msg[OS_SIZE_1024 +1]; @@ -58,11 +59,11 @@ int read_dev_file(char *file_name) int read_dev_dir(char *dir_name) { int i; - + DIR *dp; - + struct dirent *entry; - + /* when will these people learn that dev is not * meant to store log files or other kind of texts.. */ @@ -70,8 +71,8 @@ int read_dev_dir(char *dir_name) "MAKEDEV.README", ".udevdb", ".udev.tdb", ".initramfs-tools", "MAKEDEV.local", ".udev", ".initramfs", - "oprofile","fd", - #ifdef SOLARIS + "oprofile","fd","cgroup", + #ifdef SOLARIS ".devfsadm_dev.lock", ".devlink_db_lock", ".devlink_db", @@ -80,22 +81,22 @@ int read_dev_dir(char *dir_name) ".devfsadm_synch_door", ".zone_reg_door", #endif - NULL}; - + NULL}; + /* Full path ignore */ char *(ignore_dev_full_path[]) = {"/dev/shm/sysconfig", - "/dev/bus/usb/.usbfs", + "/dev/bus/usb/.usbfs", "/dev/shm", "/dev/gpmctl", NULL}; - + if((dir_name == NULL)||(strlen(dir_name) > PATH_MAX)) { merror("%s: Invalid directory given.",ARGV0); return(-1); } - + /* Opening the directory given */ dp = opendir(dir_name); if(!dp) @@ -109,24 +110,24 @@ int read_dev_dir(char *dir_name) /* Just ignore . and .. */ if((strcmp(entry->d_name,".") == 0) || - (strcmp(entry->d_name,"..") == 0)) + (strcmp(entry->d_name,"..") == 0)) continue; - + _dev_total++; - + /* Do not look for the ignored files */ for(i = 0;ignore_dev[i] != NULL;i++) { if(strcmp(ignore_dev[i], entry->d_name) == 0) break; } - + if(ignore_dev[i] != NULL) continue; - - f_name[PATH_MAX +1] = '\0'; + + f_name[PATH_MAX +1] = '\0'; snprintf(f_name, PATH_MAX +1, "%s/%s",dir_name, entry->d_name); - + /* Do not look for the full ignored files */ for(i = 0;ignore_dev_full_path[i] != NULL;i++) @@ -135,20 +136,20 @@ int read_dev_dir(char *dir_name) break; } - + /* Checking against the full path. */ if(ignore_dev_full_path[i] != NULL) { continue; } - + read_dev_file(f_name); } closedir(dp); - + return(0); } @@ -159,7 +160,7 @@ int read_dev_dir(char *dir_name) void check_rc_dev(char *basedir) { char file_path[OS_SIZE_1024 +1]; - + _dev_total = 0, _dev_errors = 0; debug1("%s: DEBUG: Starting on check_rc_dev", ARGV0); @@ -172,11 +173,11 @@ void check_rc_dev(char *basedir) { char op_msg[OS_SIZE_1024 +1]; snprintf(op_msg, OS_SIZE_1024, "No problem detected on the /dev " - "directory. Analyzed %d files", + "directory. Analyzed %d files", _dev_total); notify_rk(ALERT_OK, op_msg); } - + return; } diff --git a/src/rootcheck/check_rc_files.c b/src/rootcheck/check_rc_files.c index 5d60a82..b8c6f64 100755 --- a/src/rootcheck/check_rc_files.c +++ b/src/rootcheck/check_rc_files.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/rootcheck/check_rc_files.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -9,7 +10,7 @@ * Foundation */ - + #include "shared.h" #include "rootcheck.h" @@ -27,17 +28,17 @@ void check_rc_files(char *basedir, FILE *fp) char *file; char *name; char *link; - + int _errors = 0; int _total = 0; - - + + debug1("%s: DEBUG: Starting on check_rc_files", ARGV0); - + while(fgets(buf, OS_SIZE_1024, fp) != NULL) { char *nbuf; - + /* Removing end of line */ nbuf = strchr(buf, '\n'); if(nbuf) @@ -47,8 +48,8 @@ void check_rc_files(char *basedir, FILE *fp) /* Assigning buf to be used */ nbuf = buf; - - /* Excluding commented lines or blanked ones */ + + /* Excluding commented lines or blanked ones */ while(*nbuf != '\0') { if(*nbuf == ' ' || *nbuf == '\t') @@ -61,15 +62,15 @@ void check_rc_files(char *basedir, FILE *fp) else break; } - + if(*nbuf == '\0') goto newline; - + /* File now may be valid */ file = nbuf; - name = nbuf; - - + name = nbuf; + + /* Getting the file and the rootkit name */ while(*nbuf != '\0') { @@ -85,12 +86,12 @@ void check_rc_files(char *basedir, FILE *fp) nbuf++; } } - + if(*nbuf == '\0') goto newline; - - - /* Some ugly code to remove spaces and \t */ + + + /* Some ugly code to remove spaces and \t */ while(*nbuf != '\0') { if(*nbuf == '!') @@ -115,21 +116,21 @@ void check_rc_files(char *basedir, FILE *fp) } } - + /* Getting the link (if present) */ link = strchr(nbuf, ':'); if(link) { *link = '\0'; - - link++; + + link++; if(*link == ':') { link++; } } - - + + /* Cleaning any space of \t at the end */ nbuf = strchr(nbuf, ' '); if(nbuf) @@ -142,7 +143,7 @@ void check_rc_files(char *basedir, FILE *fp) { *nbuf = '\0'; } - + _total++; @@ -153,15 +154,15 @@ void check_rc_files(char *basedir, FILE *fp) { merror(MAX_RK_MSG, ARGV0, MAX_RK_SYS); } - + else { /* Removing * / from the file */ file++; if(*file == '/') file++; - - /* Memory assignment */ + + /* Memory assignment */ rk_sys_file[rk_sys_count] = strdup(file); rk_sys_name[rk_sys_count] = strdup(name); @@ -169,16 +170,16 @@ void check_rc_files(char *basedir, FILE *fp) !rk_sys_file[rk_sys_count] ) { merror(MEM_ERROR, ARGV0); - + if(rk_sys_file[rk_sys_count]) free(rk_sys_file[rk_sys_count]); if(rk_sys_name[rk_sys_count]) free(rk_sys_name[rk_sys_count]); - + rk_sys_file[rk_sys_count] = NULL; - rk_sys_name[rk_sys_count] = NULL; + rk_sys_name[rk_sys_count] = NULL; } - + rk_sys_count++; /* Always assigning the last as NULL */ @@ -187,23 +188,23 @@ void check_rc_files(char *basedir, FILE *fp) } continue; } - + snprintf(file_path, OS_SIZE_1024, "%s/%s",basedir, file); - - /* Checking if file exists */ + + /* Checking if file exists */ if(is_file(file_path)) { char op_msg[OS_SIZE_1024 +1]; - + _errors = 1; snprintf(op_msg, OS_SIZE_1024, "Rootkit '%s' detected " "by the presence of file '%s'.",name, file_path); - + notify_rk(ALERT_ROOTKIT_FOUND, op_msg); } - + newline: - continue; + continue; } if(_errors == 0) diff --git a/src/rootcheck/check_rc_if.c b/src/rootcheck/check_rc_if.c index 096aa4e..1d4dd62 100755 --- a/src/rootcheck/check_rc_if.c +++ b/src/rootcheck/check_rc_if.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/rootcheck/check_rc_if.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -13,7 +14,7 @@ #include #include -#include +#include #include #include @@ -49,9 +50,9 @@ int run_ifconfig(char *ifconfig) if(system(nt) == 0) return(1); - return(0); + return(0); } - + /* check_rc_if: v0.1 * Check all interfaces for promiscuous mode @@ -60,7 +61,7 @@ void check_rc_if() { int _fd, _errors = 0, _total = 0; struct ifreq tmp_str[16]; - + struct ifconf _if; struct ifreq *_ir; struct ifreq *_ifend; @@ -73,34 +74,34 @@ void check_rc_if() return; } - + memset(tmp_str, 0, sizeof(struct ifreq)*16); _if.ifc_len = sizeof(tmp_str); _if.ifc_buf = (caddr_t)(tmp_str); - + if (ioctl(_fd, SIOCGIFCONF, &_if) < 0) { close(_fd); merror("%s: Error checking interfaces (ioctl)", ARGV0); return; } - + _ifend = (struct ifreq*) ((char*)tmp_str + _if.ifc_len); _ir = tmp_str; /* Looping on all interfaces */ - for (; _ir < _ifend; _ir++) + for (; _ir < _ifend; _ir++) { strncpy(_ifr.ifr_name, _ir->ifr_name, sizeof(_ifr.ifr_name)); /* Getting information from each interface */ - if (ioctl(_fd, SIOCGIFFLAGS, (char*)&_ifr) == -1) + if (ioctl(_fd, SIOCGIFFLAGS, (char*)&_ifr) == -1) { continue; } _total++; - + if ((_ifr.ifr_flags & IFF_PROMISC) ) { @@ -120,7 +121,7 @@ void check_rc_if() } _errors++; } - } + } close(_fd); if(_errors == 0) @@ -130,7 +131,7 @@ void check_rc_if() " Analyzed %d interfaces.", _total); notify_rk(ALERT_OK, op_msg); } - + return; } diff --git a/src/rootcheck/check_rc_pids.c b/src/rootcheck/check_rc_pids.c index a2868e3..bd06f2d 100755 --- a/src/rootcheck/check_rc_pids.c +++ b/src/rootcheck/check_rc_pids.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/rootcheck/check_rc_pids.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -26,7 +27,7 @@ int proc_read(int pid) if(noproc) return(0); - + snprintf(dir, OS_SIZE_1024, "%d", pid); if(isfile_ondir(dir, "/proc")) { @@ -47,15 +48,15 @@ int proc_chdir(int pid) if(noproc) return(0); - + if(!getcwd(curr_dir, OS_SIZE_1024)) { return(0); } - + if(chdir("/proc") == -1) - return(0); - + return(0); + snprintf(dir, OS_SIZE_1024, "/proc/%d", pid); if(chdir(dir) == 0) { @@ -64,8 +65,8 @@ int proc_chdir(int pid) /* Returning to the previous directory */ chdir(curr_dir); - - return(ret); + + return(ret); } @@ -75,12 +76,12 @@ int proc_chdir(int pid) int proc_stat(int pid) { char proc_dir[OS_SIZE_1024 + 1]; - + if(noproc) return(0); - + snprintf(proc_dir, OS_SIZE_1024, "%s/%d", "/proc", pid); - + if(is_file(proc_dir)) { return(1); @@ -105,21 +106,21 @@ void loop_all_pids(char *ps, pid_t max_pid, int *_errors, int *_total) int _proc_stat = 0; int _proc_read = 0; int _proc_chdir = 0; - + pid_t i = 1; pid_t my_pid; char command[OS_SIZE_1024 +1]; my_pid = getpid(); - + for(;;i++) { if((i <= 0)||(i > max_pid)) break; (*_total)++; - + _kill0 = 0; _kill1 = 0; _gsid0 = 0; @@ -130,15 +131,15 @@ void loop_all_pids(char *ps, pid_t max_pid, int *_errors, int *_total) _proc_stat = 0; _proc_read = 0; _proc_chdir = 0; - + /* kill test */ if(!((kill(i, 0) == -1)&&(errno == ESRCH))) { _kill0 = 1; } - - /* getsid to test */ + + /* getsid to test */ if(!((getsid(i) == -1)&&(errno == ESRCH))) { _gsid0 = 1; @@ -149,20 +150,20 @@ void loop_all_pids(char *ps, pid_t max_pid, int *_errors, int *_total) { _gpid0 = 1; } - + /* proc stat */ _proc_stat = proc_stat(i); - + /* proc readdir */ _proc_read = proc_read(i); /* proc chdir */ - _proc_chdir = proc_chdir(i); - - + _proc_chdir = proc_chdir(i); + + /* IF PID does not exist, keep going */ - if(!_kill0 && !_gsid0 && !_gpid0 && + if(!_kill0 && !_gsid0 && !_gpid0 && !_proc_stat && !_proc_read && !_proc_chdir) { continue; @@ -173,8 +174,8 @@ void loop_all_pids(char *ps, pid_t max_pid, int *_errors, int *_total) { continue; } - - /* Checking the number of errors */ + + /* Checking the number of errors */ if((*_errors) > 15) { char op_msg[OS_SIZE_1024 +1]; @@ -184,13 +185,13 @@ void loop_all_pids(char *ps, pid_t max_pid, int *_errors, int *_total) notify_rk(ALERT_SYSTEM_CRIT, op_msg); return; } - - + + /* checking if process appears on ps */ if(*ps) { - snprintf(command, OS_SIZE_1024, "%s -p %d > /dev/null 2>&1", - ps, + snprintf(command, OS_SIZE_1024, "%s -p %d > /dev/null 2>&1", + ps, (int)i); /* Found PID on ps */ @@ -198,20 +199,20 @@ void loop_all_pids(char *ps, pid_t max_pid, int *_errors, int *_total) if(system(command) == 0) _ps0 = 1; } - + /* If we are being run by the ossec hids, sleep here (no rush) */ #ifdef OSSECHIDS sleep(2); #endif - + /* Everyone returned ok */ if(_ps0 && _kill0 && _gsid0 && _gpid0 && _proc_stat && _proc_read) { continue; } - - - + + + /* If our kill or getsid system call, got the * PID , but ps didn't, we need to find if it was a problem * with a PID being deleted (not used anymore) @@ -221,7 +222,7 @@ void loop_all_pids(char *ps, pid_t max_pid, int *_errors, int *_total) { _gsid1 = 1; } - + if(!((kill(i, 0) == -1)&&(errno == ESRCH))) { _kill1 = 1; @@ -231,14 +232,14 @@ void loop_all_pids(char *ps, pid_t max_pid, int *_errors, int *_total) { _gpid1 = 1; } - + _proc_stat = proc_stat(i); - + _proc_read = proc_read(i); _proc_chdir = proc_chdir(i); - + /* If it matches, process was terminated */ if(!_gsid1 &&!_kill1 &&!_gpid1 &&!_proc_stat && !_proc_read &&!_proc_chdir) @@ -246,14 +247,14 @@ void loop_all_pids(char *ps, pid_t max_pid, int *_errors, int *_total) continue; } } - + #ifdef AIX /* Ignoring AIX wait and sched programs. */ if((_gsid0 == _gsid1) && (_kill0 == _kill1) && (_gpid0 == _gpid1) && - (_ps0 == 1) && - (_gsid0 == 1) && + (_ps0 == 1) && + (_gsid0 == 1) && (_kill0 == 0)) { /* The wait and sched programs do not respond to kill 0. @@ -266,7 +267,7 @@ void loop_all_pids(char *ps, pid_t max_pid, int *_errors, int *_total) } #endif - + if((_gsid0 == _gsid1)&& (_kill0 == _kill1)&& (_gsid0 != _kill0)) @@ -325,8 +326,8 @@ void loop_all_pids(char *ps, pid_t max_pid, int *_errors, int *_total) snprintf(op_msg, OS_SIZE_1024, "Process '%d' hidden from " "ps. Possible trojaned version installed.", (int)i); - - notify_rk(ALERT_ROOTKIT_FOUND, op_msg); + + notify_rk(ALERT_ROOTKIT_FOUND, op_msg); (*_errors)++; } } @@ -341,16 +342,16 @@ void check_rc_pids() { int _total = 0; int _errors = 0; - + char ps[OS_SIZE_1024 +1]; - + char proc_0[] = "/proc"; char proc_1[] = "/proc/1"; pid_t max_pid = MAX_PID; noproc = 1; - + /* Checking where ps is */ memset(ps, '\0', OS_SIZE_1024 +1); strncpy(ps, "/bin/ps", OS_SIZE_1024); @@ -360,14 +361,14 @@ void check_rc_pids() if(!is_file(ps)) ps[0] = '\0'; } - - + + /* Proc is mounted */ if(is_file(proc_0) && is_file(proc_1)) { noproc = 0; } - + loop_all_pids(ps, max_pid, &_errors, &_total); if(_errors == 0) @@ -378,7 +379,7 @@ void check_rc_pids() "Analyzed %d processes.", ps, _total); notify_rk(ALERT_OK, op_msg); } - + return; } diff --git a/src/rootcheck/check_rc_policy.c b/src/rootcheck/check_rc_policy.c index f10708e..8d7cf65 100755 --- a/src/rootcheck/check_rc_policy.c +++ b/src/rootcheck/check_rc_policy.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/rootcheck/check_rc_policy.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -9,12 +10,12 @@ * Foundation */ - + #include "shared.h" #include "rootcheck.h" - + /* check_rc_unixaudit: * Read the file pointer specified * and check if the configured file is there @@ -22,9 +23,9 @@ void check_rc_unixaudit(FILE *fp, void *p_list) { debug1("%s: DEBUG: Starting on check_rc_unixaudit", ARGV0); - + rkcl_get_entry(fp, "System Audit:", p_list); - + } @@ -36,9 +37,9 @@ void check_rc_unixaudit(FILE *fp, void *p_list) void check_rc_winaudit(FILE *fp, void *p_list) { debug1("%s: DEBUG: Starting on check_rc_winaudit", ARGV0); - + rkcl_get_entry(fp, "Windows Audit:", p_list); - + } /* check_rc_winmalware: @@ -48,9 +49,9 @@ void check_rc_winaudit(FILE *fp, void *p_list) void check_rc_winmalware(FILE *fp, void *p_list) { debug1("%s: DEBUG: Starting on check_rc_winmalware", ARGV0); - + rkcl_get_entry(fp, "Windows Malware:", p_list); - + } /* check_rc_winapps: @@ -60,7 +61,7 @@ void check_rc_winmalware(FILE *fp, void *p_list) void check_rc_winapps(FILE *fp, void *p_list) { debug1("%s: DEBUG: Starting on check_rc_winapps", ARGV0); - + rkcl_get_entry(fp, "Application Found:", p_list); } diff --git a/src/rootcheck/check_rc_ports.c b/src/rootcheck/check_rc_ports.c index 890407c..d40356d 100755 --- a/src/rootcheck/check_rc_ports.c +++ b/src/rootcheck/check_rc_ports.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/rootcheck/check_rc_ports.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -9,9 +10,9 @@ * Foundation */ - + #ifndef WIN32 - + #include "shared.h" #include "rootcheck.h" @@ -30,7 +31,7 @@ #define NETSTAT_LIST "netstat -an | grep \"^%s\" | "\ "cut -d ':' -f 2 | cut -d ' ' -f 1" #define NETSTAT "netstat -an | grep \"^%s\" | " \ - "grep \"[^0-9]%d \" > /dev/null 2>&1" + "grep \"[^0-9]%d \" > /dev/null 2>&1" #endif #ifndef NETSTAT @@ -41,6 +42,7 @@ int run_netstat(int proto, int port) { + int ret; char nt[OS_SIZE_1024 +1]; if(proto == IPPROTO_TCP) @@ -53,10 +55,17 @@ int run_netstat(int proto, int port) return(0); } - if(system(nt) == 0) + ret = system(nt); + + if(ret == 0) return(1); - - return(0); + + else if(ret == 1) + { + return(0); + } + + return(1); } @@ -83,7 +92,7 @@ int conn_port(int proto, int port) server.sin_port = htons( port ); server.sin_addr.s_addr = htonl(INADDR_ANY); - + /* If we can't bind, it means the port is open */ if(bind(ossock, (struct sockaddr *) &server, sizeof(server)) < 0) { @@ -99,10 +108,10 @@ int conn_port(int proto, int port) { total_ports_udp[port] = rc; } - - close(ossock); - return(rc); + close(ossock); + + return(rc); } @@ -121,7 +130,7 @@ void test_ports(int proto, int *_errors, int *_total) if(run_netstat(proto, i)) { continue; - + #ifdef OSSECHIDS sleep(2); #endif @@ -140,7 +149,7 @@ void test_ports(int proto, int *_errors, int *_total) snprintf(op_msg, OS_SIZE_1024, "Port '%d'(%s) hidden. " "Kernel-level rootkit or trojaned " - "version of netstat.", i, + "version of netstat.", i, (proto == IPPROTO_UDP)? "udp" : "tcp"); notify_rk(ALERT_ROOTKIT_FOUND, op_msg); @@ -178,8 +187,8 @@ void check_rc_ports() total_ports_udp[i] = 0; i++; } - - /* Trsting TCP ports */ + + /* Trsting TCP ports */ test_ports(IPPROTO_TCP, &_errors, &_total); /* Testing UDP ports */ @@ -193,7 +202,7 @@ void check_rc_ports() " Analyzed %d ports.", _total); notify_rk(ALERT_OK, op_msg); } - + return; } diff --git a/src/rootcheck/check_rc_readproc.c b/src/rootcheck/check_rc_readproc.c index d136d6e..6cc763e 100755 --- a/src/rootcheck/check_rc_readproc.c +++ b/src/rootcheck/check_rc_readproc.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/rootcheck/check_rc_readproc.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -9,7 +10,7 @@ * Foundation */ - + #ifndef WIN32 #include "shared.h" #include "rootcheck.h" @@ -28,18 +29,18 @@ int read_proc_dir(char *dir_name, char *pid, int position); int read_proc_file(char *file_name, char *pid, int position) { struct stat statbuf; - + if(lstat(file_name, &statbuf) < 0) { return(-1); } - + /* If directory, read the directory */ else if(S_ISDIR(statbuf.st_mode)) { return(read_proc_dir(file_name, pid, position)); } - + return(0); } @@ -49,16 +50,16 @@ int read_proc_file(char *file_name, char *pid, int position) int read_proc_dir(char *dir_name, char *pid, int position) { DIR *dp; - + struct dirent *entry; - + if((dir_name == NULL)||(strlen(dir_name) > PATH_MAX)) { merror("%s: Invalid directory given",ARGV0); return(-1); } - + /* Opening the directory given */ dp = opendir(dir_name); if(!dp) @@ -72,7 +73,7 @@ int read_proc_dir(char *dir_name, char *pid, int position) /* Just ignore . and .. */ if((strcmp(entry->d_name,".") == 0) || - (strcmp(entry->d_name,"..") == 0)) + (strcmp(entry->d_name,"..") == 0)) continue; if(position == PROC) @@ -90,8 +91,8 @@ int read_proc_dir(char *dir_name, char *pid, int position) if(*tmp_str != '\0') continue; - - + + snprintf(f_name, PATH_MAX +1, "%s/%s",dir_name, entry->d_name); read_proc_file(f_name, pid, position+1); @@ -122,7 +123,7 @@ int read_proc_dir(char *dir_name, char *pid, int position) } closedir(dp); - + return(0); } @@ -136,17 +137,17 @@ int check_rc_readproc(int pid) char char_pid[32]; proc_pid_found = 0; - - /* NL threads */ + + /* NL threads */ snprintf(char_pid, 31, "/proc/.%d", pid); if(is_file(char_pid)) return(1); - - + + snprintf(char_pid, 31, "%d", pid); - + read_proc_dir("/proc", char_pid, PROC); - + return(proc_pid_found); } diff --git a/src/rootcheck/check_rc_sys.c b/src/rootcheck/check_rc_sys.c index b7b34ef..1e1761f 100755 --- a/src/rootcheck/check_rc_sys.c +++ b/src/rootcheck/check_rc_sys.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/rootcheck/check_rc_sys.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -10,7 +11,7 @@ */ -#include "shared.h" +#include "shared.h" #include "rootcheck.h" int _sys_errors; @@ -27,7 +28,7 @@ int read_sys_dir(char *dir_name, int do_read); int read_sys_file(char *file_name, int do_read) { struct stat statbuf; - + _sys_total++; @@ -51,7 +52,7 @@ int read_sys_file(char *file_name, int do_read) #endif return(-1); } - + /* If directory, read the directory */ else if(S_ISDIR(statbuf.st_mode)) { @@ -114,19 +115,19 @@ int read_sys_file(char *file_name, int do_read) } } } - - + + /* If has OTHER write and exec permission, alert */ #ifndef WIN32 - if(((statbuf.st_mode & S_IWOTH) == S_IWOTH) && + if(((statbuf.st_mode & S_IWOTH) == S_IWOTH) && (S_ISREG(statbuf.st_mode))) { if((statbuf.st_mode & S_IXUSR) == S_IXUSR) { if(_wx) fprintf(_wx, "%s\n",file_name); - - _sys_errors++; + + _sys_errors++; } else { @@ -172,16 +173,16 @@ int read_sys_dir(char *dir_name, int do_read) unsigned int entry_count = 0; int did_changed = 0; DIR *dp; - + struct dirent *entry; struct stat statbuf; - + #ifndef WIN32 char *(dirs_to_doread[]) = { "/bin", "/sbin", "/usr/bin", - "/usr/sbin", "/dev", "/etc", + "/usr/sbin", "/dev", "/etc", "/boot", NULL }; #endif - + if((dir_name == NULL)||(strlen(dir_name) > PATH_MAX)) { merror("%s: Invalid directory given.",ARGV0); @@ -203,8 +204,8 @@ int read_sys_dir(char *dir_name, int do_read) i = 0; } - - + + /* Getting the number of nodes. The total number on opendir * must be the same */ @@ -212,8 +213,8 @@ int read_sys_dir(char *dir_name, int do_read) { return(-1); } - - + + /* Currently device id */ if(did != statbuf.st_dev) { @@ -221,13 +222,13 @@ int read_sys_dir(char *dir_name, int do_read) did_changed = 1; did = statbuf.st_dev; } - - + + if(!S_ISDIR(statbuf.st_mode)) { return(-1); } - + #ifndef WIN32 /* Check if the do_read is valid for this directory */ @@ -243,14 +244,14 @@ int read_sys_dir(char *dir_name, int do_read) #else do_read = 0; #endif - - + + /* Opening the directory given */ dp = opendir(dir_name); if(!dp) { if((strcmp(dir_name, "") == 0)&& - (dp = opendir("/"))) + (dp = opendir("/"))) { /* ok */ } @@ -269,7 +270,7 @@ int read_sys_dir(char *dir_name, int do_read) /* Just ignore . and .. */ if((strcmp(entry->d_name,".") == 0) || - (strcmp(entry->d_name,"..") == 0)) + (strcmp(entry->d_name,"..") == 0)) { entry_count++; continue; @@ -294,7 +295,7 @@ int read_sys_dir(char *dir_name, int do_read) #ifndef Darwin if(S_ISDIR(statbuf_local.st_mode)) #else - if(S_ISDIR(statbuf_local.st_mode) || + if(S_ISDIR(statbuf_local.st_mode) || S_ISREG(statbuf_local.st_mode) || S_ISLNK(statbuf_local.st_mode)) #endif @@ -303,7 +304,7 @@ int read_sys_dir(char *dir_name, int do_read) } } - + /* Checking every file against the rootkit database */ for(i = 0; i<= rk_sys_count; i++) { @@ -333,15 +334,15 @@ int read_sys_dir(char *dir_name, int do_read) /* Entry count for directory different than the actual * link count from stats. */ - if((entry_count != statbuf.st_nlink) && + if((entry_count != statbuf.st_nlink) && ((did_changed == 0) || ((entry_count + 1) != statbuf.st_nlink))) { #ifndef WIN32 struct stat statbuf2; char op_msg[OS_SIZE_1024 +1]; - - if((lstat(dir_name, &statbuf2) == 0) && + + if((lstat(dir_name, &statbuf2) == 0) && (statbuf2.st_nlink != entry_count)) { snprintf(op_msg, OS_SIZE_1024, "Files hidden inside directory " @@ -361,7 +362,7 @@ int read_sys_dir(char *dir_name, int do_read) { notify_rk(ALERT_ROOTKIT_FOUND, op_msg); _sys_errors++; - } + } #else notify_rk(ALERT_ROOTKIT_FOUND, op_msg); @@ -371,9 +372,9 @@ int read_sys_dir(char *dir_name, int do_read) #endif } - + closedir(dp); - + return(0); } @@ -390,7 +391,7 @@ void check_rc_sys(char *basedir) _sys_errors = 0; _sys_total = 0; did = 0; /* device id */ - + snprintf(file_path, OS_SIZE_1024, "%s", basedir); @@ -409,9 +410,9 @@ void check_rc_sys(char *basedir) } - + /* Scan the whole file system -- may be slow */ - if(rootcheck.scanall) + if(rootcheck.scanall) { #ifndef WIN32 snprintf(file_path, 3, "%s", "/"); @@ -420,43 +421,43 @@ void check_rc_sys(char *basedir) read_sys_dir(file_path, rootcheck.readall); } - + /* Scan only specific directories */ else { int _i = 0; - + #ifndef WIN32 char *(dirs_to_scan[]) = {"/bin", "/sbin", "/usr/bin", "/usr/sbin", "/dev", "/lib", "/etc", "/root", "/var/log", "/var/mail", "/var/lib", "/var/www", "/usr/lib", "/usr/include", - "/tmp", "/boot", "/usr/local", + "/tmp", "/boot", "/usr/local", "/var/tmp", "/sys", NULL}; #else char *(dirs_to_scan[]) = {"C:\\WINDOWS", "C:\\Program Files", NULL}; #endif - + for(_i = 0; _i <= 24; _i++) { if(dirs_to_scan[_i] == NULL) break; - - #ifndef WIN32 - snprintf(file_path, OS_SIZE_1024, "%s%s", - basedir, + + #ifndef WIN32 + snprintf(file_path, OS_SIZE_1024, "%s%s", + basedir, dirs_to_scan[_i]); read_sys_dir(file_path, rootcheck.readall); #else read_sys_dir(dirs_to_scan[_i], rootcheck.readall); #endif - + } } - + if(_sys_errors == 0) { char op_msg[OS_SIZE_1024 +1]; @@ -470,13 +471,13 @@ void check_rc_sys(char *basedir) char op_msg[OS_SIZE_1024 +1]; snprintf(op_msg, OS_SIZE_1024, "Check the following files for more " "information:\n%s%s%s", - (ftell(_wx) == 0)?"": + (ftell(_wx) == 0)?"": " rootcheck-rw-rw-rw-.txt (list of world writable files)\n", (ftell(_ww) == 0)?"": " rootcheck-rwxrwxrwx.txt (list of world writtable/executable files)\n", - (ftell(_suid) == 0)?"": + (ftell(_suid) == 0)?"": " rootcheck-suid-files.txt (list of suid files)"); - + notify_rk(ALERT_SYSTEM_ERROR, op_msg); } @@ -486,21 +487,21 @@ void check_rc_sys(char *basedir) unlink("rootcheck-rw-rw-rw-.txt"); fclose(_wx); } - + if(_ww) { if(ftell(_ww) == 0) unlink("rootcheck-rwxrwxrwx.txt"); fclose(_ww); } - + if(_suid) { if(ftell(_suid) == 0) unlink("rootcheck-suid-files.txt"); - fclose(_suid); + fclose(_suid); } - + return; } diff --git a/src/rootcheck/check_rc_trojans.c b/src/rootcheck/check_rc_trojans.c index 40b16ed..1ee24ef 100755 --- a/src/rootcheck/check_rc_trojans.c +++ b/src/rootcheck/check_rc_trojans.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/rootcheck/check_rc_trojans.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -9,7 +10,7 @@ * Foundation */ - + #include "shared.h" #include "rootcheck.h" @@ -53,7 +54,7 @@ void check_rc_trojans(char *basedir, FILE *fp) /* Normalizing line */ nbuf = normalize_string(buf); - + if(*nbuf == '\0' || *nbuf == '#') { @@ -69,7 +70,7 @@ void check_rc_trojans(char *basedir, FILE *fp) { continue; } - + *string_to_look = '\0'; string_to_look++; @@ -80,26 +81,26 @@ void check_rc_trojans(char *basedir, FILE *fp) } *message = '\0'; message++; - + string_to_look = normalize_string(string_to_look); file = normalize_string(file); message = normalize_string(message); - - + + if(*file == '\0' || *string_to_look == '\0') { continue; } - + _total++; - - + + /* Trying with all possible paths */ while(all_paths[i] != NULL) { if(*file != '/') { - snprintf(file_path, OS_SIZE_1024, "%s/%s/%s",basedir, + snprintf(file_path, OS_SIZE_1024, "%s/%s/%s",basedir, all_paths[i], file); } @@ -108,15 +109,15 @@ void check_rc_trojans(char *basedir, FILE *fp) strncpy(file_path, file, OS_SIZE_1024); file_path[OS_SIZE_1024 -1] = '\0'; } - + /* Checking if entry is found */ if(is_file(file_path) && os_string(file_path, string_to_look)) { char op_msg[OS_SIZE_1024 +1]; _errors = 1; - + snprintf(op_msg, OS_SIZE_1024, "Trojaned version of file " - "'%s' detected. Signature used: '%s' (%s).", + "'%s' detected. Signature used: '%s' (%s).", file_path, string_to_look, *message == '\0'? @@ -131,7 +132,7 @@ void check_rc_trojans(char *basedir, FILE *fp) } i++; } - continue; + continue; } diff --git a/src/rootcheck/common.c b/src/rootcheck/common.c index f5d6589..eec625a 100755 --- a/src/rootcheck/common.c +++ b/src/rootcheck/common.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/rootcheck/common.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -8,14 +9,14 @@ * License (version 2) as published by the FSF - Free Software * Foundation * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/main/license/ . */ - + #include "shared.h" #include "rootcheck.h" -#include "os_regex/os_regex.h" +#include "os_regex/os_regex.h" @@ -59,7 +60,7 @@ int rk_check_dir(char *dir, char *file, char *pattern) { /* Just ignore . and .. */ if((strcmp(entry->d_name,".") == 0) || - (strcmp(entry->d_name,"..") == 0)) + (strcmp(entry->d_name,"..") == 0)) { continue; } @@ -68,7 +69,7 @@ int rk_check_dir(char *dir, char *file, char *pattern) /* Creating new file + path string */ snprintf(f_name, PATH_MAX +1, "%s/%s",dir, entry->d_name); - + /* Checking if the read entry, matches the provided file name. */ if(strncasecmp(file, "r:", 2) == 0) { @@ -80,7 +81,7 @@ int rk_check_dir(char *dir, char *file, char *pattern) } } } - + /* Trying without regex. */ else { @@ -93,7 +94,7 @@ int rk_check_dir(char *dir, char *file, char *pattern) } } - + /* Checking if file is a directory */ if(lstat(f_name, &statbuf_local) == 0) { @@ -119,13 +120,13 @@ int rk_check_dir(char *dir, char *file, char *pattern) int rk_check_file(char *file, char *pattern) { char *split_file; - int full_negate = 0; - int pt_result = 0; - + int full_negate = 0; + int pt_result = 0; + FILE *fp; char buf[OS_SIZE_2048 +1]; - - + + /* If string is null, we don't match */ if(file == NULL) { @@ -145,7 +146,7 @@ int rk_check_file(char *file, char *pattern) /* Getting each file */ do { - + /* If we don't have a pattern, just check if the file/dir is there */ if(pattern == NULL) @@ -167,7 +168,7 @@ int rk_check_file(char *file, char *pattern) while(rootcheck.alert_msg[i] && (i < 255)) i++; - + if(!rootcheck.alert_msg[i]) os_strdup(_b_msg, rootcheck.alert_msg[i]); @@ -177,14 +178,14 @@ int rk_check_file(char *file, char *pattern) else { - full_negate = pt_check_negate(pattern); + full_negate = pt_check_negate(pattern); /* Checking for a content in the file */ - debug1("checking file: %s", file); + debug1("checking file: %s", file); fp = fopen(file, "r"); if(fp) { - debug1(" starting new file: %s", file); + debug1(" starting new file: %s", file); buf[OS_SIZE_2048] = '\0'; while(fgets(buf, OS_SIZE_2048, fp) != NULL) { @@ -210,7 +211,7 @@ int rk_check_file(char *file, char *pattern) /* Matched */ pt_result = pt_matches(buf, pattern); - debug1("Buf == \"%s\"", buf); + debug1("Buf == \"%s\"", buf); debug1("Pattern == \"%s\"", pattern); debug1("pt_result == %d and full_negate == %d", pt_result, full_negate); if((pt_result == 1 && full_negate == 0) ) @@ -227,7 +228,7 @@ int rk_check_file(char *file, char *pattern) _b_msg[OS_SIZE_1024] = '\0'; snprintf(_b_msg, OS_SIZE_1024, " File: %s.", file); - + /* Already present. */ if(_is_str_in_array(rootcheck.alert_msg, _b_msg)) { @@ -245,18 +246,18 @@ int rk_check_file(char *file, char *pattern) else if((pt_result == 0 && full_negate == 1) ) { /* found a full+negate match so no longer need to search - * break out of loop and amke sure the full negate does - * not alertin + * break out of loop and amke sure the full negate does + * not alertin */ debug1("found a complete match for full_negate"); - full_negate = 0; - break; + full_negate = 0; + break; } } fclose(fp); - if(full_negate == 1) + if(full_negate == 1) { debug1("full_negate alerting - file %s",file); int i = 0; @@ -266,7 +267,7 @@ int rk_check_file(char *file, char *pattern) _b_msg[OS_SIZE_1024] = '\0'; snprintf(_b_msg, OS_SIZE_1024, " File: %s.", file); - + /* Already present. */ if(_is_str_in_array(rootcheck.alert_msg, _b_msg)) { @@ -293,8 +294,8 @@ int rk_check_file(char *file, char *pattern) split_file++; } } - - + + }while(split_file); @@ -311,7 +312,7 @@ int pt_check_negate(char *pattern) char *mypattern = NULL; os_strdup(pattern, mypattern); char *tmp_pt = mypattern; - char *tmp_pattern = mypattern; + char *tmp_pattern = mypattern; char *tmp_ret = NULL; @@ -321,9 +322,9 @@ int pt_check_negate(char *pattern) tmp_pt = strchr(tmp_pattern, ' '); if(tmp_pt && tmp_pt[1] == '&' && tmp_pt[2] == '&' && tmp_pt[3] == ' ') { - /* Marking pointer to clean it up */ + /* Marking pointer to clean it up */ tmp_ret = tmp_pt; - + *tmp_pt = '\0'; tmp_pt += 4; } @@ -337,7 +338,7 @@ int pt_check_negate(char *pattern) free(mypattern); return 0; } - + tmp_pattern = tmp_pt; } @@ -352,7 +353,7 @@ int pt_check_negate(char *pattern) * =: (for equal) - default - strcasecmp * r: (for ossec regexes) * >: (for strcmp greater) - * <: (for strcmp lower) + * <: (for strcmp lower) * * Multiple patterns can be specified by using " && " between them. * All of them must match for it to return true. @@ -370,16 +371,16 @@ int pt_matches(char *str, char *pattern) { return(0); } - + while(tmp_pt != NULL) { /* We first look for " && " */ tmp_pt = strchr(pattern, ' '); if(tmp_pt && tmp_pt[1] == '&' && tmp_pt[2] == '&' && tmp_pt[3] == ' ') { - /* Marking pointer to clean it up */ + /* Marking pointer to clean it up */ tmp_ret = tmp_pt; - + *tmp_pt = '\0'; tmp_pt += 4; } @@ -397,7 +398,7 @@ int pt_matches(char *str, char *pattern) pattern++; neg = 1; } - + /* Doing strcasecmp */ if(strncasecmp(pattern, "=:", 2) == 0) @@ -437,7 +438,7 @@ int pt_matches(char *str, char *pattern) { #ifdef WIN32 char final_file[2048 +1]; - + /* Try to get Windows variable */ if(*pattern == '%') { @@ -456,7 +457,7 @@ int pt_matches(char *str, char *pattern) { ret_code = 1; } - + #else if(strcasecmp(pattern, str) == 0) { @@ -473,7 +474,7 @@ int pt_matches(char *str, char *pattern) tmp_ret = NULL; } - + /* If we have "!", return true if we don't match */ if(neg == 1) { @@ -491,7 +492,7 @@ int pt_matches(char *str, char *pattern) break; } } - + ret_code = 1; pattern = tmp_pt; } @@ -507,8 +508,22 @@ int pt_matches(char *str, char *pattern) */ char *normalize_string(char *str) { - int str_sz = strlen(str) -1; - + unsigned int str_sz = strlen(str); + // return zero-length str as is + if (str_sz == 0) { + return str; + } else { + str_sz--; + } + // remove trailing spaces + while(str[str_sz] == ' ' || str[str_sz] == '\t') + { + if(str_sz == 0) + break; + + str[str_sz--] = '\0'; + } + // ignore leading spaces while(*str != '\0') { if(*str == ' ' || *str == '\t') @@ -521,17 +536,13 @@ char *normalize_string(char *str) } } - while(str[str_sz] == ' ' || str[str_sz] == '\t') - { - str[str_sz] = '\0'; - str_sz--; - } - return(str); } + + /** int isfile_ondir(char *file, char *dir) * Checks is 'file' is present on 'dir' using readdir */ @@ -540,7 +551,7 @@ int isfile_ondir(char *file, char *dir) DIR *dp = NULL; struct dirent *entry; dp = opendir(dir); - + if(!dp) return(0); @@ -552,7 +563,7 @@ int isfile_ondir(char *file, char *dir) return(1); } } - + closedir(dp); return(0); } @@ -565,19 +576,19 @@ int isfile_ondir(char *file, char *dir) int is_file(char *file_name) { int ret = 0; - + struct stat statbuf; FILE *fp = NULL; DIR *dp = NULL; #ifndef WIN32 - + char curr_dir[1024]; - + char *file_dirname; char *file_basename; - + curr_dir[1023] = '\0'; @@ -594,7 +605,7 @@ int is_file(char *file_name) return(0); } - + /* If file_basename == file_name, then the file * only has one slash at the beginning. */ @@ -655,7 +666,7 @@ int is_file(char *file_name) ret = 1; } } - + #else dp = opendir(file_name); if(dp) @@ -663,10 +674,10 @@ int is_file(char *file_name) closedir(dp); ret = 1; } - + #endif /* WIN32 */ - + /* Trying other calls */ if( (stat(file_name, &statbuf) < 0) && #ifndef WIN32 @@ -680,7 +691,7 @@ int is_file(char *file_name) /* must close it over here */ if(fp) fclose(fp); - + return(1); } @@ -715,7 +726,7 @@ int del_plist(void *p_list_p) { free(pinfo->p_path); } - + free(l_node->data); if(p_node) @@ -771,7 +782,7 @@ int is_process(char *value, void *p_list_p) char _b_msg[OS_SIZE_1024 +1]; _b_msg[OS_SIZE_1024] = '\0'; - + snprintf(_b_msg, OS_SIZE_1024, " Process: %s.", pinfo->p_path); @@ -780,7 +791,7 @@ int is_process(char *value, void *p_list_p) { return(1); } - + while(rootcheck.alert_msg[i] && (i< 255)) i++; @@ -796,7 +807,7 @@ int is_process(char *value, void *p_list_p) return(0); } - - + + /* EOF */ diff --git a/src/rootcheck/common_rcl.c b/src/rootcheck/common_rcl.c index ec72472..3677d78 100755 --- a/src/rootcheck/common_rcl.c +++ b/src/rootcheck/common_rcl.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/rootcheck/common_rcl.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -8,11 +9,11 @@ * License (version 2) as published by the FSF - Free Software * Foundation * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/main/license/ */ - + #include "shared.h" #include "rootcheck.h" @@ -26,7 +27,7 @@ #define RKCL_COND_ALL 0x001 #define RKCL_COND_ANY 0x002 #define RKCL_COND_REQ 0x004 -#define RKCL_COND_INV 0x010 +#define RKCL_COND_INV 0x010 @@ -40,7 +41,7 @@ char *_rkcl_getrootdir(char *root_dir, int dir_size) final_file[0] = '\0'; final_file[2048] = '\0'; - + ExpandEnvironmentStrings("%WINDIR%", final_file, 2047); tmp = strchr(final_file, '\\'); @@ -50,7 +51,7 @@ char *_rkcl_getrootdir(char *root_dir, int dir_size) strncpy(root_dir, final_file, dir_size); return(root_dir); } - + return(NULL); #endif @@ -132,7 +133,7 @@ int _rkcl_get_vars(OSStore *vars, char *nbuf) char *var_name; char *var_value; char *tmp; - + /* If not a variable, return 0 */ if(*nbuf != '$') { @@ -150,7 +151,7 @@ int _rkcl_get_vars(OSStore *vars, char *nbuf) { return(-1); } - + /* Getting value. */ tmp = strchr(nbuf, '='); @@ -183,7 +184,7 @@ char *_rkcl_get_name(char *buf, char *ref, int *condition) { char *tmp_location; char *tmp_location2; - + *condition = 0; /* Checking if name is valid */ @@ -200,8 +201,8 @@ char *_rkcl_get_name(char *buf, char *ref, int *condition) return(NULL); } *tmp_location = '\0'; - - + + /* Getting condition */ tmp_location++; if(*tmp_location != ' ' && tmp_location[1] != '[') @@ -217,8 +218,8 @@ char *_rkcl_get_name(char *buf, char *ref, int *condition) } *tmp_location2 = '\0'; tmp_location2++; - - + + /* Getting condition */ if(strcmp(tmp_location, "all") == 0) { @@ -260,7 +261,7 @@ char *_rkcl_get_name(char *buf, char *ref, int *condition) *tmp_location = '\0'; /* Copying reference */ - strncpy(ref, tmp_location2, 255); + strncpy(ref, tmp_location2, 255); return(strdup(buf)); } @@ -309,21 +310,21 @@ char *_rkcl_get_value(char *buf, int *type) *value = '\0'; value++; - + tmp_str = strchr(value, ';'); if(tmp_str == NULL) { return(NULL); } *tmp_str = '\0'; - + /* Getting types - removing negate flag (using later) */ if(*buf == '!') { buf++; } - + if(strcmp(buf, "f") == 0) { *type = RKCL_TYPE_FILE; @@ -374,7 +375,7 @@ int rkcl_get_entry(FILE *fp, char *msg, void *p_list_p) memset(final_file, '\0', sizeof(final_file)); memset(ref, '\0', sizeof(ref)); - + root_dir_len = sizeof(root_dir) -1; @@ -383,14 +384,14 @@ int rkcl_get_entry(FILE *fp, char *msg, void *p_list_p) _rkcl_getrootdir(root_dir, root_dir_len); if(root_dir[0] == '\0') { - merror(INVALID_ROOTDIR, ARGV0); + merror(INVALID_ROOTDIR, ARGV0); } - #endif + #endif /* Getting variables */ vars = OSStore_Create(); - + /* We first read all variables -- they must be defined at the top. */ while(1) @@ -422,15 +423,15 @@ int rkcl_get_entry(FILE *fp, char *msg, void *p_list_p) merror(INVALID_RKCL_NAME, ARGV0, nbuf); goto clean_return; } - + /* Getting the real entries. */ do { int g_found = 0; - - + + /* Getting entry name */ if(name == NULL) { @@ -447,21 +448,21 @@ int rkcl_get_entry(FILE *fp, char *msg, void *p_list_p) int negate = 0; int found = 0; value = NULL; - + nbuf = _rkcl_getfp(fp, buf); if(nbuf == NULL) { break; } - + /* We first try to get the name, looking for new entries */ if(_rkcl_is_name(nbuf)) { break; } - - + + /* Getting value to look for */ value = _rkcl_get_value(nbuf, &type); if(value == NULL) @@ -500,15 +501,15 @@ int rkcl_get_entry(FILE *fp, char *msg, void *p_list_p) continue; } } - + #ifdef WIN32 else if(value[0] == '\\') { final_file[0] = '\0'; final_file[sizeof(final_file) -1] = '\0'; - - snprintf(final_file, sizeof(final_file) -2, "%s%s", + + snprintf(final_file, sizeof(final_file) -2, "%s%s", root_dir, value); f_value = final_file; } @@ -516,8 +517,8 @@ int rkcl_get_entry(FILE *fp, char *msg, void *p_list_p) { final_file[0] = '\0'; final_file[sizeof(final_file) -1] = '\0'; - - ExpandEnvironmentStrings(value, final_file, + + ExpandEnvironmentStrings(value, final_file, sizeof(final_file) -2); f_value = final_file; } @@ -531,15 +532,15 @@ int rkcl_get_entry(FILE *fp, char *msg, void *p_list_p) found = 1; } } - + /* Checking for a registry entry */ else if(type == RKCL_TYPE_REGISTRY) { char *entry = NULL; char *pattern = NULL; - - + + /* Looking for additional entries in the registry * and a pattern to match. */ @@ -548,8 +549,8 @@ int rkcl_get_entry(FILE *fp, char *msg, void *p_list_p) { pattern = _rkcl_get_pattern(entry); } - - + + #ifdef WIN32 debug2("%s: DEBUG: Checking registry: '%s'.", ARGV0, value); if(is_registry(value, entry, pattern)) @@ -569,7 +570,7 @@ int rkcl_get_entry(FILE *fp, char *msg, void *p_list_p) char *f_value = NULL; char *dir = NULL; - + file = _rkcl_get_pattern(value); if(file) { @@ -592,7 +593,7 @@ int rkcl_get_entry(FILE *fp, char *msg, void *p_list_p) f_value = value; } - + /* Checking for multiple, comma separated directories. */ dir = f_value; f_value = strchr(dir, ','); @@ -600,7 +601,7 @@ int rkcl_get_entry(FILE *fp, char *msg, void *p_list_p) { *f_value = '\0'; } - + while(dir) { @@ -610,14 +611,14 @@ int rkcl_get_entry(FILE *fp, char *msg, void *p_list_p) debug2("%s: DEBUG: Found dir.", ARGV0); found = 1; } - + if(f_value) { *f_value = ','; f_value++; - + dir = f_value; - + f_value = strchr(dir, ','); if(f_value) { @@ -630,7 +631,7 @@ int rkcl_get_entry(FILE *fp, char *msg, void *p_list_p) } } } - + /* Checking for a process. */ else if(type == RKCL_TYPE_PROCESS) @@ -681,8 +682,8 @@ int rkcl_get_entry(FILE *fp, char *msg, void *p_list_p) } } }while(value != NULL); - - + + /* Alerting if necessary */ if(g_found == 1) { @@ -690,18 +691,18 @@ int rkcl_get_entry(FILE *fp, char *msg, void *p_list_p) char op_msg[OS_SIZE_1024 +1]; char **p_alert_msg = rootcheck.alert_msg; - while(1) + while(1) { if(ref[0] != '\0') { snprintf(op_msg, OS_SIZE_1024, "%s %s.%s" - " Reference: %s .",msg, name, + " Reference: %s .",msg, name, p_alert_msg[j]?p_alert_msg[j]:"\0", ref); } else { - snprintf(op_msg, OS_SIZE_1024, "%s %s.%s",msg, + snprintf(op_msg, OS_SIZE_1024, "%s %s.%s",msg, name, p_alert_msg[j]?p_alert_msg[j]:"\0"); } @@ -742,7 +743,7 @@ int rkcl_get_entry(FILE *fp, char *msg, void *p_list_p) goto clean_return; } } - + /* Ending if we don't have anything else. */ if(!nbuf) @@ -757,7 +758,7 @@ int rkcl_get_entry(FILE *fp, char *msg, void *p_list_p) free(name); name = NULL; } - + /* Getting name already read */ name = _rkcl_get_name(nbuf, ref, &condition); @@ -778,8 +779,8 @@ int rkcl_get_entry(FILE *fp, char *msg, void *p_list_p) name = NULL; } vars = OSStore_Free(vars); - - + + return(1); } diff --git a/src/rootcheck/config.c b/src/rootcheck/config.c index b04d492..9cf9e6c 100755 --- a/src/rootcheck/config.c +++ b/src/rootcheck/config.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/rootcheck/config.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -33,7 +34,7 @@ int Read_Rootcheck_Config(char * cfgfile) modules|= CAGENT_CONFIG; ReadConfig(modules, AGENTCONFIG, &rootcheck, NULL); #endif - + return(0); } diff --git a/src/rootcheck/db/cis_debian_linux_rcl.txt b/src/rootcheck/db/cis_debian_linux_rcl.txt index 9c87619..e9d0d56 100644 --- a/src/rootcheck/db/cis_debian_linux_rcl.txt +++ b/src/rootcheck/db/cis_debian_linux_rcl.txt @@ -1,4 +1,5 @@ -# @(#) $Id$ +# @(#) $Id: ./src/rootcheck/db/cis_debian_linux_rcl.txt, 2011/09/08 dcid Exp $ + # # OSSEC Linux Audit - (C) 2008 Daniel B. Cid - dcid@ossec.net # @@ -70,19 +71,19 @@ f:/etc/ssh/sshd_config -> !r:^# && r:PermitRootLogin\.+yes; # Section 2.4 Enable system accounting -[CIS - Debian Linux 2.4 - System Accounting - Sysstat not installed] [all] [http://www.ossec.net/wiki/index.php/CIS_DebianLinux] -f:!/etc/default/sysstat; -f:!/var/log/sysstat; +#[CIS - Debian Linux 2.4 - System Accounting - Sysstat not installed] [all] [http://www.ossec.net/wiki/index.php/CIS_DebianLinux] +#f:!/etc/default/sysstat; +#f:!/var/log/sysstat; -[CIS - Debian Linux 2.4 - System Accounting - Sysstat not enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_DebianLinux] -f:!/etc/default/sysstat; -f:/etc/default/sysstat -> !r:^# && r:ENABLED="false"; +#[CIS - Debian Linux 2.4 - System Accounting - Sysstat not enabled] [any] [http://www.ossec.net/wiki/index.php/CIS_DebianLinux] +#f:!/etc/default/sysstat; +#f:/etc/default/sysstat -> !r:^# && r:ENABLED="false"; # Section 2.5 Install and run Bastille -[CIS - Debian Linux 2.5 - System harderning - Bastille is not installed] [any] [http://www.ossec.net/wiki/index.php/CIS_DebianLinux] -f:!/etc/Bastille; +#[CIS - Debian Linux 2.5 - System harderning - Bastille is not installed] [any] [http://www.ossec.net/wiki/index.php/CIS_DebianLinux] +#f:!/etc/Bastille; diff --git a/src/rootcheck/db/cis_rhel5_linux_rcl.txt b/src/rootcheck/db/cis_rhel5_linux_rcl.txt index 75c6b3e..20f1329 100644 --- a/src/rootcheck/db/cis_rhel5_linux_rcl.txt +++ b/src/rootcheck/db/cis_rhel5_linux_rcl.txt @@ -1,4 +1,5 @@ -# @(#) $Id$ +# @(#) $Id: ./src/rootcheck/db/cis_rhel5_linux_rcl.txt, 2011/09/08 dcid Exp $ + # # OSSEC Linux Audit - (C) 2008 Daniel B. Cid - dcid@ossec.net # @@ -69,8 +70,8 @@ f:/etc/ssh/sshd_config -> !r:^# && r:PermitRootLogin\.+yes; # Section 2.4 Enable system accounting -[CIS - RHEL5 2.4 - System Accounting - Sysstat not installed] [all] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] -f:!/var/log/sa; +#[CIS - RHEL5 2.4 - System Accounting - Sysstat not installed] [all] [http://www.ossec.net/wiki/index.php/CIS_RHEL5] +#f:!/var/log/sa; diff --git a/src/rootcheck/db/cis_rhel_linux_rcl.txt b/src/rootcheck/db/cis_rhel_linux_rcl.txt index 976ee6f..6a34cb4 100644 --- a/src/rootcheck/db/cis_rhel_linux_rcl.txt +++ b/src/rootcheck/db/cis_rhel_linux_rcl.txt @@ -1,4 +1,5 @@ -# @(#) $Id$ +# @(#) $Id: ./src/rootcheck/db/cis_rhel_linux_rcl.txt, 2011/09/08 dcid Exp $ + # # OSSEC Linux Audit - (C) 2008 Daniel B. Cid - dcid@ossec.net # @@ -79,14 +80,14 @@ f:/etc/ssh/sshd_config -> !r:^# && r:PermitRootLogin\.+yes; # Section 1.4 Enable system accounting -[CIS - Red Hat Linux 1.4 - System Accounting - Sysstat not installed] [all] [http://www.ossec.net/wiki/index.php/CIS_RHEL] -f:!/var/log/sa; +#[CIS - Red Hat Linux 1.4 - System Accounting - Sysstat not installed] [all] [http://www.ossec.net/wiki/index.php/CIS_RHEL] +#f:!/var/log/sa; # Section 2.5 Install and run Bastille -[CIS - Red Hat Linux 1.5 - System harderning - Bastille is not installed] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL] -f:!/etc/Bastille; +#[CIS - Red Hat Linux 1.5 - System harderning - Bastille is not installed] [any] [http://www.ossec.net/wiki/index.php/CIS_RHEL] +#f:!/etc/Bastille; diff --git a/src/rootcheck/db/rootkit_files.txt b/src/rootcheck/db/rootkit_files.txt index efdbd21..3e6e466 100755 --- a/src/rootcheck/db/rootkit_files.txt +++ b/src/rootcheck/db/rootkit_files.txt @@ -1,4 +1,5 @@ -# @(#) $Id$ +# @(#) $Id: ./src/rootcheck/db/rootkit_files.txt, 2011/09/08 dcid Exp $ + # # rootkit_files.txt, (C) Daniel B. Cid # Imported from the rootcheck project. @@ -372,8 +373,8 @@ dev/grid-unhide-port- ! Override rootkit ::/rootkits/override.php # PHALANX rootkit -usr/share/.home.ph1 ! PHALANX rootkit :: -usr/share/.home.ph1/tty ! PHALANX rootkit :: +usr/share/.home* ! PHALANX rootkit :: +usr/share/.home*/tty ! PHALANX rootkit :: etc/host.ph1 ! PHALANX rootkit :: bin/host.ph1 ! PHALANX rootkit :: diff --git a/src/rootcheck/db/rootkit_trojans.txt b/src/rootcheck/db/rootkit_trojans.txt index b2cfa86..523770c 100755 --- a/src/rootcheck/db/rootkit_trojans.txt +++ b/src/rootcheck/db/rootkit_trojans.txt @@ -1,4 +1,5 @@ -# @(#) $Id$ +# @(#) $Id: ./src/rootcheck/db/rootkit_trojans.txt, 2012/04/26 dcid Exp $ + # # rootkit_trojans.txt, (C) Daniel B. Cid # Imported from the rootcheck project. @@ -68,7 +69,7 @@ xinetd !bash|file\.h|proc\.h! in.telnetd !cterm100|vt350|VT100|ansi-term|bash|^/bin/sh|/dev[A-R]|/dev/[a-z]/! in.fingerd !bash|^/bin/sh|cterm100|/dev/! identd !bash|^/bin/sh|file\.h|proc\.h|/dev/[^n]|^/bin/.*sh! -init !bash|/dev/h|HOME! +init !bash|/dev/h tcpd !bash|proc\.h|p1r0c4|hack|/dev/[^n]! rlogin !p1r0c4|r00t|bash|/dev/[^nt]! @@ -80,8 +81,6 @@ kill !/dev/[ab,d-k,m-z]|/dev/[F-Z]|/dev/[A-D]|/dev/[0-9]|proc\.h|bash|tmp! # Rootkit entries -/sbin/init !HOME! Suckit rootkit -/proc/1/maps !init.! Suckit rootkit /etc/rc.d/rc.sysinit !enyelkmHIDE! enye-sec Rootkit diff --git a/src/rootcheck/db/system_audit_rcl.txt b/src/rootcheck/db/system_audit_rcl.txt index a0c6810..fb747c4 100644 --- a/src/rootcheck/db/system_audit_rcl.txt +++ b/src/rootcheck/db/system_audit_rcl.txt @@ -1,4 +1,5 @@ -# @(#) $Id$ +# @(#) $Id: ./src/rootcheck/db/system_audit_rcl.txt, 2012/02/13 dcid Exp $ + # # OSSEC Linux Audit - (C) 2007 Daniel B. Cid - dcid@ossec.net # @@ -45,10 +46,6 @@ f:$php.ini -> r:^expose_php = On; f:$php.ini -> r:^allow_url_fopen = On; -# PHP checks -[PHP - Safe mode disabled] [any] [] -f:$php.ini -> r:^safe_mode = Off; - # PHP checks [PHP - Displaying of errors is enabled] [any] [] @@ -60,116 +57,8 @@ f:$php.ini -> r:^display_errors = On; ## Looking for common web exploits (might indicate that you are owned). ## Using http://www.ossec.net/wiki/index.php/WebAttacks_links as a reference. -[Web exploits - Possible compromise] [any] [http://www.ossec.net/wiki/index.php/WebAttacks_links] -d:$web_dirs -> ^echo$ -> r: ^id.txt$ -> r: ^irc.txt$ -> r: ^stringa.txt -> r: ^cmd1.gif$ -> r: ^mambo1.txt$|^hai.txt$|^iyes.txt$ -> r: ^57.txt$ -> r: ^r57.txt -> r: ^evilx$ -> r: ^cmd$ -> r: ^root.gif -> r: ^bn.txt -> r: ^kk.txt -> r: ^graba.txt -> r: ^no.txt -> r: ^ddos.pl -> r: ^rox.txt -> r: ^lila.jpg -> r: ^safe.txt -> r: ^rootlab.jpg -> r: ^tool25.dat -> r: ^sela.txt -> r: ^zero.txt -> r: ^paged.gif -> r: ^hh.txt -> r: ^metodi.txt -> r: ^idpitbull.txt -> r: ^echo.txt -> r: ^ban.gif -> r: ^c.txt -> r: ^gay.txt -> r: ^genlog.txt$ -> r: ^safe$ -> r: ^safe3$ -> r: ^tool25.txt$ -> r: ^test.txt$ -> r: ^safeon.txt$ -> r: .txt$ -> r:^ ^...$; [Web exploits (uncommon file name inside htdocs) - Possible compromise] [any] [http://www.ossec.net/wiki/index.php/WebAttacks_links] d:$web_dirs -> ^.shell$; + +## Looking for outdated Web applications +## Taken from http://sucuri.net/latest-versions +[Web vulnerability - Outdated WordPress installation] [any] [http://sucuri.net/latest-versions] +d:$web_dirs -> ^version.php$ -> r:^\.wp_version && >:$wp_version = '3.2.1'; + +[Web vulnerability - Outdated Joomla (v1.0) installation] [any] [http://sucuri.net/latest-versions] +d:$web_dirs -> ^version.php$ -> r:var \.RELEASE && r:'1.0'; + +#[Web vulnerability - Outdated Joomla (v1.5) installation] [any] [http://sucuri.net/latest-versions] +#d:$web_dirs -> ^version.php$ -> r:var \.RELEASE && r:'1.5' && r:'23' + +[Web vulnerability - Outdated osCommerce (v2.2) installation] [any] [http://sucuri.net/latest-versions] +d:$web_dirs -> ^application_top.php$ -> r:'osCommerce 2.2-; + + +## Looking for known backdoors +[Web vulnerability - Backdoors / Web based malware found - eval(base64_decode] [any] [] +d:$web_dirs -> .php$ -> r:eval\(base64_decode\(\paWYo; + +[Web vulnerability - Backdoors / Web based malware found - eval(base64_decode(POST] [any] [] +d:$web_dirs -> .php$ -> r:eval\(base64_decode\(\S_POST; + +[Web vulnerability - .htaccess file compromised] [any] [http://blog.sucuri.net/2011/05/understanding-htaccess-attacks-part-1.html] +d:$web_dirs -> ^.htaccess$ -> r:RewriteCond \S+HTTP_REFERERS \S+google; + +[Web vulnerability - .htaccess file compromised - auto append] [any] [http://blog.sucuri.net/2011/05/understanding-htaccess-attacks-part-1.html] +d:$web_dirs -> ^.htaccess$ -> r:php_value auto_append_file; + + # EOF # diff --git a/src/rootcheck/db/win_applications_rcl.txt b/src/rootcheck/db/win_applications_rcl.txt index f4892b7..6ffd3e6 100644 --- a/src/rootcheck/db/win_applications_rcl.txt +++ b/src/rootcheck/db/win_applications_rcl.txt @@ -1,4 +1,5 @@ -# @(#) $Id$ +# @(#) $Id: ./src/rootcheck/db/win_applications_rcl.txt, 2011/09/08 dcid Exp $ + # # OSSEC Application detection - (C) 2007 Daniel B. Cid - dcid@ossec.net # diff --git a/src/rootcheck/db/win_audit_rcl.txt b/src/rootcheck/db/win_audit_rcl.txt index d9a165f..6ce8ddd 100644 --- a/src/rootcheck/db/win_audit_rcl.txt +++ b/src/rootcheck/db/win_audit_rcl.txt @@ -1,4 +1,5 @@ -# @(#) $Id$ +# @(#) $Id: ./src/rootcheck/db/win_audit_rcl.txt, 2011/09/08 dcid Exp $ + # # OSSEC Windows Audit - (C) 2007 Daniel B. Cid - dcid@ossec.net # diff --git a/src/rootcheck/db/win_malware_rcl.txt b/src/rootcheck/db/win_malware_rcl.txt index 7b8a768..d3dc72d 100644 --- a/src/rootcheck/db/win_malware_rcl.txt +++ b/src/rootcheck/db/win_malware_rcl.txt @@ -1,4 +1,5 @@ -# @(#) $Id$ +# @(#) $Id: ./src/rootcheck/db/win_malware_rcl.txt, 2011/09/08 dcid Exp $ + # # OSSEC Windows Malware list - (C) 2007 Daniel B. Cid - dcid@ossec.net # diff --git a/src/rootcheck/os_string.c b/src/rootcheck/os_string.c index a3ad59a..069f5bd 100755 --- a/src/rootcheck/os_string.c +++ b/src/rootcheck/os_string.c @@ -1,9 +1,10 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/rootcheck/os_string.c, 2011/09/08 dcid Exp $ + */ /* Included and modified strings.c from the OpenBSD project. * Copyright bellow. */ - + /* * Copyright (c) 1980, 1987, 1993 * The Regents of the University of California. All rights reserved. @@ -135,9 +136,9 @@ struct exec #ifdef AIX -typedef struct aouthdr EXEC; +typedef struct aouthdr EXEC; #else -typedef struct exec EXEC; +typedef struct exec EXEC; #endif typedef struct _os_strings @@ -161,25 +162,25 @@ int os_getch(os_strings *oss); int os_string(char *file, char *regex) { int ch, cnt; - + unsigned char *C; unsigned char *bfr; - + char line[OS_SIZE_1024 +1]; char *buf; - + EXEC *head; os_strings oss; - + /* Return didn't match */ if(!file || !regex) { return(0); } - - - /* Allocating for the buffer */ + + + /* Allocating for the buffer */ bfr = calloc(STR_MINLEN + 2, sizeof(char *)); if (!bfr) { @@ -197,21 +198,21 @@ int os_string(char *file, char *regex) /* cleaning the line */ memset(line, '\0', OS_SIZE_1024 +1); - + /* starting .. (from old strings.c) */ oss.foff = 0; oss.head_len = 0; - + oss.read_len = -1; head = (EXEC *)oss.hbfr; - + if ((oss.head_len = read(fileno(oss.fp), head, sizeof(EXEC))) == -1) { oss.head_len = 0; oss.read_len = -1; } - else if (oss.head_len == sizeof(EXEC) && !N_BADMAG(*head)) + else if (oss.head_len == sizeof(EXEC) && !N_BADMAG(*head)) { oss.foff = N_TXTOFF(*head); if (fseek(stdin, oss.foff, SEEK_SET) == -1) @@ -235,20 +236,20 @@ int os_string(char *file, char *regex) } /* Read the file and perform the regex comparison */ - for (cnt = 0; (ch = os_getch(&oss)) != EOF;) + for (cnt = 0; (ch = os_getch(&oss)) != EOF;) { - if (ISSTR(ch)) + if (ISSTR(ch)) { if (!cnt) C = bfr; *C++ = ch; if (++cnt < STR_MINLEN) continue; - + strncpy(line, (char *)bfr, STR_MINLEN +1); buf = line; buf+=strlen(line); - + while ((ch = os_getch(&oss)) != EOF && ISSTR(ch)) { @@ -293,7 +294,7 @@ int os_string(char *file, char *regex) int os_getch(os_strings *oss) { ++oss->foff; - if (oss->head_len) + if (oss->head_len) { if (oss->hcnt < oss->head_len) return((int)oss->hbfr[oss->hcnt++]); diff --git a/src/rootcheck/rootcheck-config.c b/src/rootcheck/rootcheck-config.c index 5553471..46ad77e 100755 --- a/src/rootcheck/rootcheck-config.c +++ b/src/rootcheck/rootcheck-config.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/rootcheck/rootcheck-config.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -23,6 +24,26 @@ #include "rootcheck.h" +/*evaluate boolean with two arguments + * str: input string, "yes"|"no" + * default_val: 1(yes)|0(no) + */ +short eval_bool2(char *str, short default_val) +{ + short ret = default_val; + + if (str == NULL) + return(ret); + else if (strcmp(str, "yes") == 0) + ret = 1; + else if (strcmp(str, "no") == 0) + ret = 0; + + free(str); + return(ret); +} + + /* Read_Rootcheck_Config: Reads the rootcheck config */ int Read_Rootcheck_Config(char * cfgfile) @@ -47,9 +68,29 @@ int Read_Rootcheck_Config(char * cfgfile) char *(xml_readall[])={xml_rootcheck, "readall", NULL}; char *(xml_time[])={xml_rootcheck, "frequency", NULL}; + char *(xml_check_dev[])={xml_rootcheck, "check_dev", NULL}; + char *(xml_check_files[])={xml_rootcheck, "check_files", NULL}; + char *(xml_check_if[])={xml_rootcheck, "check_if", NULL}; + char *(xml_check_pids[])={xml_rootcheck, "check_pids", NULL}; + char *(xml_check_ports[])={xml_rootcheck, "check_ports", NULL}; + char *(xml_check_sys[])={xml_rootcheck, "check_sys", NULL}; + char *(xml_check_trojans[])={xml_rootcheck, "check_trojans", NULL}; + + #ifdef WIN32 + + char *(xml_check_winapps[])={xml_rootcheck, "check_winapps", NULL}; + char *(xml_check_winaudit[])={xml_rootcheck, "check_winaudit", NULL}; + char *(xml_check_winmalware[])={xml_rootcheck, "check_winmalware", NULL}; + + #else + + char *(xml_check_unixaudit[])={xml_rootcheck, "check_unixaudit", NULL}; + + #endif + /* :) */ xml_time[2] = NULL; - + if(OS_ReadXML(cfgfile,&xml) < 0) { merror("config_op: XML error: %s",xml.err); @@ -65,14 +106,7 @@ int Read_Rootcheck_Config(char * cfgfile) /* run as a daemon */ - str = OS_GetOneContentforElement(&xml,xml_daemon); - if(str) - { - if(str[0] == 'n') - rootcheck.daemon = 0; - free(str); - str = NULL; - } + rootcheck.daemon = eval_bool2(OS_GetOneContentforElement(&xml,xml_daemon), rootcheck.daemon); /* time */ #ifdef OSSECHIDS @@ -92,36 +126,22 @@ int Read_Rootcheck_Config(char * cfgfile) str = NULL; } #endif - - + + /* Scan all flag */ if(!rootcheck.scanall) { - str = OS_GetOneContentforElement(&xml,xml_scanall); - if(str) - { - if(str[0] == 'y') - rootcheck.scanall = 1; - free(str); - str = NULL; - } + rootcheck.scanall = eval_bool2(OS_GetOneContentforElement(&xml,xml_scanall), 0); } /* read all flag */ if(!rootcheck.readall) { - str = OS_GetOneContentforElement(&xml,xml_readall); - if(str) - { - if(str[0] == 'y') - rootcheck.readall = 1; - free(str); - str = NULL; - } + rootcheck.readall = eval_bool2(OS_GetOneContentforElement(&xml,xml_readall), 0); } - - + + /* Notifications type */ str = OS_GetOneContentforElement(&xml,xml_notify); if(str) @@ -136,9 +156,9 @@ int Read_Rootcheck_Config(char * cfgfile) "'syslog' or 'queue' are allowed.",ARGV0); return(-1); } - + free(str); - str = NULL; + str = NULL; } else { @@ -148,15 +168,15 @@ int Read_Rootcheck_Config(char * cfgfile) /* Getting work directory */ if(!rootcheck.workdir) - rootcheck.workdir = OS_GetOneContentforElement(&xml,xml_workdir); - - + rootcheck.workdir = OS_GetOneContentforElement(&xml,xml_workdir); + + rootcheck.rootkit_files = OS_GetOneContentforElement (&xml,xml_rootkit_files); rootcheck.rootkit_trojans = OS_GetOneContentforElement (&xml,xml_rootkit_trojans); - - rootcheck.unixaudit = OS_GetContents + + rootcheck.unixaudit = OS_GetContents (&xml,xml_rootkit_unixaudit); rootcheck.winaudit = OS_GetOneContentforElement @@ -167,15 +187,34 @@ int Read_Rootcheck_Config(char * cfgfile) rootcheck.winmalware = OS_GetOneContentforElement (&xml,xml_rootkit_winmalware); - + rootcheck.basedir = OS_GetOneContentforElement(&xml, xml_base_dir); + rootcheck.checks.rc_dev = eval_bool2(OS_GetOneContentforElement(&xml,xml_check_dev), 1); + rootcheck.checks.rc_files = eval_bool2(OS_GetOneContentforElement(&xml,xml_check_files), 1); + rootcheck.checks.rc_if = eval_bool2(OS_GetOneContentforElement(&xml,xml_check_if), 1); + rootcheck.checks.rc_pids = eval_bool2(OS_GetOneContentforElement(&xml,xml_check_pids), 1); + rootcheck.checks.rc_ports = eval_bool2(OS_GetOneContentforElement(&xml,xml_check_ports), 1); + rootcheck.checks.rc_sys = eval_bool2(OS_GetOneContentforElement(&xml,xml_check_sys), 1); + rootcheck.checks.rc_trojans = eval_bool2(OS_GetOneContentforElement(&xml,xml_check_trojans), 1); + + #ifdef WIN32 + + rootcheck.checks.rc_winapps = eval_bool2(OS_GetOneContentforElement(&xml,xml_check_winapps), 1); + rootcheck.checks.rc_winaudit = eval_bool2(OS_GetOneContentforElement(&xml,xml_check_winaudit), 1); + rootcheck.checks.rc_winmalware = eval_bool2(OS_GetOneContentforElement(&xml,xml_check_winmalware), 1); + + #else + + rootcheck.checks.rc_unixaudit = eval_bool2(OS_GetOneContentforElement(&xml,xml_check_unixaudit), 1); + + #endif OS_ClearXML(&xml); - + debug1("%s: DEBUG: Daemon set to '%d'",ARGV0, rootcheck.daemon); debug1("%s: DEBUG: alert set to '%d'",ARGV0, rootcheck.notify); - + return(0); } diff --git a/src/rootcheck/rootcheck.c b/src/rootcheck/rootcheck.c index 83dfb5b..00831b6 100755 --- a/src/rootcheck/rootcheck.c +++ b/src/rootcheck/rootcheck.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/rootcheck/rootcheck.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation */ - + /* * Rootcheck v 0.3 * Copyright (C) 2003 Daniel B. Cid @@ -65,16 +66,16 @@ int main(int argc, char **argv) int rootcheck_init(int test_config) { int c; - -#endif - - #ifdef OSSECHIDS + +#endif + + #ifdef OSSECHIDS char *cfg = DEFAULTCPATH; #else char *cfg = "./rootcheck.conf"; #endif - - /* Zeroing the structure */ + + /* Zeroing the structure, initializing default values */ rootcheck.workdir = NULL; rootcheck.basedir = NULL; rootcheck.unixaudit = NULL; @@ -93,6 +94,26 @@ int rootcheck_init(int test_config) rootcheck.time = ROOTCHECK_WAIT; + rootcheck.checks.rc_dev = 1; + rootcheck.checks.rc_files = 1; + rootcheck.checks.rc_if = 1; + rootcheck.checks.rc_pids = 1; + rootcheck.checks.rc_ports = 1; + rootcheck.checks.rc_sys = 1; + rootcheck.checks.rc_trojans = 1; + + #ifdef WIN32 + + rootcheck.checks.rc_winaudit = 1; + rootcheck.checks.rc_winmalware = 1; + rootcheck.checks.rc_winapps = 1; + + #else + + rootcheck.checks.rc_unixaudit = 1; + + #endif + /* We store up to 255 alerts in there. */ os_calloc(256, sizeof(char *), rootcheck.alert_msg); c = 0; @@ -101,7 +122,7 @@ int rootcheck_init(int test_config) rootcheck.alert_msg[c] = NULL; c++; } - + #ifndef OSSECHIDS rootcheck.notify = SYSLOG; @@ -134,18 +155,18 @@ int rootcheck_init(int test_config) break; case 't': test_config = 1; - break; + break; case 'r': rootcheck.readall = 1; - break; + break; default: rootcheck_help(); - break; + break; } } - + #ifdef WIN32 /* Starting Winsock */ { @@ -156,10 +177,10 @@ int rootcheck_init(int test_config) } } #endif - - + + #endif /* OSSECHIDS */ - + /* Staring message */ debug1(STARTED_MSG,ARGV0); @@ -191,8 +212,8 @@ int rootcheck_init(int test_config) verbose("%s: Rootcheck disabled. Exiting.", ARGV0); return(1); } - - + + /* Checking if Unix audit file is configured. */ if(!rootcheck.unixaudit) { @@ -200,32 +221,32 @@ int rootcheck_init(int test_config) log2file("%s: System audit file not configured.", ARGV0); #endif } - - + + /* Setting default values */ if(rootcheck.workdir == NULL) rootcheck.workdir = DEFAULTDIR; #ifdef OSSECHIDS - + /* Start up message */ #ifdef WIN32 verbose(STARTUP_MSG, "ossec-rootcheck", getpid()); #else - + /* Connect to the queue if configured to do so */ if(rootcheck.notify == QUEUE) { debug1("%s: Starting queue ...",ARGV0); - + /* Starting the queue. */ if((rootcheck.queue = StartMQ(DEFAULTQPATH,WRITE)) < 0) - { + { merror(QUEUE_ERROR,ARGV0,DEFAULTQPATH, strerror(errno)); - + /* 5 seconds to see if the agent starts */ sleep(5); if((rootcheck.queue = StartMQ(DEFAULTQPATH,WRITE)) < 0) @@ -240,7 +261,7 @@ int rootcheck_init(int test_config) } #endif /* Not win32 */ - + #endif /* ossec hids */ @@ -256,7 +277,7 @@ int rootcheck_init(int test_config) #ifndef OSSECHIDS - + #ifndef WIN32 /* Start the signal handling */ StartSIG(ARGV0); @@ -264,17 +285,17 @@ int rootcheck_init(int test_config) #else return(0); - + #endif - + debug1("%s: DEBUG: Running run_rk_check",ARGV0); - run_rk_check(); + run_rk_check(); - - debug1("%s: DEBUG: Leaving...",ARGV0); - return(0); + debug1("%s: DEBUG: Leaving...",ARGV0); + + return(0); } /* EOF */ diff --git a/src/rootcheck/rootcheck.conf b/src/rootcheck/rootcheck.conf index eda1905..f40388b 100755 --- a/src/rootcheck/rootcheck.conf +++ b/src/rootcheck/rootcheck.conf @@ -11,4 +11,18 @@ ./shared/win_audit_rcl.txt ./shared/win_applications_rcl.txt ./shared/win_malware_rcl.txt + + yes + yes + + yes + yes + yes + yes + + yes + yes + yes + yes + yes diff --git a/src/rootcheck/rootcheck.h b/src/rootcheck/rootcheck.h index 3d9af73..ca9b279 100755 --- a/src/rootcheck/rootcheck.h +++ b/src/rootcheck/rootcheck.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/rootcheck/rootcheck.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation */ - + #ifndef __ROOTCHECK_H #define __ROOTCHECK_H @@ -28,7 +29,7 @@ rkconfig rootcheck; /* rk_types */ #define ALERT_OK 0 -#define ALERT_SYSTEM_ERROR 1 +#define ALERT_SYSTEM_ERROR 1 #define ALERT_SYSTEM_CRIT 2 #define ALERT_ROOTKIT_FOUND 3 #define ALERT_POLICY_VIOLATION 4 @@ -51,11 +52,11 @@ int rk_check_file(char *file, char *pattern); /* int rk_check_dir(char *dir, char *file, char *pattern) */ int rk_check_dir(char *dir, char *file, char *pattern); - + /* pt_matches: Checks if pattern is present on string */ int pt_matches(char *str, char *pattern); -/* pt_check_negate: checks if the patterns is made up +/* pt_check_negate: checks if the patterns is made up * completely of negate matches */ int pt_check_negate(char *pattern); @@ -67,37 +68,37 @@ int is_registry(char *entry_name, char *reg_option, char *reg_value); /* int rkcl_get_entry: Reads cl configuration file. */ int rkcl_get_entry(FILE *fp, char *msg, void *p_list); - + /** char *normalize_string * Normalizes a string, removing white spaces and tabs * from the begining and the end of it. */ char *normalize_string(char *str); - + /* Check if regex is present on the file. * Similar to `strings file | grep -r regex` - */ + */ int os_string(char *file, char *regex); /* check for NTFS ADS (Windows only) */ int os_check_ads(char *full_path); -/* os_get_process_list: Get list of processes +/* os_get_process_list: Get list of processes */ void *os_get_process_list(); /* is_process: Check is a process is running. */ int is_process(char *value, void *p_list); - + /* del_plist:. Deletes the process list */ int del_plist(void *p_list); - + /* Used to report messages */ int notify_rk(int rk_type, char *msg); @@ -138,7 +139,7 @@ void check_rc_sys(char *basedir); void check_rc_pids(); /* Verifies if "pid" is in the proc directory */ -int check_rc_readproc(int pid); +int check_rc_readproc(int pid); void check_rc_ports(); diff --git a/src/rootcheck/run_rk_check.c b/src/rootcheck/run_rk_check.c index b209b95..0e2c805 100755 --- a/src/rootcheck/run_rk_check.c +++ b/src/rootcheck/run_rk_check.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/rootcheck/run_rk_check.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -9,7 +10,7 @@ * Foundation */ - + #include "shared.h" #include "rootcheck.h" @@ -27,7 +28,7 @@ int notify_rk(int rk_type, char *msg) else if(rk_type == ALERT_SYSTEM_ERROR) printf("[ERR]: %s\n", msg); else if(rk_type == ALERT_POLICY_VIOLATION) - printf("[INFO]: %s\n", msg); + printf("[INFO]: %s\n", msg); else { printf("[FAILED]: %s\n", msg); @@ -36,12 +37,12 @@ int notify_rk(int rk_type, char *msg) printf("\n"); return(0); } - + /* No need to alert on that to the server */ if(rk_type <= ALERT_SYSTEM_ERROR) return(0); - #ifdef OSSECHIDS + #ifdef OSSECHIDS if(SendMSG(rootcheck.queue, msg, ROOTCHECK, ROOTCHECK_MQ) < 0) { merror(QUEUE_SEND, ARGV0); @@ -58,17 +59,17 @@ int notify_rk(int rk_type, char *msg) } #endif - return(0); + return(0); } - + /* start_rk_daemon * Start the rootkit daemon variables */ void start_rk_daemon() { return; - + if(rootcheck.notify == QUEUE) { } @@ -85,9 +86,9 @@ void run_rk_check() FILE *fp; OSList *plist; - + #ifndef WIN32 - /* Hard coding basedir */ + /* Hard coding basedir */ int i; char basedir[] = "/"; @@ -101,22 +102,22 @@ void run_rk_check() } } #else - + /* Basedir for Windows */ char basedir[] = "C:\\"; - + #endif - - + + /* Setting basedir */ if(rootcheck.basedir == NULL) { rootcheck.basedir = basedir; } - + time1 = time(0); - + /*** Initial message ***/ if(rootcheck.notify != QUEUE) { @@ -127,15 +128,15 @@ void run_rk_check() printf("Be patient, it may take a few minutes to complete...\n"); printf("\n"); } - - + + /* Cleaning the global variables */ rk_sys_count = 0; rk_sys_file[rk_sys_count] = NULL; rk_sys_name[rk_sys_count] = NULL; - - + + /* Sending scan start message */ notify_rk(ALERT_POLICY_VIOLATION, "Starting rootcheck scan."); if(rootcheck.notify == QUEUE) @@ -147,127 +148,142 @@ void run_rk_check() /*** First check, look for rootkits ***/ /* Open rootkit_files and pass the pointer to check_rc_files */ - if(!rootcheck.rootkit_files) + if (rootcheck.checks.rc_files) { - #ifndef WIN32 - merror("%s: No rootcheck_files file configured.", ARGV0); - #endif - } - - else - { - fp = fopen(rootcheck.rootkit_files, "r"); - if(!fp) + if(!rootcheck.rootkit_files) { - merror("%s: No rootcheck_files file: '%s'",ARGV0, - rootcheck.rootkit_files); + #ifndef WIN32 + merror("%s: No rootcheck_files file configured.", ARGV0); + #endif } else { - check_rc_files(rootcheck.basedir, fp); + fp = fopen(rootcheck.rootkit_files, "r"); + if(!fp) + { + merror("%s: No rootcheck_files file: '%s'",ARGV0, + rootcheck.rootkit_files); + } - fclose(fp); + else + { + check_rc_files(rootcheck.basedir, fp); + + fclose(fp); + } } } - - + + /*** Second check. look for trojan entries in common binaries ***/ - if(!rootcheck.rootkit_trojans) + if (rootcheck.checks.rc_trojans) { - #ifndef WIN32 - merror("%s: No rootcheck_trojans file configured.", ARGV0); - #endif - } - - else - { - fp = fopen(rootcheck.rootkit_trojans, "r"); - if(!fp) + if(!rootcheck.rootkit_trojans) { - merror("%s: No rootcheck_trojans file: '%s'",ARGV0, - rootcheck.rootkit_trojans); + #ifndef WIN32 + merror("%s: No rootcheck_trojans file configured.", ARGV0); + #endif } else { - #ifndef HPUX - check_rc_trojans(rootcheck.basedir, fp); - #endif + fp = fopen(rootcheck.rootkit_trojans, "r"); + if(!fp) + { + merror("%s: No rootcheck_trojans file: '%s'",ARGV0, + rootcheck.rootkit_trojans); + } + + else + { + #ifndef HPUX + check_rc_trojans(rootcheck.basedir, fp); + #endif - fclose(fp); + fclose(fp); + } } } #ifdef WIN32 - + /*** Getting process list ***/ plist = os_get_process_list(); /*** Windows audit check ***/ - if(!rootcheck.winaudit) + if (rootcheck.checks.rc_winaudit) { - merror("%s: No winaudit file configured.", ARGV0); - } - else - { - fp = fopen(rootcheck.winaudit, "r"); - if(!fp) + if(!rootcheck.winaudit) { - merror("%s: No winaudit file: '%s'",ARGV0, - rootcheck.winaudit); + merror("%s: No winaudit file configured.", ARGV0); } else { - check_rc_winaudit(fp, plist); - fclose(fp); + fp = fopen(rootcheck.winaudit, "r"); + if(!fp) + { + merror("%s: No winaudit file: '%s'",ARGV0, + rootcheck.winaudit); + } + else + { + check_rc_winaudit(fp, plist); + fclose(fp); + } } } /* Windows malware */ - if(!rootcheck.winmalware) + if (rootcheck.checks.rc_winmalware) { - merror("%s: No winmalware file configured.", ARGV0); - } - else - { - fp = fopen(rootcheck.winmalware, "r"); - if(!fp) + if(!rootcheck.winmalware) { - merror("%s: No winmalware file: '%s'",ARGV0, - rootcheck.winmalware); + merror("%s: No winmalware file configured.", ARGV0); } else { - check_rc_winmalware(fp, plist); - fclose(fp); + fp = fopen(rootcheck.winmalware, "r"); + if(!fp) + { + merror("%s: No winmalware file: '%s'",ARGV0, + rootcheck.winmalware); + } + else + { + check_rc_winmalware(fp, plist); + fclose(fp); + } } } - + /* Windows Apps */ - if(!rootcheck.winapps) - { - merror("%s: No winapps file configured.", ARGV0); - } - else + if (rootcheck.checks.rc_winapps) { - fp = fopen(rootcheck.winapps, "r"); - if(!fp) + if(!rootcheck.winapps) { - merror("%s: No winapps file: '%s'",ARGV0, - rootcheck.winapps); + merror("%s: No winapps file configured.", ARGV0); } else { - check_rc_winapps(fp, plist); - fclose(fp); + fp = fopen(rootcheck.winapps, "r"); + if(!fp) + { + merror("%s: No winapps file: '%s'",ARGV0, + rootcheck.winapps); + } + else + { + check_rc_winapps(fp, plist); + fclose(fp); + } } } - + /* Freeing process list */ del_plist((void *)plist); @@ -276,73 +292,91 @@ void run_rk_check() /** Checks for other non Windows. **/ #else - + /*** Unix audit check ***/ - if(rootcheck.unixaudit) + if (rootcheck.checks.rc_unixaudit) { - /* Getting process list. */ - plist = os_get_process_list(); + if(rootcheck.unixaudit) + { + /* Getting process list. */ + plist = os_get_process_list(); - i = 0; - while(rootcheck.unixaudit[i]) - { - fp = fopen(rootcheck.unixaudit[i], "r"); - if(!fp) + i = 0; + while(rootcheck.unixaudit[i]) { - merror("%s: No unixaudit file: '%s'",ARGV0, - rootcheck.unixaudit[i]); + fp = fopen(rootcheck.unixaudit[i], "r"); + if(!fp) + { + merror("%s: No unixaudit file: '%s'",ARGV0, + rootcheck.unixaudit[i]); + } + else + { + /* Running unix audit. */ + check_rc_unixaudit(fp, plist); + + fclose(fp); + } + + i++; } - else - { - /* Running unix audit. */ - check_rc_unixaudit(fp, plist); - fclose(fp); - } - i++; + /* Freeing list */ + del_plist((void *)plist); } - - - /* Freeing list */ - del_plist((void *)plist); } - + #endif - - + + /*** Third check, looking for files on the /dev ***/ - debug1("%s: DEBUG: Going into check_rc_dev", ARGV0); - check_rc_dev(rootcheck.basedir); - + if (rootcheck.checks.rc_dev) + { + debug1("%s: DEBUG: Going into check_rc_dev", ARGV0); + check_rc_dev(rootcheck.basedir); + } + /*** Fourth check, scan the whole system looking for additional issues */ - debug1("%s: DEBUG: Going into check_rc_sys", ARGV0); - check_rc_sys(rootcheck.basedir); - + if (rootcheck.checks.rc_sys) + { + debug1("%s: DEBUG: Going into check_rc_sys", ARGV0); + check_rc_sys(rootcheck.basedir); + } + /*** Process checking ***/ - debug1("%s: DEBUG: Going into check_rc_pids", ARGV0); - check_rc_pids(); + if (rootcheck.checks.rc_pids) + { + debug1("%s: DEBUG: Going into check_rc_pids", ARGV0); + check_rc_pids(); + } /*** Check all the ports ***/ - debug1("%s: DEBUG: Going into check_rc_ports", ARGV0); - check_rc_ports(); + if (rootcheck.checks.rc_ports) + { + debug1("%s: DEBUG: Going into check_rc_ports", ARGV0); + check_rc_ports(); + + /*** Check open ports ***/ + debug1("%s: DEBUG: Going into check_open_ports", ARGV0); + check_open_ports(); + } - /*** Check open ports ***/ - debug1("%s: DEBUG: Going into check_open_ports", ARGV0); - check_open_ports(); - /*** Check interfaces ***/ - debug1("%s: DEBUG: Going into check_rc_if", ARGV0); - check_rc_if(); - - - debug1("%s: DEBUG: Completed with all checks.", ARGV0); - - + if (rootcheck.checks.rc_if) + { + debug1("%s: DEBUG: Going into check_rc_if", ARGV0); + check_rc_if(); + } + + + debug1("%s: DEBUG: Completed with all checks.", ARGV0); + + /* Cleaning the global memory */ { int li; @@ -350,7 +384,7 @@ void run_rk_check() { if(!rk_sys_file[li] || !rk_sys_name[li]) - break; + break; free(rk_sys_file[li]); free(rk_sys_name[li]); @@ -359,7 +393,7 @@ void run_rk_check() /*** Final message ***/ time2 = time(0); - + if(rootcheck.notify != QUEUE) { printf("\n"); @@ -377,9 +411,9 @@ void run_rk_check() { merror("%s: INFO: Ending rootcheck scan.", ARGV0); } - - - debug1("%s: DEBUG: Leaving run_rk_check",ARGV0); + + + debug1("%s: DEBUG: Leaving run_rk_check",ARGV0); return; } diff --git a/src/rootcheck/unix-process.c b/src/rootcheck/unix-process.c index 072964e..3b873d3 100755 --- a/src/rootcheck/unix-process.c +++ b/src/rootcheck/unix-process.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/rootcheck/unix-process.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -8,11 +9,11 @@ * License (version 2) as published by the FSF - Free Software * Foundation * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/main/license/ . */ - + #include "shared.h" #include "rootcheck.h" @@ -24,13 +25,13 @@ char *_os_get_runps(char *ps, int mpid) char buf[OS_SIZE_2048 +1]; char command[OS_SIZE_1024 +1]; FILE *fp; - - + + buf[0] = '\0'; command[0] = '\0'; - command[OS_SIZE_1024] = '\0'; - - + command[OS_SIZE_1024] = '\0'; + + snprintf(command, OS_SIZE_1024, "%s -p %d 2> /dev/null", ps, mpid); fp = popen(command, "r"); @@ -58,9 +59,9 @@ char *_os_get_runps(char *ps, int mpid) while(*tmp_str == ' ') tmp_str++; - + nbuf = tmp_str; - + tmp_str = strchr(nbuf, '\n'); if(tmp_str) @@ -86,7 +87,7 @@ void *os_get_process_list() int i = 1; pid_t max_pid = MAX_PID; OSList *p_list = NULL; - + char ps[OS_SIZE_1024 +1]; @@ -109,7 +110,7 @@ void *os_get_process_list() if(!p_list) { merror(LIST_ERROR, ARGV0); - return(NULL); + return(NULL); } @@ -135,11 +136,11 @@ void *os_get_process_list() OSList_AddData(p_list, p_info); } } - + return((void *)p_list); } - - + + #endif /* EOF */ diff --git a/src/rootcheck/util/ads_dump.c b/src/rootcheck/util/ads_dump.c index f27d4cd..68316bd 100644 --- a/src/rootcheck/util/ads_dump.c +++ b/src/rootcheck/util/ads_dump.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/rootcheck/util/ads_dump.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -8,11 +9,11 @@ * License (version 2) as published by the FSF - Free Software * Foundation */ - + #include #include #include -#include +#include #include @@ -28,18 +29,18 @@ int ads_found = 0; /* Print out streams of a file */ int os_get_streams(char *full_path) { - HANDLE file_h; + HANDLE file_h; WIN32_STREAM_ID sid; void *context = NULL; - char stream_name[MAX_PATH +1]; - char final_name[MAX_PATH +1]; + char stream_name[MAX_PATH +1]; + char final_name[MAX_PATH +1]; DWORD dwRead, shs, dw1, dw2; /* Opening file */ - file_h = CreateFile(full_path, + file_h = CreateFile(full_path, GENERIC_READ, FILE_SHARE_READ, NULL, @@ -47,8 +48,8 @@ int os_get_streams(char *full_path) FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_POSIX_SEMANTICS, NULL); - if (file_h == INVALID_HANDLE_VALUE) - { + if (file_h == INVALID_HANDLE_VALUE) + { return 0; } @@ -62,7 +63,7 @@ int os_get_streams(char *full_path) while(1) { - if(BackupRead(file_h, (LPBYTE) &sid, shs, &dwRead, + if(BackupRead(file_h, (LPBYTE) &sid, shs, &dwRead, FALSE, FALSE, &context) == 0) { break; @@ -74,14 +75,14 @@ int os_get_streams(char *full_path) stream_name[0] = '\0'; stream_name[MAX_PATH] = '\0'; - if(BackupRead(file_h, (LPBYTE)stream_name, - sid.dwStreamNameSize, + if(BackupRead(file_h, (LPBYTE)stream_name, + sid.dwStreamNameSize, &dwRead, FALSE, FALSE, &context)) { if(dwRead != 0) { char *tmp_pt; - snprintf(final_name, MAX_PATH, "%s%S", full_path, + snprintf(final_name, MAX_PATH, "%s%S", full_path, (WCHAR *)stream_name); tmp_pt = strrchr(final_name, ':'); if(tmp_pt) @@ -94,7 +95,7 @@ int os_get_streams(char *full_path) } /* Getting next */ - if(!BackupSeek(file_h, sid.Size.LowPart, sid.Size.HighPart, + if(!BackupSeek(file_h, sid.Size.LowPart, sid.Size.HighPart, &dw1, &dw2, &context)) { break; @@ -114,7 +115,7 @@ int read_sys_file(char *file_name) /* Getting streams */ os_get_streams(file_name); - + if(stat(file_name, &statbuf) < 0) { return(0); @@ -170,7 +171,7 @@ int read_sys_dir(char *dir_name) /* Just ignore . and .. */ if((strcmp(entry->d_name,".") == 0) || - (strcmp(entry->d_name,"..") == 0)) + (strcmp(entry->d_name,"..") == 0)) { continue; } diff --git a/src/rootcheck/win-common.c b/src/rootcheck/win-common.c index 3e9e26d..10a4545 100644 --- a/src/rootcheck/win-common.c +++ b/src/rootcheck/win-common.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/rootcheck/win-common.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -8,19 +9,19 @@ * License (version 2) as published by the FSF - Free Software * Foundation */ - - + + #include "shared.h" #include "rootcheck.h" -#ifdef WIN32 +#ifdef WIN32 /** Registry checking values **/ /* Global variables */ HKEY rk_sub_tree; - + /* Default values */ #define MAX_KEY_LENGTH 255 #define MAX_KEY 2048 @@ -33,18 +34,18 @@ HKEY rk_sub_tree; */ int os_check_ads(char *full_path) { - HANDLE file_h; + HANDLE file_h; WIN32_STREAM_ID sid; void *context = NULL; - char stream_name[MAX_PATH +1]; - char final_name[MAX_PATH +1]; + char stream_name[MAX_PATH +1]; + char final_name[MAX_PATH +1]; DWORD dwRead, shs, dw1, dw2; /* Opening file */ - file_h = CreateFile(full_path, + file_h = CreateFile(full_path, GENERIC_READ, FILE_SHARE_READ, NULL, @@ -52,8 +53,8 @@ int os_check_ads(char *full_path) FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_POSIX_SEMANTICS, NULL); - if (file_h == INVALID_HANDLE_VALUE) - { + if (file_h == INVALID_HANDLE_VALUE) + { return 0; } @@ -67,7 +68,7 @@ int os_check_ads(char *full_path) while(1) { - if(BackupRead(file_h, (LPBYTE) &sid, shs, &dwRead, + if(BackupRead(file_h, (LPBYTE) &sid, shs, &dwRead, FALSE, FALSE, &context) == 0) { break; @@ -79,8 +80,8 @@ int os_check_ads(char *full_path) stream_name[0] = '\0'; stream_name[MAX_PATH] = '\0'; - if(BackupRead(file_h, (LPBYTE)stream_name, - sid.dwStreamNameSize, + if(BackupRead(file_h, (LPBYTE)stream_name, + sid.dwStreamNameSize, &dwRead, FALSE, FALSE, &context)) { if(dwRead != 0) @@ -90,9 +91,9 @@ int os_check_ads(char *full_path) char op_msg[OS_SIZE_1024 +1]; snprintf(final_name, MAX_PATH, "%s", full_path); - + max_path_size = strlen(final_name); - + /* Copying from wide char to char. */ while((i < dwRead) && (max_path_size < MAX_PATH)) @@ -122,7 +123,7 @@ int os_check_ads(char *full_path) } /* Getting next */ - if(!BackupSeek(file_h, sid.Size.LowPart, sid.Size.HighPart, + if(!BackupSeek(file_h, sid.Size.LowPart, sid.Size.HighPart, &dw1, &dw2, &context)) { break; @@ -153,7 +154,7 @@ char *__os_winreg_getkey(char *reg_entry) /* Setting sub tree */ if((strcmp(reg_entry, "HKEY_LOCAL_MACHINE") == 0) || - (strcmp(reg_entry, "HKLM") == 0)) + (strcmp(reg_entry, "HKLM") == 0)) { rk_sub_tree = HKEY_LOCAL_MACHINE; } @@ -178,7 +179,7 @@ char *__os_winreg_getkey(char *reg_entry) { /* Setting sub tree to null */ rk_sub_tree = NULL; - + /* Returning tmp_str to the previous value */ if(tmp_str && (*tmp_str == '\0')) *tmp_str = '\\'; @@ -263,7 +264,7 @@ int __os_winreg_querykey(HKEY hKey, char *p_key, char *full_key_name, value_buffer[MAX_VALUE_NAME] = '\0'; data_buffer[MAX_VALUE_NAME] = '\0'; var_storage[MAX_VALUE_NAME] = '\0'; - + /* Getting each value */ for(i=0;i " @@ -110,7 +111,7 @@ void *os_get_process_list() return(NULL); } } - + /* Enabling debug privilege */ if(!os_win32_setdebugpriv(hpriv, 1)) @@ -148,7 +149,7 @@ void *os_get_process_list() merror(LIST_ERROR, ARGV0); return(0); } - + /* Getting each process name and path */ while(Process32Next( hsnap, &p_entry)) @@ -159,15 +160,15 @@ void *os_get_process_list() /* Setting process name */ os_strdup(p_entry.szExeFile, p_name); - - + + /* Getting additional information from modules */ HANDLE hmod = INVALID_HANDLE_VALUE; MODULEENTRY32 m_entry; m_entry.dwSize = sizeof(MODULEENTRY32); - + /* Snapshot of the process */ - hmod = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, + hmod = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, p_entry.th32ProcessID); if(hmod == INVALID_HANDLE_VALUE) { diff --git a/src/shared/agent_op.c b/src/shared/agent_op.c index 2ff49b7..229043b 100755 --- a/src/shared/agent_op.c +++ b/src/shared/agent_op.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/shared/agent_op.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -17,7 +18,7 @@ /** Checks if syscheck is to be executed/restarted. * Returns 1 on success or 0 on failure (shouldn't be executed now). */ -int os_check_restart_syscheck() +int os_check_restart_syscheck() { struct stat restart_status; @@ -28,19 +29,19 @@ int os_check_restart_syscheck() { if(stat(SYSCHECK_RESTART, &restart_status) == -1) return(0); - - unlink(SYSCHECK_RESTART); + + unlink(SYSCHECK_RESTART); } else { if(stat(SYSCHECK_RESTART_PATH, &restart_status) == -1) return(0); - - unlink(SYSCHECK_RESTART_PATH); + + unlink(SYSCHECK_RESTART_PATH); } - - return(1); + + return(1); } @@ -77,12 +78,14 @@ char* os_read_agent_name() char buf[1024 + 1]; FILE *fp = NULL; + debug2("%s: calling os_read_agent_name().", ARGV0); + if(isChroot()) fp = fopen(AGENT_INFO_FILE, "r"); else fp = fopen(AGENT_INFO_FILEP, "r"); - - /* We give 1 second for the file to be created... */ + + /* We give 1 second for the file to be created... */ if(!fp) { sleep(1); @@ -90,9 +93,9 @@ char* os_read_agent_name() if(isChroot()) fp = fopen(AGENT_INFO_FILE, "r"); else - fp = fopen(AGENT_INFO_FILEP, "r"); + fp = fopen(AGENT_INFO_FILEP, "r"); } - + if(!fp) { debug1(FOPEN_ERROR, __local_name, AGENT_INFO_FILE); @@ -108,7 +111,9 @@ char* os_read_agent_name() char *ret = NULL; os_strdup(buf, ret); fclose(fp); - + + debug2("%s: os_read_agent_name returned (%s).", __local_name, ret); + return(ret); } @@ -127,6 +132,8 @@ char *os_read_agent_ip() char buf[1024 + 1]; FILE *fp; + debug2("%s: calling os_read_agent_ip().", ARGV0); + fp = fopen(AGENT_INFO_FILE, "r"); if(!fp) { @@ -162,6 +169,8 @@ char *os_read_agent_id() char buf[1024 + 1]; FILE *fp; + debug2("%s: calling os_read_agent_id().", ARGV0); + fp = fopen(AGENT_INFO_FILE, "r"); if(!fp) { @@ -187,12 +196,72 @@ char *os_read_agent_id() } +/* cmoraes: begin add */ + +/** char *os_read_agent_profile() + * Reads the agent profile name for the current agent. + * Returns NULL on error. + * + * Description: + * Comma separated list of strings that used to identify what type + * of configuration is used for this agent. + * The profile name is set in the agent's etc/ossec.conf file + * It is matched with the ossec manager's agent.conf file to read + * configuration only applicable to this profile name. + * + */ +char* os_read_agent_profile() +{ + char buf[1024 + 1]; + FILE *fp; + + debug2("%s: calling os_read_agent_profile().", __local_name); + + if(isChroot()) + fp = fopen(AGENT_INFO_FILE, "r"); + else + fp = fopen(AGENT_INFO_FILEP, "r"); + + if(!fp) + { + debug2("%s: Failed to open file. Errno=%d.", ARGV0, errno); + merror(FOPEN_ERROR, __local_name, AGENT_INFO_FILE); + return(NULL); + } + + buf[1024] = '\0'; + + + /* Getting profile */ + if(fgets(buf, 1024, fp) && fgets(buf, 1024, fp) && + fgets(buf, 1024, fp) && fgets(buf, 1024, fp)) + { + char *ret = NULL; + + /* Trim the /n and/or /r at the end of the string */ + os_trimcrlf(buf); + + os_strdup(buf, ret); + debug2("%s: os_read_agent_profile() = [%s]", __local_name, ret); + + fclose(fp); + + return(ret); + } + + fclose(fp); + return(NULL); +} +/* cmoraes: end add */ + /** int os_write_agent_info(char *agent_name, char *agent_ip, char *agent_id) * Writes the agent info inside the queue, for the other processes to read. * Returns 1 on success or <= 0 on failure. */ -int os_write_agent_info(char *agent_name, char *agent_ip, char *agent_id) +/* cmoraes: changed function. added cfg_profile_name parameter */ +int os_write_agent_info(char *agent_name, char *agent_ip, + char *agent_id, char *cfg_profile_name) { FILE *fp; @@ -203,7 +272,8 @@ int os_write_agent_info(char *agent_name, char *agent_ip, char *agent_id) return(0); } - fprintf(fp, "%s\n-\n%s\n", agent_name, agent_id); + /*cmoraes: added cfg_profile_name parameter*/ + fprintf(fp, "%s\n-\n%s\n%s\n", agent_name, agent_id, cfg_profile_name); fclose(fp); return(1); } diff --git a/src/shared/debug_op.c b/src/shared/debug_op.c index 1c8343a..6be1f8c 100755 --- a/src/shared/debug_op.c +++ b/src/shared/debug_op.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/shared/debug_op.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -41,13 +42,13 @@ void _log(const char * msg,va_list args) va_list args2; FILE *fp; - + tm = time(NULL); p = localtime(&tm); /* Duplicating args */ va_copy(args2, args); - + /* If under chroot, log directly to /logs/ossec.log */ if(chroot_flag == 1) @@ -69,7 +70,7 @@ void _log(const char * msg,va_list args) if(fp) { (void)fprintf(fp,"%d/%02d/%02d %02d:%02d:%02d ", - p->tm_year+1900,p->tm_mon+1, + p->tm_year+1900,p->tm_mon+1, p->tm_mday,p->tm_hour,p->tm_min,p->tm_sec); (void)vfprintf(fp, msg, args); #ifdef WIN32 @@ -156,15 +157,15 @@ void log2file(const char * msg,... ) _log(msg, args); daemon_flag = dbg_tmp; - + va_end(args); } void ErrorExit(const char *msg, ...) { va_list args; - - #ifdef WIN32 + + #ifdef WIN32 /* If not MA */ #ifndef MA WinSetError(); @@ -197,13 +198,13 @@ void print_out(const char *msg, ...) /* Print to stderr */ (void)vfprintf(stderr, msg, args); - + #ifdef WIN32 (void)fprintf(stderr, "\r\n"); #else (void)fprintf(stderr, "\n"); #endif - + va_end(args); } diff --git a/src/shared/dirtree_op.c b/src/shared/dirtree_op.c index 10199ad..47adbb4 100755 --- a/src/shared/dirtree_op.c +++ b/src/shared/dirtree_op.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/shared/dirtree_op.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -11,15 +12,15 @@ * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ - -/* Common API for dealing with directory trees */ + +/* Common API for dealing with directory trees */ #include "shared.h" -/* Create the tree +/* Create the tree * Return NULL on error */ OSDirTree *OSDirTree_Create() @@ -31,16 +32,16 @@ OSDirTree *OSDirTree_Create() { return(NULL); } - + my_tree->first_node = NULL; my_tree->last_node = NULL; - + return(my_tree); } -/* Get first node from tree (starting from parent) +/* Get first node from tree (starting from parent) * Returns null on invalid tree (not initialized) */ OSTreeNode *OSDirTree_GetFirstNode(OSDirTree *tree) @@ -54,7 +55,7 @@ OSTreeNode *OSDirTree_GetFirstNode(OSDirTree *tree) * Internal call, looks up for an entry in the middle of the tree. * Should not be called directly. */ -OSDirTree *_OSTreeNode_Add(OSDirTree *tree, char *str, +OSDirTree *_OSTreeNode_Add(OSDirTree *tree, char *str, void *data, char sep) { char *tmp_str; @@ -82,7 +83,7 @@ OSDirTree *_OSTreeNode_Add(OSDirTree *tree, char *str, tree->first_node = NULL; tree->last_node = NULL; } - + curnode = tree->first_node; @@ -108,7 +109,7 @@ OSDirTree *_OSTreeNode_Add(OSDirTree *tree, char *str, { os_calloc(1, sizeof(OSTreeNode), newnode); //printf("XXXX Adding node: %s\n", str); - + if(!tree->first_node && !tree->last_node) { @@ -146,11 +147,11 @@ OSDirTree *_OSTreeNode_Add(OSDirTree *tree, char *str, { *tmp_str = sep; } - + return(tree); } - + /** void OSDirTree_AddToTree @@ -168,16 +169,16 @@ void OSDirTree_AddToTree(OSDirTree *tree, char *str, void *data, char sep) char *tmp_str; OSTreeNode *newnode; OSTreeNode *curnode; - - + + /* First character doesn't count as a separator */ tmp_str = strchr(str +1, sep); if(tmp_str) { *tmp_str = '\0'; } - - + + curnode = tree->first_node; while(curnode) { @@ -186,7 +187,7 @@ void OSDirTree_AddToTree(OSDirTree *tree, char *str, void *data, char sep) /* If we have other elements, keep going */ if(tmp_str) { - curnode->child = _OSTreeNode_Add(curnode->child, + curnode->child = _OSTreeNode_Add(curnode->child, tmp_str +1, data, sep); } break; @@ -213,7 +214,7 @@ void OSDirTree_AddToTree(OSDirTree *tree, char *str, void *data, char sep) tree->last_node->next = newnode; tree->last_node = newnode; } - + newnode->next = NULL; os_strdup(str, newnode->value); @@ -221,7 +222,7 @@ void OSDirTree_AddToTree(OSDirTree *tree, char *str, void *data, char sep) /* If we have other elements, keep going */ if(tmp_str) { - newnode->child = _OSTreeNode_Add(newnode->child, + newnode->child = _OSTreeNode_Add(newnode->child, tmp_str +1, data, sep); newnode->data = NULL; } @@ -290,7 +291,7 @@ void *OSDirTree_SearchTree(OSDirTree *tree, char *str, char sep) { *tmp_str = sep; } - + return(ret); } diff --git a/src/shared/file-queue.c b/src/shared/file-queue.c index 17ef8c9..d0c316d 100755 --- a/src/shared/file-queue.c +++ b/src/shared/file-queue.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/shared/file-queue.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -32,13 +33,13 @@ void file_sleep() { #ifndef WIN32 struct timeval fp_timeout; - + fp_timeout.tv_sec = FQ_TIMEOUT; fp_timeout.tv_usec = 0; /* Waiting for the select timeout */ select(0, NULL, NULL, NULL, &fp_timeout); - + #else /* Windows don't like select that way */ Sleep((FQ_TIMEOUT + 2) * 1000); @@ -70,7 +71,7 @@ void GetFile_Queue(file_queue *fileq) ALERTS, fileq->year, fileq->mon, - fileq->day); + fileq->day); } } @@ -79,7 +80,7 @@ void GetFile_Queue(file_queue *fileq) /** int Handle_Queue(file_queue *fileq) * Re Handle the file queue. */ -int Handle_Queue(file_queue *fileq, int flags) +int Handle_Queue(file_queue *fileq, int flags) { /* Closing if it is open */ if(!(flags & CRALERT_FP_SET)) @@ -115,7 +116,7 @@ int Handle_Queue(file_queue *fileq, int flags) } } - + /* File change time */ if(fstat(fileno(fileq->fp), &fileq->f_status) < 0) { @@ -124,9 +125,9 @@ int Handle_Queue(file_queue *fileq, int flags) fileq->fp = NULL; return(-1); } - + fileq->last_change = fileq->f_status.st_mtime; - + return(1); } @@ -144,29 +145,29 @@ int Init_FileQueue(file_queue *fileq, struct tm *p, int flags) } fileq->last_change = 0; fileq->flags = 0; - + fileq->day = p->tm_mday; fileq->year = p->tm_year+1900; - + strncpy(fileq->mon, s_month[p->tm_mon], 4); memset(fileq->file_name, '\0',MAX_FQUEUE + 1); /* Setting the supplied flags */ fileq->flags = flags; - + /* Getting latest file */ GetFile_Queue(fileq); - + /* Always seek end when starting the queue */ if(Handle_Queue(fileq, fileq->flags) < 0) { return(-1); } - return(0); + return(0); } @@ -179,7 +180,7 @@ alert_data *Read_FileMon(file_queue *fileq, struct tm *p, int timeout) int i = 0; alert_data *al_data; - + /* If the file queue is not available, try to access it */ if(!fileq->fp) { @@ -190,7 +191,7 @@ alert_data *Read_FileMon(file_queue *fileq, struct tm *p, int timeout) } } - + /* Getting currently file */ if(p->tm_mday != fileq->day) { @@ -217,7 +218,7 @@ alert_data *Read_FileMon(file_queue *fileq, struct tm *p, int timeout) } } - + /* Try up to timeout times to get an event */ while(i < timeout) { @@ -226,12 +227,12 @@ alert_data *Read_FileMon(file_queue *fileq, struct tm *p, int timeout) { return(al_data); } - - i++; + + i++; file_sleep(); } - + /* Returning NULL if timeout expires. */ return(NULL); } diff --git a/src/shared/file_op.c b/src/shared/file_op.c index f97597a..17778e2 100755 --- a/src/shared/file_op.c +++ b/src/shared/file_op.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/shared/file_op.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -10,7 +11,7 @@ */ -/* Functions to handle operation with files +/* Functions to handle operation with files */ @@ -52,7 +53,7 @@ #ifndef PRODUCT_DATACENTER_SERVER_CORE_V #define PRODUCT_DATACENTER_SERVER_CORE_V 0x00000027 #define PRODUCT_DATACENTER_SERVER_CORE_V_C "Datacenter Edition (core) " -#endif +#endif #ifndef PRODUCT_DATACENTER_SERVER_V #define PRODUCT_DATACENTER_SERVER_V 0x00000025 @@ -250,7 +251,7 @@ int CreatePID(char *name, int pid) { char file[256]; FILE *fp; - + if(isChroot()) { snprintf(file,255,"%s/%s-%d.pid",OS_PIDFILE,name,pid); @@ -264,18 +265,20 @@ int CreatePID(char *name, int pid) fp = fopen(file,"a"); if(!fp) return(-1); - + fprintf(fp,"%d\n",pid); - + + chmod(file, 0640); + fclose(fp); - + return(0); } int DeletePID(char *name) { char file[256]; - + if(isChroot()) { snprintf(file,255,"%s/%s-%d.pid",OS_PIDFILE,name,(int)getpid()); @@ -288,9 +291,9 @@ int DeletePID(char *name) if(File_DateofChange(file) < 0) return(-1); - + unlink(file); - + return(0); } @@ -309,7 +312,7 @@ int UnmergeFiles(char *finalpath, char *optdir) finalfp = fopen(finalpath, "r"); if(!finalfp) { - merror("%s: ERROR: Unable to read merged file: '%s'.", + merror("%s: ERROR: Unable to read merged file: '%s'.", __local_name, finalpath); return(0); } @@ -322,7 +325,7 @@ int UnmergeFiles(char *finalpath, char *optdir) break; } - + /* Initiator. */ if(buf[0] != '!') continue; @@ -360,7 +363,7 @@ int UnmergeFiles(char *finalpath, char *optdir) if(!fp) { ret = 0; - merror("%s: ERROR: Unable to unmerge file '%s'.", + merror("%s: ERROR: Unable to unmerge file '%s'.", __local_name, final_name); } @@ -430,7 +433,7 @@ int MergeAppendFile(char *finalpath, char *files) finalfp = fopen(finalpath, "w"); if(!finalfp) { - merror("%s: ERROR: Unable to create merged file: '%s'.", + merror("%s: ERROR: Unable to create merged file: '%s'.", __local_name, finalpath); return(0); } @@ -443,7 +446,7 @@ int MergeAppendFile(char *finalpath, char *files) finalfp = fopen(finalpath, "a"); if(!finalfp) { - merror("%s: ERROR: Unable to create merged file: '%s'.", + merror("%s: ERROR: Unable to create merged file: '%s'.", __local_name, finalpath); return(0); } @@ -501,7 +504,7 @@ int MergeFiles(char *finalpath, char **files) finalfp = fopen(finalpath, "w"); if(!finalfp) { - merror("%s: ERROR: Unable to create merged file: '%s'.", + merror("%s: ERROR: Unable to create merged file: '%s'.", __local_name, finalpath); return(0); } @@ -566,7 +569,7 @@ char *getuname() if(ret == NULL) return(NULL); - snprintf(ret, 255, "%s %s %s %s %s - %s %s", + snprintf(ret, 255, "%s %s %s %s %s - %s %s", uts_buf.sysname, uts_buf.nodename, uts_buf.release, @@ -582,9 +585,9 @@ char *getuname() ret = calloc(256, sizeof(char)); if(ret == NULL) return(NULL); - + snprintf(ret, 255, "No system info available - %s %s", - __name, __version); + __name, __version); return(ret); } @@ -641,7 +644,7 @@ void goDaemonLight() /* Going to / */ chdir("/"); - + return; } @@ -699,7 +702,7 @@ void goDaemon() /* Going to / */ chdir("/"); - + /* Closing stdin, stdout and stderr */ /* fclose(stdin); @@ -713,7 +716,7 @@ void goDaemon() open("/dev/null", O_RDWR); open("/dev/null", O_RDWR); */ - + return; } @@ -732,12 +735,13 @@ int checkVista() } - /* We check if the system is vista (most be called during the startup. */ + /* We check if the system is vista (must be called during the startup.) */ if(strstr(m_uname, "Windows Server 2008") || - strstr(m_uname, "Vista")) + strstr(m_uname, "Vista") || + strstr(m_uname, "Windows 7")) { isVista = 1; - verbose("%s: INFO: System is Vista or Windows Server 2008.", + verbose("%s: INFO: System is Vista or Windows Server 2008.", __local_name); } @@ -759,7 +763,7 @@ char *getuname() typedef BOOL (WINAPI *PGPI)(DWORD, DWORD, DWORD, DWORD, PDWORD); - /* Extracted from ms web site + /* Extracted from ms web site * http://msdn.microsoft.com/library/en-us/sysinfo/base/getting_the_system_version.asp */ OSVERSIONINFOEX osvi; @@ -775,25 +779,37 @@ char *getuname() if(!(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi))) { osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); - if (!GetVersionEx((OSVERSIONINFO *)&osvi)) + if (!GetVersionEx((OSVERSIONINFO *)&osvi)) return(NULL); } /* Allocating the memory */ os_calloc(OS_SIZE_1024 +1, sizeof(char), ret); ret[OS_SIZE_1024] = '\0'; - + switch(osvi.dwPlatformId) { /* Test for the Windows NT product family. */ case VER_PLATFORM_WIN32_NT: - if(osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0 ) + if(osvi.dwMajorVersion == 6) { - if(osvi.wProductType == VER_NT_WORKSTATION ) - strncat(ret, "Microsoft Windows Vista ", ret_size -1); - else + if(osvi.dwMinorVersion == 0) + { + if(osvi.wProductType == VER_NT_WORKSTATION ) + strncat(ret, "Microsoft Windows Vista ", ret_size -1); + else + { + strncat(ret, "Microsoft Windows Server 2008 ", ret_size -1); + } + } + else if(osvi.dwMinorVersion == 1) { - strncat(ret, "Microsoft Windows Server 2008 ", ret_size -1); + if(osvi.wProductType == VER_NT_WORKSTATION ) + strncat(ret, "Microsoft Windows 7 ", ret_size -1); + else + { + strncat(ret, "Microsoft Windows Server 2008 R2 ", ret_size -1); + } } ret_size-=strlen(ret) +1; @@ -801,7 +817,7 @@ char *getuname() /* Getting product version. */ pGPI = (PGPI) GetProcAddress( - GetModuleHandle(TEXT("kernel32.dll")), + GetModuleHandle(TEXT("kernel32.dll")), "GetProductInfo"); pGPI( 6, 0, 0, 0, &dwType); @@ -926,7 +942,7 @@ char *getuname() strncat(ret, PRODUCT_WEB_SERVER_CORE_C, ret_size -1); break; } - + ret_size-=strlen(ret) +1; } @@ -934,18 +950,18 @@ char *getuname() else if(osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) { pGNSI = (PGNSI) GetProcAddress( - GetModuleHandle("kernel32.dll"), + GetModuleHandle("kernel32.dll"), "GetNativeSystemInfo"); if(NULL != pGNSI) pGNSI(&si); if( GetSystemMetrics(89) ) - strncat(ret, "Microsoft Windows Server 2003 R2 ", + strncat(ret, "Microsoft Windows Server 2003 R2 ", ret_size -1); else if(osvi.wProductType == VER_NT_WORKSTATION && si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64) { - strncat(ret, + strncat(ret, "Microsoft Windows XP Professional x64 Edition ", ret_size -1 ); } @@ -953,7 +969,7 @@ char *getuname() { strncat(ret, "Microsoft Windows Server 2003, ",ret_size-1); } - + ret_size-=strlen(ret) +1; } @@ -963,7 +979,7 @@ char *getuname() ret_size-=strlen(ret) +1; } - + else if(osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) { strncat(ret, "Microsoft Windows 2000 ", ret_size -1); @@ -995,15 +1011,15 @@ char *getuname() strncat(ret, "Workstation 4.0 ", ret_size -1); else if( osvi.wSuiteMask & VER_SUITE_PERSONAL ) strncat(ret, "Home Edition ", ret_size -1); - else + else strncat(ret, "Professional ",ret_size -1); /* Fixing size */ - ret_size-=strlen(ret) +1; + ret_size-=strlen(ret) +1; } /* Test for the server type. */ - else if( osvi.wProductType == VER_NT_SERVER || + else if( osvi.wProductType == VER_NT_SERVER || osvi.wProductType == VER_NT_DOMAIN_CONTROLLER ) { if(osvi.dwMajorVersion==5 && osvi.dwMinorVersion==2) @@ -1012,7 +1028,7 @@ char *getuname() PROCESSOR_ARCHITECTURE_IA64 ) { if( osvi.wSuiteMask & VER_SUITE_DATACENTER ) - strncat(ret, + strncat(ret, "Datacenter Edition for Itanium-based Systems ", ret_size -1); else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) @@ -1020,7 +1036,7 @@ char *getuname() "Enterprise Edition for Itanium-based Systems ", ret_size -1); - ret_size-=strlen(ret) +1; + ret_size-=strlen(ret) +1; } else if ( si.wProcessorArchitecture== @@ -1032,11 +1048,11 @@ char *getuname() else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) strncat(ret, "Enterprise x64 Edition ", ret_size -1 ); - else + else strncat(ret, "Standard x64 Edition ", ret_size -1 ); - ret_size-=strlen(ret) +1; + ret_size-=strlen(ret) +1; } else @@ -1048,10 +1064,10 @@ char *getuname() strncat(ret,"Enterprise Edition ",ret_size -1); else if ( osvi.wSuiteMask == VER_SUITE_BLADE ) strncat(ret,"Web Edition ",ret_size -1 ); - else + else strncat(ret, "Standard Edition ",ret_size -1); - ret_size-=strlen(ret) +1; + ret_size-=strlen(ret) +1; } } else if(osvi.dwMajorVersion==5 && osvi.dwMinorVersion==0) @@ -1060,25 +1076,25 @@ char *getuname() strncat(ret, "Datacenter Server ",ret_size -1); else if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) strncat(ret, "Advanced Server ",ret_size -1 ); - else + else strncat(ret, "Server ",ret_size -1); - ret_size-=strlen(ret) +1; + ret_size-=strlen(ret) +1; } else if(osvi.dwMajorVersion <= 4) /* Windows NT 4.0 */ { if( osvi.wSuiteMask & VER_SUITE_ENTERPRISE ) strncat(ret, "Server 4.0, Enterprise Edition ", ret_size -1 ); - else + else strncat(ret, "Server 4.0 ",ret_size -1); - + ret_size-=strlen(ret) +1; } } } /* Test for specific product on Windows NT 4.0 SP5 and earlier */ - else + else { HKEY hKey; char szProductType[81]; @@ -1091,7 +1107,7 @@ char *getuname() if(lRet == ERROR_SUCCESS) { char __wv[32]; - + lRet = RegQueryValueEx( hKey, "ProductType", NULL, NULL, (LPBYTE) szProductType, &dwBufLen); RegCloseKey( hKey ); @@ -1108,7 +1124,7 @@ char *getuname() ret_size-=strlen(ret) +1; memset(__wv, '\0', 32); - snprintf(__wv, 31, + snprintf(__wv, 31, "%d.%d ", (int)osvi.dwMajorVersion, (int)osvi.dwMinorVersion); @@ -1121,9 +1137,9 @@ char *getuname() /* Display service pack (if any) and build number. */ - if( osvi.dwMajorVersion == 4 && + if( osvi.dwMajorVersion == 4 && lstrcmpi( osvi.szCSDVersion, "Service Pack 6" ) == 0 ) - { + { HKEY hKey; LONG lRet; char __wp[64]; @@ -1134,8 +1150,8 @@ char *getuname() "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Hotfix\\Q246009", 0, KEY_QUERY_VALUE, &hKey ); if( lRet == ERROR_SUCCESS ) - snprintf(__wp, 63, "Service Pack 6a (Build %d)", - (int)osvi.dwBuildNumber & 0xFFFF ); + snprintf(__wp, 63, "Service Pack 6a (Build %d)", + (int)osvi.dwBuildNumber & 0xFFFF ); else /* Windows NT 4.0 prior to SP6a */ { snprintf(__wp, 63, "%s (Build %d)", @@ -1169,13 +1185,13 @@ char *getuname() { strncat(ret, "Microsoft Windows 95 ", ret_size -1); ret_size-=strlen(ret) +1; - } + } if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10) { strncat(ret, "Microsoft Windows 98 ", ret_size -1); ret_size-=strlen(ret) +1; - } + } if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90) { @@ -1183,7 +1199,7 @@ char *getuname() ret_size -1); ret_size-=strlen(ret) +1; - } + } break; case VER_PLATFORM_WIN32s: @@ -1197,10 +1213,10 @@ char *getuname() /* Adding ossec version */ snprintf(os_v, 128, " - %s %s", __name, __version); strncat(ret, os_v, ret_size -1); - - + + /* Returning system information */ - return(ret); + return(ret); } #endif diff --git a/src/shared/hash_op.c b/src/shared/hash_op.c index 322fb1c..20b7392 100755 --- a/src/shared/hash_op.c +++ b/src/shared/hash_op.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/shared/hash_op.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -11,9 +12,9 @@ * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ - -/* Common API for dealing with hashes/maps */ + +/* Common API for dealing with hashes/maps */ #include "shared.h" @@ -67,7 +68,7 @@ OSHash *OSHash_Create() self->initial_seed = os_getprime(random() % self->rows); self->constant = os_getprime(random() % self->rows); - + return(self); } @@ -81,8 +82,8 @@ void *OSHash_Free(OSHash *self) int i = 0; OSHashNode *curr_node; OSHashNode *next_node; - - + + /* Freeing each entry */ while(i <= self->rows) { @@ -102,7 +103,7 @@ void *OSHash_Free(OSHash *self) free(self->table); free(self); - return(NULL); + return(NULL); } @@ -143,7 +144,7 @@ int OSHash_setSize(OSHash *self, int new_size) return(1); } - + /* Getting next prime */ self->rows = os_getprime(new_size); if(self->rows == 0) @@ -151,7 +152,7 @@ int OSHash_setSize(OSHash *self, int new_size) return(0); } - + /* If we fail, the hash should not be used anymore */ self->table = realloc(self->table, (self->rows +1) * sizeof(OSHashNode *)); if(!self->table) @@ -175,6 +176,44 @@ int OSHash_setSize(OSHash *self, int new_size) } +/** int OSHash_Update(OSHash *self, char *key, void *data) + * Returns 0 on error (not found). + * Returns 1 on successduplicated key (not added) + * Key must not be NULL. + */ +int OSHash_Update(OSHash *self, char *key, void *data) +{ + unsigned int hash_key; + unsigned int index; + + OSHashNode *curr_node; + + + /* Generating hash of the message */ + hash_key = _os_genhash(self, key); + + + /* Getting array index */ + index = hash_key % self->rows; + + + /* Checking for duplicated entries in the index */ + curr_node = self->table[index]; + while(curr_node) + { + /* Checking for duplicated key -- not adding */ + if(strcmp(curr_node->key, key) == 0) + { + free(curr_node->data); + curr_node->data = data; + return(1); + } + curr_node = curr_node->next; + } + return(0); +} + + /** int OSHash_Add(OSHash *self, char *key, void *data) * Returns 0 on error. @@ -189,7 +228,7 @@ int OSHash_Add(OSHash *self, char *key, void *data) OSHashNode *curr_node; OSHashNode *new_node; - + /* Generating hash of the message */ hash_key = _os_genhash(self, key); @@ -197,7 +236,7 @@ int OSHash_Add(OSHash *self, char *key, void *data) /* Getting array index */ index = hash_key % self->rows; - + /* Checking for duplicated entries in the index */ curr_node = self->table[index]; @@ -212,7 +251,7 @@ int OSHash_Add(OSHash *self, char *key, void *data) curr_node = curr_node->next; } - + /* Creating new node */ new_node = calloc(1, sizeof(OSHashNode)); if(!new_node) @@ -235,7 +274,7 @@ int OSHash_Add(OSHash *self, char *key, void *data) new_node->next = self->table[index]; self->table[index] = new_node; } - + return(2); } @@ -252,7 +291,7 @@ void *OSHash_Get(OSHash *self, char *key) unsigned int index; OSHashNode *curr_node; - + /* Generating hash of the message */ hash_key = _os_genhash(self, key); @@ -260,7 +299,7 @@ void *OSHash_Get(OSHash *self, char *key) /* Getting array index */ index = hash_key % self->rows; - + /* Getting entry */ curr_node = self->table[index]; @@ -271,7 +310,7 @@ void *OSHash_Get(OSHash *self, char *key) { return(curr_node->data); } - + curr_node = curr_node->next; } diff --git a/src/shared/help.c b/src/shared/help.c index 96c2a7c..0d184f2 100755 --- a/src/shared/help.c +++ b/src/shared/help.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/shared/help.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. diff --git a/src/shared/list_op.c b/src/shared/list_op.c index 19e5e46..660dfbb 100755 --- a/src/shared/list_op.c +++ b/src/shared/list_op.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/shared/list_op.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -9,13 +10,13 @@ * Foundation */ -/* Common API for dealing with lists */ +/* Common API for dealing with lists */ #include "shared.h" -/* Create the list +/* Create the list * Return NULL on error */ OSList *OSList_Create() @@ -25,14 +26,14 @@ OSList *OSList_Create() my_list = calloc(1, sizeof(OSList)); if(!my_list) return(NULL); - + my_list->first_node = NULL; my_list->last_node = NULL; my_list->cur_node = NULL; my_list->currently_size = 0; my_list->max_size = 0; my_list->free_data_function = NULL; - + return(my_list); } @@ -47,7 +48,7 @@ int OSList_SetMaxSize(OSList *list, int max_size) { return(0); } - + /* Minimum size is 1 */ if(max_size <= 1) { @@ -69,7 +70,7 @@ int OSList_SetFreeDataPointer(OSList *list, void *free_data_function) { return(0); } - + list->free_data_function = free_data_function; return(1); } @@ -103,12 +104,12 @@ OSListNode *OSList_GetNextNode(OSList *list) { if(list->cur_node == NULL) return(NULL); - + list->cur_node = list->cur_node->next; - + return(list->cur_node); } - + /* Get the prev node from the list * Returns NULL at the beginning @@ -122,11 +123,11 @@ OSListNode *OSList_GetPrevNode(OSList *list) return(list->cur_node); } - + /* Get the currently node. * Returns null when no currently node is available - */ + */ OSListNode *OSList_GetCurrentlyNode(OSList *list) { return(list->cur_node); @@ -137,15 +138,15 @@ OSListNode *OSList_GetCurrentlyNode(OSList *list) void OSList_DeleteOldestNode(OSList *list) { OSListNode *next; - + if(list->first_node) { next = list->first_node->next; if(next) next->prev = NULL; else - list->last_node = next; - + list->last_node = next; + free(list->first_node); list->first_node = next; } @@ -215,14 +216,14 @@ void OSList_DeleteCurrentlyNode(OSList *list) { OSListNode *prev; OSListNode *next; - + if(list->cur_node == NULL) return; - + prev = list->cur_node->prev; next = list->cur_node->next; - + /* Setting the previous node of the next one * and the next node of the previous one.. :) */ @@ -246,7 +247,7 @@ void OSList_DeleteCurrentlyNode(OSList *list) list->last_node = NULL; list->first_node = NULL; } - + /* Freeing the node memory */ free(list->cur_node); @@ -262,7 +263,7 @@ void OSList_DeleteCurrentlyNode(OSList *list) */ int OSList_AddData(OSList *list, void *data) { - OSListNode *newnode; + OSListNode *newnode; /* Allocating memory for new node */ @@ -283,20 +284,20 @@ int OSList_AddData(OSList *list, void *data) { list->first_node = newnode; } - + /* If we have a last node, set the next to new node */ if(list->last_node) { list->last_node->next = newnode; } - - + + /* newnode become last node */ list->last_node = newnode; /* Increment list size */ list->currently_size++; - + /* if currently_size higher than the maximum size, remove the * oldest node (first one) */ @@ -314,10 +315,10 @@ int OSList_AddData(OSList *list, void *data) { list->free_data_function(list->first_node->data); } - + /* Clearing the memory */ free(list->first_node); - + /* First node become the ex first->next */ list->first_node = newnode; @@ -325,7 +326,7 @@ int OSList_AddData(OSList *list, void *data) list->currently_size--; } } - + return(1); } diff --git a/src/shared/math_op.c b/src/shared/math_op.c index 21ef109..b08f854 100755 --- a/src/shared/math_op.c +++ b/src/shared/math_op.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/shared/math_op.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -24,14 +25,14 @@ int os_getprime(int val) { int i; int max_i; - + /* Value can't be even */ if((val % 2) == 0) { val++; } - - + + do { /* We just need to check odd numbers up until half diff --git a/src/shared/mem_op.c b/src/shared/mem_op.c index d54bc02..8ba4ccb 100755 --- a/src/shared/mem_op.c +++ b/src/shared/mem_op.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/shared/mem_op.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -85,22 +86,22 @@ void os_FreeArray(char *ch1, char **ch2) free(ch1); ch1 = NULL; } - + /* Cleaning chat ** */ if(ch2) { char **nch2 = ch2; - + while(*ch2 != NULL) { free(*ch2); ch2++; } - + free(nch2); nch2 = NULL; } - + return; } diff --git a/src/shared/mq_op.c b/src/shared/mq_op.c index 81c2772..3f1d037 100755 --- a/src/shared/mq_op.c +++ b/src/shared/mq_op.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/shared/mq_op.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -21,12 +22,12 @@ */ int StartMQ(char * path, short int type) { - + if(type == READ) { return(OS_BindUnixDomain(path, 0660, OS_MAXSTR + 512)); } - + /* We give up to 21 seconds for the other end to * start */ @@ -62,7 +63,7 @@ int StartMQ(char * path, short int type) sleep(2); if((rc = OS_ConnectUnixDomain(path, OS_MAXSTR + 256)) < 0) { - merror(QUEUE_ERROR, __local_name, path, + merror(QUEUE_ERROR, __local_name, path, strerror(errno)); return(-1); } @@ -88,8 +89,8 @@ int SendMSG(int queue, char *message, char *locmsg, char loc) /* Checking for global locks */ os_wait(); - - + + if(loc == SECURE_MQ) { loc = message[0]; @@ -100,9 +101,14 @@ int SendMSG(int queue, char *message, char *locmsg, char loc) merror(FORMAT_ERROR, __local_name); return(0); } - + message++; /* Pointing now to the location */ - + + if(strncmp(message, "keepalive",9) == 0) + { + return(0); + } + snprintf(tmpstr,OS_MAXSTR,"%c:%s->%s",loc, locmsg, message); } else @@ -113,7 +119,7 @@ int SendMSG(int queue, char *message, char *locmsg, char loc) if(queue < 0) return(-1); - + /* We attempt 5 times to send the message if * the receiver socket is busy. * After the first error, we wait 1 second. @@ -134,7 +140,7 @@ int SendMSG(int queue, char *message, char *locmsg, char loc) return(-1); } - + /* Unable to send. Socket busy */ sleep(1); if(OS_SendUnix(queue, tmpstr, 0) < 0) @@ -157,10 +163,10 @@ int SendMSG(int queue, char *message, char *locmsg, char loc) { /* Message is going to be lost * if the application does not care - * about checking the error - */ + * about checking the error + */ close(queue); - queue = -1; + queue = -1; return(-1); } } diff --git a/src/shared/privsep_op.c b/src/shared/privsep_op.c index 1e0ce18..b24cb31 100755 --- a/src/shared/privsep_op.c +++ b/src/shared/privsep_op.c @@ -29,30 +29,30 @@ int Privsep_GetUser(char * name) { int os_uid = -1; - + struct passwd *pw; pw = getpwnam(name); if(pw == NULL) return(OS_INVALID); os_uid = (int)pw->pw_uid; - endpwent(); - + endpwent(); + return(os_uid); } int Privsep_GetGroup(char * name) { int os_gid = -1; - + struct group *grp; grp = getgrnam(name); if(grp == NULL) return(OS_INVALID); os_gid = (int)grp->gr_gid; - endgrent(); - + endgrent(); + return(os_gid); } @@ -72,16 +72,16 @@ int Privsep_SetUser(uid_t uid) int Privsep_SetGroup(gid_t gid) { if (setgroups(1, &gid) == -1) - return(OS_INVALID); - + return(OS_INVALID); + #ifndef HPUX if(setegid(gid) < 0) return(OS_INVALID); #endif - + if(setgid(gid) < 0) return(OS_INVALID); - + return(OS_SUCCESS); } @@ -89,12 +89,12 @@ int Privsep_Chroot(char * path) { if(chdir(path) < 0) return(OS_INVALID); - + if(chroot(path) < 0) return(OS_INVALID); - + chdir("/"); - + return(OS_SUCCESS); } diff --git a/src/shared/pthreads_op.c b/src/shared/pthreads_op.c index f88dcc1..4a8e0aa 100755 --- a/src/shared/pthreads_op.c +++ b/src/shared/pthreads_op.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/shared/pthreads_op.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. diff --git a/src/shared/read-agents.c b/src/shared/read-agents.c index 37e8bd4..814fb9d 100755 --- a/src/shared/read-agents.c +++ b/src/shared/read-agents.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/shared/read-agents.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -21,7 +22,7 @@ void free_agents(char **agent_list) int i; if(!agent_list) return; - + for(i = 0;;i++) { if(agent_list[i] == NULL) @@ -39,8 +40,8 @@ void free_agents(char **agent_list) #ifndef WIN32 /* Print syscheck attributes. */ -#define sk_strchr(x,y,z) z = strchr(x, y); if(z == NULL) return(0); else { *z = '\0'; z++; } -int _do_print_attrs_syscheck(char *prev_attrs, char *attrs, int csv_output, +#define sk_strchr(x,y,z) z = strchr(x, y); if(z == NULL) return(0); else { *z = '\0'; z++; } +int _do_print_attrs_syscheck(char *prev_attrs, char *attrs, int csv_output, int is_win, int number_of_changes) { char *p_size, *p_perm, *p_uid, *p_gid, *p_md5, *p_sha1; @@ -49,6 +50,13 @@ int _do_print_attrs_syscheck(char *prev_attrs, char *attrs, int csv_output, char perm_str[36]; + /* a deleted file has no attributes */ + if(strcmp(attrs, "-1") == 0) + { + printf("File deleted.\n"); + return(0); + } + /* Setting each value. */ size = attrs; sk_strchr(size, ':', perm); @@ -56,13 +64,15 @@ int _do_print_attrs_syscheck(char *prev_attrs, char *attrs, int csv_output, sk_strchr(uid, ':', gid); sk_strchr(gid, ':', md5); sk_strchr(md5, ':', sha1); - - if(strcmp(attrs, "-1") == 0) - { - printf("File deleted. "); - return(0); - } - else if(prev_attrs && (strcmp(prev_attrs, "-1") == 0)) + + p_size = size; + p_perm = perm; + p_uid = uid; + p_gid = gid; + p_md5 = md5; + p_sha1 = sha1; + + if(prev_attrs && (strcmp(prev_attrs, "-1") == 0)) { printf("File restored. "); } @@ -78,12 +88,6 @@ int _do_print_attrs_syscheck(char *prev_attrs, char *attrs, int csv_output, } else { - p_size = size; - p_perm = perm; - p_uid = uid; - p_gid = gid; - p_md5 = md5; - p_sha1 = sha1; printf("File added to the database. "); } @@ -102,14 +106,14 @@ int _do_print_attrs_syscheck(char *prev_attrs, char *attrs, int csv_output, case 1: printf("- 1st time modified.\n"); break; - case 2: + case 2: printf("- 2nd time modified.\n"); break; - case 3: + case 3: printf("- 3rd time modified.\n"); break; default: - printf("- Being ignored (3 or more changes).\n"); + printf("- Being ignored (3 or more changes).\n"); } } else @@ -120,22 +124,22 @@ int _do_print_attrs_syscheck(char *prev_attrs, char *attrs, int csv_output, perm_str[35] = '\0'; perm_int = atoi(perm); - snprintf(perm_str, 35, + snprintf(perm_str, 35, "%c%c%c%c%c%c%c%c%c", (perm_int & S_IRUSR)? 'r' : '-', (perm_int & S_IWUSR)? 'w' : '-', - + (perm_int & S_ISUID)? 's' : (perm_int & S_IXUSR)? 'x' : '-', - + (perm_int & S_IRGRP)? 'r' : '-', (perm_int & S_IWGRP)? 'w' : '-', - + (perm_int & S_ISGID)? 's' : (perm_int & S_IXGRP)? 'x' : '-', - - + + (perm_int & S_IROTH)? 'r' : '-', (perm_int & S_IWOTH)? 'w' : '-', (perm_int & S_ISVTX)? 't' : @@ -152,7 +156,7 @@ int _do_print_attrs_syscheck(char *prev_attrs, char *attrs, int csv_output, } printf(" Md5: %s%s\n", (strcmp(md5,p_md5) == 0)? " ": " >", md5); printf(" Sha1:%s%s\n", (strcmp(sha1,p_sha1) == 0)? " ": " >", sha1); - + /* Fixing entries. */ perm[-1] = ':'; @@ -167,12 +171,12 @@ int _do_print_attrs_syscheck(char *prev_attrs, char *attrs, int csv_output, /* Print information about a specific file. */ -int _do_print_file_syscheck(FILE *fp, char *fname, +int _do_print_file_syscheck(FILE *fp, char *fname, int update_counter, int csv_output) { int f_found = 0; struct tm *tm_time; - + char read_day[24 +1]; char buf[OS_MAXSTR + 1]; @@ -180,7 +184,7 @@ int _do_print_file_syscheck(FILE *fp, char *fname, OSStore *files_list; fpos_t init_pos; - + buf[OS_MAXSTR] = '\0'; read_day[24] = '\0'; @@ -208,11 +212,11 @@ int _do_print_file_syscheck(FILE *fp, char *fname, printf("\n** ERROR: fgetpos failed.\n"); return(0); } - - + + while(fgets(buf, OS_MAXSTR, fp) != NULL) { - if(buf[0] == '!' || buf[0] == '#') + if(buf[0] == '!' || buf[0] == '#' || buf[0] == '+') { int number_changes = 0; time_t change_time = 0; @@ -220,15 +224,15 @@ int _do_print_file_syscheck(FILE *fp, char *fname, char *changed_attrs; char *prev_attrs; - + if(strlen(buf) < 16) { fgetpos(fp, &init_pos); continue; } - - /* Removing new line. */ - buf[strlen(buf) -1] = '\0'; + + /* Removing new line. */ + buf[strlen(buf) -1] = '\0'; /* with update counter, we only modify the last entry. */ @@ -255,26 +259,26 @@ int _do_print_file_syscheck(FILE *fp, char *fname, changed_attrs = buf + 3; - + changed_file_name = strchr(changed_attrs, '!'); if(!changed_file_name) { fgetpos(fp, &init_pos); continue; } - - + + /* Getting time of change. */ changed_file_name[-1] = '\0'; changed_file_name++; change_time = (time_t)atoi(changed_file_name); - + changed_file_name = strchr(changed_file_name, ' '); - changed_file_name++; - + changed_file_name++; + /* Checking if the name should be printed. */ - if(!OSMatch_Execute(changed_file_name, strlen(changed_file_name), + if(!OSMatch_Execute(changed_file_name, strlen(changed_file_name), ®)) { fgetpos(fp, &init_pos); @@ -283,8 +287,8 @@ int _do_print_file_syscheck(FILE *fp, char *fname, f_found = 1; - - + + /* Reset the values. */ if(update_counter) { @@ -315,45 +319,45 @@ int _do_print_file_syscheck(FILE *fp, char *fname, } } - printf("\n**Counter updated for file '%s'\n\n", + printf("\n**Counter updated for file '%s'\n\n", changed_file_name); return(0); } - + tm_time = localtime(&change_time); strftime(read_day, 23, "%Y %h %d %T", tm_time); - - if(!csv_output) - printf("\n%s,%d - %s\n", read_day, number_changes, + + if(!csv_output) + printf("\n%s,%d - %s\n", read_day, number_changes, changed_file_name); - else - printf("%s,%s,%d\n", read_day, changed_file_name, + else + printf("%s,%s,%d\n", read_day, changed_file_name, number_changes); - - + + prev_attrs = OSStore_Get(files_list, changed_file_name); if(prev_attrs) { char *new_attrs; os_strdup(changed_attrs, new_attrs); - _do_print_attrs_syscheck(prev_attrs, changed_attrs, - csv_output, + _do_print_attrs_syscheck(prev_attrs, changed_attrs, + csv_output, changed_file_name[0] == '/'?0:1, number_changes); - + free(files_list->cur_node->data); - files_list->cur_node->data = new_attrs; + files_list->cur_node->data = new_attrs; } else { char *new_name; char *new_attrs; - + os_strdup(changed_attrs, new_attrs); os_strdup(changed_file_name, new_name); OSStore_Put(files_list, new_name, new_attrs); - _do_print_attrs_syscheck(NULL, + _do_print_attrs_syscheck(NULL, changed_attrs, csv_output, changed_file_name[0] == '/'?0:1, number_changes); @@ -368,7 +372,7 @@ int _do_print_file_syscheck(FILE *fp, char *fname, printf("\n** No entries found.\n"); } OSMatch_FreePattern(®); - + return(0); } @@ -379,16 +383,16 @@ int _do_print_syscheck(FILE *fp, int all_files, int csv_output) { int f_found = 0; struct tm *tm_time; - + char read_day[24 +1]; char saved_read_day[24 +1]; char buf[OS_MAXSTR + 1]; - + buf[OS_MAXSTR] = '\0'; read_day[24] = '\0'; saved_read_day[0] = '\0'; saved_read_day[24] = '\0'; - + while(fgets(buf, OS_MAXSTR, fp) != NULL) { if(buf[0] == '!' || buf[0] == '#') @@ -397,13 +401,13 @@ int _do_print_syscheck(FILE *fp, int all_files, int csv_output) time_t change_time = 0; char *changed_file_name; - + if(strlen(buf) < 16) continue; - - /* Removing new line. */ - buf[strlen(buf) -1] = '\0'; - + + /* Removing new line. */ + buf[strlen(buf) -1] = '\0'; + /* Checking number of changes. */ if(buf[1] == '!') @@ -418,23 +422,23 @@ int _do_print_syscheck(FILE *fp, int all_files, int csv_output) number_changes = 4; } } - + changed_file_name = strchr(buf +3, '!'); if(!changed_file_name) continue; - - + + f_found = 1; - - + + /* Getting time of change. */ changed_file_name++; change_time = atoi(changed_file_name); - + changed_file_name = strchr(changed_file_name, ' '); - changed_file_name++; - + changed_file_name++; + tm_time = localtime(&change_time); strftime(read_day, 23, "%Y %h %d", tm_time); if(strcmp(read_day, saved_read_day) != 0) @@ -444,12 +448,12 @@ int _do_print_syscheck(FILE *fp, int all_files, int csv_output) strncpy(saved_read_day, read_day, 23); } strftime(read_day, 23, "%Y %h %d %T", tm_time); - - if(!csv_output) - printf("%s,%d - %s\n", read_day, number_changes, + + if(!csv_output) + printf("%s,%d - %s\n", read_day, number_changes, changed_file_name); - else - printf("%s,%s,%d\n", read_day, changed_file_name, + else + printf("%s,%s,%d\n", read_day, changed_file_name, number_changes); } } @@ -458,13 +462,13 @@ int _do_print_syscheck(FILE *fp, int all_files, int csv_output) { printf("\n** No entries found.\n"); } - + return(0); } /* Print syscheck db (of modified files. */ -int print_syscheck(char *sk_name, char *sk_ip, char *fname, int print_registry, +int print_syscheck(char *sk_name, char *sk_ip, char *fname, int print_registry, int all_files, int csv_output, int update_counter) { FILE *fp; @@ -489,7 +493,7 @@ int print_syscheck(char *sk_name, char *sk_ip, char *fname, int print_registry, fp = fopen(tmp_file, "r+"); } - + else if(!print_registry) { /* Printing database */ @@ -556,12 +560,12 @@ int _do_get_rootcheckscan(FILE *fp) /* Print syscheck db (of modified files. */ -int _do_print_rootcheck(FILE *fp, int resolved, int time_last_scan, +int _do_print_rootcheck(FILE *fp, int resolved, int time_last_scan, int csv_output, int show_last) { int i = 0; int f_found = 0; - + /* Current time. */ time_t c_time; @@ -569,7 +573,7 @@ int _do_print_rootcheck(FILE *fp, int resolved, int time_last_scan, time_t s_time = 0; time_t i_time = 0; struct tm *tm_time; - + char old_day[24 +1]; char read_day[24 +1]; char buf[OS_MAXSTR + 1]; @@ -585,14 +589,14 @@ int _do_print_rootcheck(FILE *fp, int resolved, int time_last_scan, char *(ns_events[]) = {"Application Found:", "Windows Audit:", "Windows Malware:", - NULL}; - + NULL}; + buf[OS_MAXSTR] = '\0'; old_day[24] = '\0'; read_day[24] = '\0'; - + c_time = time(0); fseek(fp, 0, SEEK_SET); @@ -603,13 +607,13 @@ int _do_print_rootcheck(FILE *fp, int resolved, int time_last_scan, { tm_time = localtime((time_t *)&time_last_scan); strftime(read_day, 23, "%Y %h %d %T", tm_time); - + printf("\nLast scan: %s\n\n", read_day); } else if(resolved) printf("\nResolved events: \n\n"); else - printf("\nOutstanding events: \n\n"); + printf("\nOutstanding events: \n\n"); } @@ -625,7 +629,7 @@ int _do_print_rootcheck(FILE *fp, int resolved, int time_last_scan, if(tmp_str) *tmp_str = '\0'; - + /* Getting initial time. */ tmp_str = strchr(buf + 1, '!'); if(!tmp_str) @@ -639,10 +643,10 @@ int _do_print_rootcheck(FILE *fp, int resolved, int time_last_scan, tmp_str = strchr(tmp_str, ' '); if(!tmp_str) continue; - tmp_str++; - + tmp_str++; + + - /* Checking for resolved. */ if(time_last_scan > (s_time + 86400)) { @@ -666,12 +670,12 @@ int _do_print_rootcheck(FILE *fp, int resolved, int time_last_scan, { if(strncmp(tmp_str, ig_events[i], strlen(ig_events[i]) -1) == 0) break; - i++; + i++; } if(ig_events[i]) continue; - + /* Checking events that are not system audit. */ i = 0; while(ns_events[i]) @@ -680,13 +684,13 @@ int _do_print_rootcheck(FILE *fp, int resolved, int time_last_scan, break; i++; } - + tm_time = localtime((time_t *)&s_time); strftime(read_day, 23, "%Y %h %d %T", tm_time); tm_time = localtime((time_t *)&i_time); strftime(old_day, 23, "%Y %h %d %T", tm_time); - + if(!csv_output) { @@ -707,11 +711,11 @@ int _do_print_rootcheck(FILE *fp, int resolved, int time_last_scan, printf("%s,%s,%s,%s%s\n", resolved == 0?"outstanding":"resolved", read_day, old_day, ns_events[i] != NULL?"":"System Audit: ", - tmp_str); + tmp_str); } - - - + + + f_found++; } @@ -719,14 +723,14 @@ int _do_print_rootcheck(FILE *fp, int resolved, int time_last_scan, { printf("** No entries found.\n"); } - + return(0); } /* Print rootcheck db */ -int print_rootcheck(char *sk_name, char *sk_ip, char *fname, int resolved, +int print_rootcheck(char *sk_name, char *sk_ip, char *fname, int resolved, int csv_output, int show_last) { int ltime = 0; @@ -744,7 +748,7 @@ int print_rootcheck(char *sk_name, char *sk_ip, char *fname, int resolved, fp = fopen(tmp_file, "r+"); } - + else { /* Printing database */ @@ -789,14 +793,14 @@ int print_rootcheck(char *sk_name, char *sk_ip, char *fname, int resolved, #endif -/* Delete syscheck db */ +/* Delete syscheck db */ int delete_syscheck(char *sk_name, char *sk_ip, int full_delete) { FILE *fp; char tmp_file[513]; tmp_file[512] = '\0'; - + /* Deleting related files */ snprintf(tmp_file, 512, "%s/(%s) %s->syscheck", SYSCHECK_DIR, @@ -807,7 +811,7 @@ int delete_syscheck(char *sk_name, char *sk_ip, int full_delete) if(fp) fclose(fp); - if(full_delete) + if(full_delete) unlink(tmp_file); @@ -852,14 +856,14 @@ int delete_syscheck(char *sk_name, char *sk_ip, int full_delete) -/* Delete rootcheck db */ +/* Delete rootcheck db */ int delete_rootcheck(char *sk_name, char *sk_ip, int full_delete) { FILE *fp; char tmp_file[513]; tmp_file[512] = '\0'; - + /* Deleting related files */ snprintf(tmp_file, 512, "%s/(%s) %s->rootcheck", ROOTCHECK_DIR, @@ -870,7 +874,7 @@ int delete_rootcheck(char *sk_name, char *sk_ip, int full_delete) if(fp) fclose(fp); - if(full_delete) + if(full_delete) unlink(tmp_file); @@ -907,11 +911,11 @@ int delete_agentinfo(char *name) /* Deleting syscheck */ delete_syscheck(sk_name, sk_ip, 1); - + return(1); } - + /** char *print_agent_status(int status) * Prints the text representation of the agent status. @@ -947,7 +951,7 @@ int send_msg_to_agent(int msocket, char *msg, char *agt_id, char *exec) char agt_msg[OS_SIZE_1024 +1]; agt_msg[OS_SIZE_1024] = '\0'; - + if(!exec) { @@ -973,7 +977,7 @@ int send_msg_to_agent(int msocket, char *msg, char *agt_id, char *exec) } - + if((rc = OS_SendUnix(msocket, agt_msg, 0)) < 0) { if(rc == OS_SOCKBUSY) @@ -1002,7 +1006,7 @@ int send_msg_to_agent(int msocket, char *msg, char *agt_id, char *exec) int connect_to_remoted() { int arq = -1; - + if((arq = StartMQ(ARQUEUE, WRITE)) < 0) { merror(ARQ_ERROR, __local_name); @@ -1026,15 +1030,15 @@ int _get_time_rkscan(char *agent_name, char *agent_ip, agent_info *agt_info) /* Agent name of null, means it is the server info. */ if(agent_name == NULL) { - snprintf(buf, 1024, "%s/rootcheck", + snprintf(buf, 1024, "%s/rootcheck", ROOTCHECK_DIR); } else { - snprintf(buf, 1024, "%s/(%s) %s->rootcheck", + snprintf(buf, 1024, "%s/(%s) %s->rootcheck", ROOTCHECK_DIR, agent_name, agent_ip); } - + /* If file is not there, set to unknown. */ fp = fopen(buf, "r"); @@ -1046,7 +1050,7 @@ int _get_time_rkscan(char *agent_name, char *agent_ip, agent_info *agt_info) os_strdup("Unknown", agt_info->syscheck_endtime); return(0); } - + while(fgets(buf, 1024, fp) != NULL) { @@ -1072,7 +1076,7 @@ int _get_time_rkscan(char *agent_name, char *agent_ip, agent_info *agt_info) tmp_str = strchr(agt_info->syscheck_time, '\n'); if(tmp_str) *tmp_str = '\0'; - + continue; } @@ -1090,10 +1094,10 @@ int _get_time_rkscan(char *agent_name, char *agent_ip, agent_info *agt_info) tmp_str = strchr(agt_info->syscheck_endtime, '\n'); if(tmp_str) *tmp_str = '\0'; - + continue; } - + tmp_str = strstr(buf, "Starting rootcheck scan"); if(tmp_str) @@ -1142,7 +1146,7 @@ int _get_time_rkscan(char *agent_name, char *agent_ip, agent_info *agt_info) os_strdup("Unknown", agt_info->syscheck_time); if(!agt_info->syscheck_endtime) os_strdup("Unknown", agt_info->syscheck_endtime); - + fclose(fp); return(0); } @@ -1161,7 +1165,7 @@ char *_get_agent_keepalive(char *agent_name, char *agent_ip) { return(strdup("Not available")); } - + snprintf(buf, 1024, "%s/%s-%s", AGENTINFO_DIR, agent_name, agent_ip); if(stat(buf, &file_status) < 0) { @@ -1180,7 +1184,7 @@ int _get_agent_os(char *agent_name, char *agent_ip, agent_info *agt_info) FILE *fp; char buf[1024 +1]; - + /* Getting server info. */ if(!agent_name) { @@ -1213,7 +1217,7 @@ int _get_agent_os(char *agent_name, char *agent_ip, agent_info *agt_info) return(0); } - + snprintf(buf, 1024, "%s/%s-%s", AGENTINFO_DIR, agent_name, agent_ip); fp = fopen(buf, "r"); if(!fp) @@ -1222,8 +1226,8 @@ int _get_agent_os(char *agent_name, char *agent_ip, agent_info *agt_info) os_strdup("Unknown", agt_info->version); return(0); } - - + + if(fgets(buf, 1024, fp)) { char *ossec_version = NULL; @@ -1232,8 +1236,8 @@ int _get_agent_os(char *agent_name, char *agent_ip, agent_info *agt_info) ossec_version = strchr(buf, '\n'); if(ossec_version) *ossec_version = '\0'; - - + + ossec_version = strstr(buf, " - "); if(ossec_version) { @@ -1259,10 +1263,10 @@ int _get_agent_os(char *agent_name, char *agent_ip, agent_info *agt_info) } fclose(fp); - + os_strdup("Unknown", agt_info->os); os_strdup("Unknown", agt_info->version); - + return(0); } @@ -1276,7 +1280,7 @@ agent_info *get_agent_info(char *agent_name, char *agent_ip) char tmp_file[513]; char *agent_ip_pt = NULL; char *tmp_str = NULL; - + agent_info *agt_info = NULL; tmp_file[512] = '\0'; @@ -1314,7 +1318,7 @@ agent_info *get_agent_info(char *agent_name, char *agent_ip) if(tmp_str) *tmp_str = '\0'; - + /* Setting back the ip address. */ if(agent_ip_pt) @@ -1335,7 +1339,7 @@ int get_agent_status(char *agent_name, char *agent_ip) { char tmp_file[513]; char *agent_ip_pt = NULL; - + struct stat file_status; tmp_file[512] = '\0'; @@ -1344,9 +1348,9 @@ int get_agent_status(char *agent_name, char *agent_ip) /* Server info. */ if(agent_name == NULL) { - return(GA_STATUS_ACTIVE); + return(GA_STATUS_ACTIVE); } - + /* Removing the "/", since it is not present on the file. */ if((agent_ip_pt = strchr(agent_ip, '/'))) @@ -1368,7 +1372,7 @@ int get_agent_status(char *agent_name, char *agent_ip) { return(GA_STATUS_INV); } - + if(file_status.st_mtime > (time(0) - (3*NOTIFY_TIME + 30))) { @@ -1379,28 +1383,28 @@ int get_agent_status(char *agent_name, char *agent_ip) } - + /* List available agents. */ char **get_agents(int flag) { int f_size = 0; - + char **f_files = NULL; DIR *dp; struct dirent *entry; - + /* Opening the directory given */ dp = opendir(AGENTINFO_DIR); - if(!dp) + if(!dp) { merror("%s: Error opening directory: '%s': %s ", __local_name, AGENTINFO_DIR, strerror(errno)); return(NULL); - } + } /* Reading directory */ @@ -1409,7 +1413,7 @@ char **get_agents(int flag) int status = 0; char tmp_file[513]; tmp_file[512] = '\0'; - + /* Just ignore . and .. */ if((strcmp(entry->d_name,".") == 0) || (strcmp(entry->d_name,"..") == 0)) @@ -1424,7 +1428,7 @@ char **get_agents(int flag) if(stat(tmp_file, &file_status) < 0) continue; - + if(file_status.st_mtime > (time(0) - (3*NOTIFY_TIME + 30))) { status = 1; @@ -1437,7 +1441,7 @@ char **get_agents(int flag) continue; } } - + f_files = (char **)realloc(f_files, (f_size +2) * sizeof(char *)); if(!f_files) { @@ -1449,9 +1453,9 @@ char **get_agents(int flag) if(flag == GA_ALL_WSTATUS) { char agt_stat[512]; - + snprintf(agt_stat, sizeof(agt_stat) -1, "%s %s", - entry->d_name, status == 1?"active":"disconnected"); + entry->d_name, status == 1?"active":"disconnected"); os_strdup(agt_stat, f_files[f_size]); } @@ -1459,15 +1463,15 @@ char **get_agents(int flag) { os_strdup(entry->d_name, f_files[f_size]); } - + f_files[f_size +1] = NULL; - + f_size++; } - + closedir(dp); return(f_files); } - + /* EOF */ diff --git a/src/shared/read-alert.c b/src/shared/read-alert.c index b9553b6..b5d8a3b 100755 --- a/src/shared/read-alert.c +++ b/src/shared/read-alert.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/shared/read-alert.c, 2011/11/09 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -27,11 +28,29 @@ #define RULE_BEGIN_SZ 6 #define SRCIP_BEGIN "Src IP: " #define SRCIP_BEGIN_SZ 8 +#define GEOIP_BEGIN_SRC "Src Location: " +#define GEOIP_BEGIN_SRC_SZ 14 +#define GEOIP_BEGIN_DST "Dst Location: " +#define GEOIP_BEGIN_DST_SZ 14 +#define SRCPORT_BEGIN "Src Port: " +#define SRCPORT_BEGIN_SZ 10 +#define DSTIP_BEGIN "Dst IP: " +#define DSTIP_BEGIN_SZ 8 +#define DSTPORT_BEGIN "Dst Port: " +#define DSTPORT_BEGIN_SZ 10 #define USER_BEGIN "User: " #define USER_BEGIN_SZ 6 #define ALERT_MAIL "mail" #define ALERT_MAIL_SZ 4 #define ALERT_AR "active-response" +#define OLDMD5_BEGIN "Old md5sum was: " +#define OLDMD5_BEGIN_SZ 16 +#define NEWMD5_BEGIN "New md5sum is : " +#define NEWMD5_BEGIN_SZ 16 +#define OLDSHA1_BEGIN "Old sha1sum was: " +#define OLDSHA1_BEGIN_SZ 17 +#define NEWSHA1_BEGIN "New sha1sum is : " +#define NEWSHA1_BEGIN_SZ 17 /** void FreeAlertData(alert_data *al_data) @@ -39,38 +58,98 @@ */ void FreeAlertData(alert_data *al_data) { + char **p; + + if(al_data->alertid) + { + free(al_data->alertid); + al_data->alertid = NULL; + } if(al_data->date) { free(al_data->date); + al_data->date = NULL; } if(al_data->location) { free(al_data->location); + al_data->location = NULL; } if(al_data->comment) { free(al_data->comment); + al_data->comment = NULL; } if(al_data->group) { free(al_data->group); + al_data->group = NULL; } if(al_data->srcip) { free(al_data->srcip); + al_data->srcip = NULL; + } + if(al_data->dstip) + { + free(al_data->dstip); + al_data->dstip = NULL; } if(al_data->user) { free(al_data->user); + al_data->user = NULL; + } + if(al_data->filename) + { + free(al_data->filename); + al_data->filename = NULL; + } + if(al_data->old_md5) + { + free(al_data->old_md5); + al_data->old_md5 = NULL; + } + if(al_data->new_md5) + { + free(al_data->new_md5); + al_data->new_md5 = NULL; + } + if(al_data->old_sha1) + { + free(al_data->old_sha1); + al_data->old_sha1 = NULL; + } + if(al_data->new_sha1) + { + free(al_data->new_sha1); + al_data->new_sha1 = NULL; } if(al_data->log) { - while(*(al_data->log)) + p = al_data->log; + + while(*(p)) { - free(*(al_data->log)); - al_data->log++; + free(*(p)); + *(p) = NULL; + p++; } + free(al_data->log); + al_data->log = NULL; + } +#ifdef GEOIP + if (al_data->geoipdatasrc) + { + free(al_data->geoipdatasrc); + al_data->geoipdatasrc = NULL; } + if (al_data->geoipdatadst) + { + free(al_data->geoipdatadst); + al_data->geoipdatadst = NULL; + } +#endif free(al_data); al_data = NULL; } @@ -81,33 +160,46 @@ void FreeAlertData(alert_data *al_data) */ alert_data *GetAlertData(int flag, FILE *fp) { - int _r = 0, log_size; + int _r = 0, log_size = 0, issyscheck = 0; char *p; + char *alertid = NULL; char *date = NULL; char *comment = NULL; char *location = NULL; char *srcip = NULL; + char *dstip = NULL; char *user = NULL; char *group = NULL; + char *filename = NULL; + char *old_md5 = NULL; + char *new_md5 = NULL; + char *old_sha1 = NULL; + char *new_sha1 = NULL; char **log = NULL; - int level, rule; - +#ifdef GEOIP + char *geoipdatasrc = NULL; + char *geoipdatadst = NULL; +#endif + int level, rule, srcport = 0, dstport = 0; + + char str[OS_BUFFER_SIZE+1]; str[OS_BUFFER_SIZE]='\0'; while(fgets(str, OS_BUFFER_SIZE, fp) != NULL) { - + /* Enf of alert */ - if(strcmp(str, "\n") == 0) + if(strcmp(str, "\n") == 0 && log_size > 0) { /* Found in here */ if(_r == 2) { alert_data *al_data; os_calloc(1, sizeof(alert_data), al_data); + al_data->alertid = alertid; al_data->level = level; al_data->rule = rule; al_data->location = location; @@ -115,20 +207,46 @@ alert_data *GetAlertData(int flag, FILE *fp) al_data->group = group; al_data->log = log; al_data->srcip = srcip; + al_data->srcport = srcport; + al_data->dstip = dstip; + al_data->dstport = dstport; al_data->user = user; al_data->date = date; - + al_data->filename = filename; +#ifdef GEOIP + al_data->geoipdatasrc = geoipdatasrc; + al_data->geoipdatadst = geoipdatadst; +#endif + al_data->old_md5 = old_md5; + al_data->new_md5 = new_md5; + al_data->old_sha1 = old_sha1; + al_data->new_sha1 = new_sha1; + + return(al_data); } _r = 0; } - - + + /* Checking for the header */ if(strncmp(ALERT_BEGIN, str, ALERT_BEGIN_SZ) == 0) { + char *m; + int z = 0; p = str + ALERT_BEGIN_SZ + 1; - + + m = strstr(p, ":"); + if (!m) + { + continue; + } + + z = strlen(p) - strlen(m); + os_realloc(alertid, (z + 1)*sizeof(char *), alertid); + strncpy(alertid, p, z); + alertid[z] = '\0'; + /* Searching for email flag */ p = strchr(p, ' '); if(!p) @@ -137,10 +255,10 @@ alert_data *GetAlertData(int flag, FILE *fp) } p++; - - - /* Checking for the flags */ - if((flag & CRALERT_MAIL_SET) && + + + /* Checking for the flags */ + if((flag & CRALERT_MAIL_SET) && (strncmp(ALERT_MAIL, p, ALERT_MAIL_SZ) != 0)) { continue; @@ -154,6 +272,10 @@ alert_data *GetAlertData(int flag, FILE *fp) /* Cleaning new line from group */ os_clearnl(group, p); + if(group != NULL && strstr(group, "syscheck") != NULL) + { + issyscheck = 1; + } } @@ -164,16 +286,16 @@ alert_data *GetAlertData(int flag, FILE *fp) if(_r < 1) continue; - - + + /*** Extract information from the event ***/ - + /* r1 means: 2006 Apr 13 16:15:17 /var/log/auth.log */ if(_r == 1) { /* Clear new line */ os_clearnl(str, p); - + p = strchr(str, ':'); if(p) { @@ -196,22 +318,22 @@ alert_data *GetAlertData(int flag, FILE *fp) /* If not, str is date and p is the location */ if(date || location) merror("ZZZ Merror date or location not NULL"); - + os_strdup(str, date); - os_strdup(p, location); + os_strdup(p, location); _r = 2; log_size = 0; continue; } - + else if(_r == 2) { /* Rule begin */ if(strncmp(RULE_BEGIN, str, RULE_BEGIN_SZ) == 0) { os_clearnl(str,p); - + p = str + RULE_BEGIN_SZ; rule = atoi(p); @@ -226,17 +348,17 @@ alert_data *GetAlertData(int flag, FILE *fp) if(!p) goto l_error; - + level = atoi(p); - + /* Getting the comment */ p = strchr(p, '\''); if(!p) goto l_error; - + p++; os_strdup(p, comment); - + /* Must have the closing \' */ p = strrchr(comment, '\''); if(p) @@ -248,30 +370,117 @@ alert_data *GetAlertData(int flag, FILE *fp) goto l_error; } } - + /* srcip */ else if(strncmp(SRCIP_BEGIN, str, SRCIP_BEGIN_SZ) == 0) { os_clearnl(str,p); - + p = str + SRCIP_BEGIN_SZ; os_strdup(p, srcip); } +#ifdef GEOIP + /* GeoIP Source Location */ + else if (strncmp(GEOIP_BEGIN_SRC, str, GEOIP_BEGIN_SRC_SZ) == 0) + { + os_clearnl(str,p); + p = str + GEOIP_BEGIN_SRC_SZ; + os_strdup(p, geoipdatasrc); + } +#endif + /* srcport */ + else if(strncmp(SRCPORT_BEGIN, str, SRCPORT_BEGIN_SZ) == 0) + { + os_clearnl(str,p); + + p = str + SRCPORT_BEGIN_SZ; + srcport = atoi(p); + } + /* dstip */ + else if(strncmp(DSTIP_BEGIN, str, DSTIP_BEGIN_SZ) == 0) + { + os_clearnl(str,p); + + p = str + DSTIP_BEGIN_SZ; + os_strdup(p, dstip); + } +#ifdef GEOIP + /* GeoIP Destination Location */ + else if (strncmp(GEOIP_BEGIN_DST, str, GEOIP_BEGIN_DST_SZ) == 0) + { + os_clearnl(str,p); + p = str + GEOIP_BEGIN_DST_SZ; + os_strdup(p, geoipdatadst); + } +#endif + /* dstport */ + else if(strncmp(DSTPORT_BEGIN, str, DSTPORT_BEGIN_SZ) == 0) + { + os_clearnl(str,p); + + p = str + DSTPORT_BEGIN_SZ; + dstport = atoi(p); + } /* username */ else if(strncmp(USER_BEGIN, str, USER_BEGIN_SZ) == 0) { os_clearnl(str,p); - + p = str + USER_BEGIN_SZ; os_strdup(p, user); } + /* Old MD5 */ + else if(strncmp(OLDMD5_BEGIN, str, OLDMD5_BEGIN_SZ) == 0) + { + os_clearnl(str,p); + + p = str + OLDMD5_BEGIN_SZ; + os_strdup(p, old_md5); + } + /* New MD5 */ + else if(strncmp(NEWMD5_BEGIN, str, NEWMD5_BEGIN_SZ) == 0) + { + os_clearnl(str,p); + + p = str + NEWMD5_BEGIN_SZ; + os_strdup(p, new_md5); + } + /* Old SHA1 */ + else if(strncmp(OLDSHA1_BEGIN, str, OLDSHA1_BEGIN_SZ) == 0) + { + os_clearnl(str,p); + + p = str + OLDSHA1_BEGIN_SZ; + os_strdup(p, old_sha1); + } + /* New SHA1 */ + else if(strncmp(NEWSHA1_BEGIN, str, NEWSHA1_BEGIN_SZ) == 0) + { + os_clearnl(str,p); + + p = str + NEWSHA1_BEGIN_SZ; + os_strdup(p, new_sha1); + } /* It is a log message */ else if(log_size < 20) { os_clearnl(str,p); - + + if(str != NULL && issyscheck == 1) + { + if(strncmp(str, "Integrity checksum changed for: '",33) == 0) + { + filename = strdup(str+33); + if(filename) + { + filename[strlen(filename) -1] = '\0'; + } + } + issyscheck = 0; + } + os_realloc(log, (log_size +2)*sizeof(char *), log); - os_strdup(str, log[log_size]); + os_strdup(str, log[log_size]); log_size++; log[log_size] = NULL; } @@ -279,7 +488,7 @@ alert_data *GetAlertData(int flag, FILE *fp) continue; l_error: - + /* Freeing the memory */ _r = 0; if(date) @@ -302,16 +511,56 @@ alert_data *GetAlertData(int flag, FILE *fp) free(srcip); srcip = NULL; } +#ifdef GEOIP + if(geoipdatasrc) + { + free(geoipdatasrc); + geoipdatasrc = NULL; + } + if(geoipdatadst) + { + free(geoipdatadst); + geoipdatadst = NULL; + } +#endif if(user) { free(user); user = NULL; } + if(filename) + { + free(filename); + filename = NULL; + } if(group) { free(group); group = NULL; } + if(old_md5) + { + free(old_md5); + old_md5 = NULL; + } + + if(new_md5) + { + free(new_md5); + new_md5 = NULL; + } + + if(old_sha1) + { + free(old_sha1); + old_sha1 = NULL; + } + + if(new_sha1) + { + free(new_sha1); + new_sha1 = NULL; + } while(log_size > 0) { log_size--; @@ -323,6 +572,12 @@ alert_data *GetAlertData(int flag, FILE *fp) } } + if(alertid) + { + free(alertid); + alertid = NULL; + } + /* We need to clean end of file before returning */ clearerr(fp); return(NULL); diff --git a/src/shared/regex_op.c b/src/shared/regex_op.c index 7478c31..8bb0322 100755 --- a/src/shared/regex_op.c +++ b/src/shared/regex_op.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/shared/regex_op.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -23,11 +24,11 @@ int OS_PRegex(char *str, char *regex) { regex_t preg; - + if(!str || !regex) return(0); - - + + if(regcomp(&preg, regex, REG_EXTENDED|REG_NOSUB) != 0) { merror("%s: Posix Regex compile error (%s).", __local_name, regex); @@ -43,7 +44,7 @@ int OS_PRegex(char *str, char *regex) regfree(&preg); return(1); - + } #endif diff --git a/src/shared/report_op.c b/src/shared/report_op.c index 06dc8b4..ede6310 100755 --- a/src/shared/report_op.c +++ b/src/shared/report_op.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/shared/report_op.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -35,12 +36,12 @@ void l_print_out(const char *msg, ...) /* Sort function used by OSStore sort. - * Returns if d1 > d2. + * Returns if d1 > d2. */ void *_os_report_sort_compare(void *d1, void *d2) { OSList *d1l = (OSList *)d1; - OSList *d2l = (OSList *)d2; + OSList *d2l = (OSList *)d2; if(d1l->currently_size > d2l->currently_size) { @@ -71,7 +72,7 @@ void _os_header_print(int t, char *hname) int _os_report_str_int_compare(char *str, int id) { int pt_check = 0; - + do { if((*str == ',')||(*str == ' ')) @@ -151,6 +152,13 @@ int _os_report_check_filters(alert_data *al_data, report_filter *r_filter) return(0); } } + if(r_filter->files) + { + if(!strstr(al_data->filename, r_filter->files)) + { + return(0); + } + } return(1); } @@ -207,11 +215,19 @@ int _report_filter_value(char *filter_by, int prev_filter) } return(prev_filter); } + else if(strcmp(filter_by, "filename") == 0) + { + if(!(prev_filter & REPORT_REL_FILE)) + { + prev_filter|=REPORT_REL_FILE; + } + return(prev_filter); + } else { merror("%s: ERROR: Invalid relation '%s'.", __local_name, filter_by); return(-1); - } + } } @@ -222,13 +238,13 @@ int _os_report_print_related(int print_related, OSList *st_data) OSListNode *list_entry; alert_data *list_aldata; alert_data *saved_aldata; - - + + list_entry = OSList_GetFirstNode(st_data); while(list_entry) { saved_aldata = (alert_data *)list_entry->data; - + /* Removing duplicates. */ list_entry = list_entry->prev; while(list_entry) @@ -263,7 +279,10 @@ int _os_report_print_related(int print_related, OSList *st_data) else if(print_related & REPORT_REL_USER) { list_aldata = (alert_data *)list_entry->data; - if(strcmp(list_aldata->user, saved_aldata->user) == 0) + if(list_aldata->user == NULL || saved_aldata->user == NULL) + { + } + else if(strcmp(list_aldata->user, saved_aldata->user) == 0) { break; } @@ -272,7 +291,10 @@ int _os_report_print_related(int print_related, OSList *st_data) else if(print_related & REPORT_REL_SRCIP) { list_aldata = (alert_data *)list_entry->data; - if(strcmp(list_aldata->srcip, saved_aldata->srcip) == 0) + if(list_aldata->srcip == NULL || saved_aldata->srcip == NULL) + { + } + else if(strcmp(list_aldata->srcip, saved_aldata->srcip) == 0) { break; } @@ -286,6 +308,17 @@ int _os_report_print_related(int print_related, OSList *st_data) break; } } + else if(print_related & REPORT_REL_FILE) + { + list_aldata = (alert_data *)list_entry->data; + if(list_aldata->filename == NULL || saved_aldata->filename == NULL) + { + } + else if(strcmp(list_aldata->filename, saved_aldata->filename) == 0) + { + break; + } + } list_entry = list_entry->prev; } @@ -297,12 +330,14 @@ int _os_report_print_related(int print_related, OSList *st_data) l_print_out(" group: '%s'", saved_aldata->group); else if(print_related & REPORT_REL_RULE) l_print_out(" rule: '%d'", saved_aldata->rule); - else if(print_related & REPORT_REL_SRCIP) + else if(print_related & REPORT_REL_SRCIP && saved_aldata->srcip) l_print_out(" srcip: '%s'", saved_aldata->srcip); - else if(print_related & REPORT_REL_USER) + else if(print_related & REPORT_REL_USER && saved_aldata->user) l_print_out(" user: '%s'", saved_aldata->user); else if(print_related & REPORT_REL_LEVEL) l_print_out(" level: '%d'", saved_aldata->level); + else if(print_related & REPORT_REL_FILE && saved_aldata->filename) + l_print_out(" filename: '%s'", saved_aldata->filename); } list_entry = OSList_GetNextNode(st_data); @@ -347,7 +382,7 @@ void os_report_printtop(void *topstore_pt, char *hname, int print_related) int dopdout = 0; OSStore *topstore = (OSStore *)topstore_pt; OSStoreNode *next_node; - + next_node = OSStore_GetFirstNode(topstore); while(next_node) { @@ -396,6 +431,8 @@ void os_report_printtop(void *topstore_pt, char *hname, int print_related) _os_report_print_related(REPORT_REL_GROUP, st_data); if(print_related & REPORT_REL_LEVEL) _os_report_print_related(REPORT_REL_LEVEL, st_data); + if(print_related & REPORT_REL_FILE) + _os_report_print_related(REPORT_REL_FILE, st_data); } @@ -408,7 +445,7 @@ void os_report_printtop(void *topstore_pt, char *hname, int print_related) l_print_out(" "); l_print_out(" "); } - return; + return; } @@ -420,11 +457,11 @@ void os_ReportdStart(report_filter *r_filter) char *first_alert = NULL; char *last_alert = NULL; void **data_to_clean = NULL; - - - time_t tm; - struct tm *p; - + + + time_t tm; + struct tm *p; + file_queue *fileq; alert_data *al_data; @@ -466,10 +503,12 @@ void os_ReportdStart(report_filter *r_filter) r_filter->top_rule = OSStore_Create(); r_filter->top_group = OSStore_Create(); r_filter->top_location = OSStore_Create(); - + r_filter->top_files = OSStore_Create(); + Init_FileQueue(fileq, p, CRALERT_READ_ALL|CRALERT_FP_SET); + /* Reading the alerts. */ while(1) { @@ -481,7 +520,7 @@ void os_ReportdStart(report_filter *r_filter) } alerts_processed++; - + /* Checking the filters. */ if(!_os_report_check_filters(al_data, r_filter)) @@ -489,8 +528,8 @@ void os_ReportdStart(report_filter *r_filter) FreeAlertData(al_data); continue; } - - + + alerts_filtered++; data_to_clean = os_AddPtArray(al_data, data_to_clean); @@ -499,15 +538,15 @@ void os_ReportdStart(report_filter *r_filter) if(!first_alert) first_alert = al_data->date; last_alert = al_data->date; - - + + /* Adding source ip if it is set properly. */ - if(strcmp(al_data->srcip, "(none)") != 0) + if(al_data->srcip != NULL && strcmp(al_data->srcip, "(none)") != 0) _os_report_add_tostore(al_data->srcip, r_filter->top_srcip, al_data); - + /* Adding user if it is set properly. */ - if(strcmp(al_data->user, "(none)") != 0) + if(al_data->user != NULL && strcmp(al_data->user, "(none)") != 0) _os_report_add_tostore(al_data->user, r_filter->top_user, al_data); @@ -518,10 +557,10 @@ void os_ReportdStart(report_filter *r_filter) mrule[76] = '\0'; snprintf(mlevel, 16, "Severity %d" , al_data->level); snprintf(mrule, 76, "%d - %s" , al_data->rule, al_data->comment); - - _os_report_add_tostore(strdup(mlevel), r_filter->top_level, + + _os_report_add_tostore(strdup(mlevel), r_filter->top_level, al_data); - _os_report_add_tostore(strdup(mrule), r_filter->top_rule, + _os_report_add_tostore(strdup(mrule), r_filter->top_rule, al_data); } @@ -543,8 +582,8 @@ void os_ReportdStart(report_filter *r_filter) mgroup++; continue; } - - _os_report_add_tostore(tmp_str, r_filter->top_group, + + _os_report_add_tostore(tmp_str, r_filter->top_group, al_data); mgroup++; } @@ -556,16 +595,23 @@ void os_ReportdStart(report_filter *r_filter) tmp_str++; if(*tmp_str != '\0') { - _os_report_add_tostore(tmp_str, r_filter->top_group, + _os_report_add_tostore(tmp_str, r_filter->top_group, al_data); } } } - /* Adding to the location top filter. */ - _os_report_add_tostore(al_data->location, r_filter->top_location, + /* Adding to the location top filter. */ + _os_report_add_tostore(al_data->location, r_filter->top_location, al_data); + + + if(al_data->filename != NULL) + { + _os_report_add_tostore(al_data->filename, r_filter->top_files, + al_data); + } } /* No report available */ @@ -574,15 +620,15 @@ void os_ReportdStart(report_filter *r_filter) if(!r_filter->report_name) merror("%s: INFO: Report completed and zero alerts post-filter.", __local_name); else - merror("%s: INFO: Report '%s' completed and zero alerts post-filter.", __local_name, r_filter->report_name); + merror("%s: INFO: Report '%s' completed and zero alerts post-filter.", __local_name, r_filter->report_name); return; } - + if(r_filter->report_name) verbose("%s: INFO: Report '%s' completed. Creating output...", __local_name, r_filter->report_name); else - verbose("%s: INFO: Report completed. Creating output...", __local_name); + verbose("%s: INFO: Report completed. Creating output...", __local_name); l_print_out(" "); @@ -591,66 +637,74 @@ void os_ReportdStart(report_filter *r_filter) else l_print_out("Report completed. =="); l_print_out("------------------------------------------------"); - + l_print_out("->Processed alerts: %d", alerts_processed); l_print_out("->Post-filtering alerts: %d", alerts_filtered); l_print_out("->First alert: %s", first_alert); l_print_out("->Last alert: %s", last_alert); l_print_out(" "); l_print_out(" "); - + OSStore_Sort(r_filter->top_srcip, _os_report_sort_compare); OSStore_Sort(r_filter->top_user, _os_report_sort_compare); OSStore_Sort(r_filter->top_level, _os_report_sort_compare); OSStore_Sort(r_filter->top_group, _os_report_sort_compare); OSStore_Sort(r_filter->top_location, _os_report_sort_compare); OSStore_Sort(r_filter->top_rule, _os_report_sort_compare); - + OSStore_Sort(r_filter->top_files, _os_report_sort_compare); + if(r_filter->top_srcip) os_report_printtop(r_filter->top_srcip, "Source ip", 0); - + if(r_filter->top_user) os_report_printtop(r_filter->top_user, "Username", 0); - + if(r_filter->top_level) os_report_printtop(r_filter->top_level, "Level", 0); - + if(r_filter->top_group) os_report_printtop(r_filter->top_group, "Group", 0); - + if(r_filter->top_location) os_report_printtop(r_filter->top_location, "Location", 0); - + if(r_filter->top_rule) os_report_printtop(r_filter->top_rule, "Rule", 0); + if(r_filter->top_files) + os_report_printtop(r_filter->top_files, "Filenames", 0); + /* Print related events. */ if(r_filter->related_srcip) - os_report_printtop(r_filter->top_srcip, "Source ip", + os_report_printtop(r_filter->top_srcip, "Source ip", r_filter->related_srcip); if(r_filter->related_user) - os_report_printtop(r_filter->top_user, "Username", + os_report_printtop(r_filter->top_user, "Username", r_filter->related_user); if(r_filter->related_level) - os_report_printtop(r_filter->top_level, "Level", + os_report_printtop(r_filter->top_level, "Level", r_filter->related_level); if(r_filter->related_group) - os_report_printtop(r_filter->top_group, "Group", + os_report_printtop(r_filter->top_group, "Group", r_filter->related_group); - + if(r_filter->related_location) - os_report_printtop(r_filter->top_location, "Location", + os_report_printtop(r_filter->top_location, "Location", r_filter->related_location); - + if(r_filter->related_rule) - os_report_printtop(r_filter->top_rule, "Rule", + os_report_printtop(r_filter->top_rule, "Rule", r_filter->related_rule); - - + + if(r_filter->related_file) + os_report_printtop(r_filter->top_files, "Filename", + r_filter->related_file); + + /* If we have to dump the alerts. */ if(data_to_clean) { @@ -682,39 +736,43 @@ void os_ReportdStart(report_filter *r_filter) * report_filter *r_filter) * Checks the configuration filters. */ -int os_report_configfilter(char *filter_by, char *filter_value, +int os_report_configfilter(char *filter_by, char *filter_value, report_filter *r_filter, int arg_type) { if(!filter_by || !filter_value) { return(-1); } - + if(arg_type == REPORT_FILTER) { if(strcmp(filter_by, "group") == 0) { - r_filter->group = filter_value; + r_filter->group = filter_value; } else if(strcmp(filter_by, "rule") == 0) { - r_filter->rule = filter_value; + r_filter->rule = filter_value; } else if(strcmp(filter_by, "level") == 0) { - r_filter->level = filter_value; + r_filter->level = filter_value; } else if(strcmp(filter_by, "location") == 0) { - r_filter->location = filter_value; + r_filter->location = filter_value; } else if(strcmp(filter_by, "user") == 0) { - r_filter->user = filter_value; + r_filter->user = filter_value; } else if(strcmp(filter_by, "srcip") == 0) { - r_filter->srcip = filter_value; + r_filter->srcip = filter_value; + } + else if(strcmp(filter_by, "filename") == 0) + { + r_filter->files = filter_value; } else { @@ -726,7 +784,7 @@ int os_report_configfilter(char *filter_by, char *filter_value, { if(strcmp(filter_by, "group") == 0) { - r_filter->related_group = + r_filter->related_group = _report_filter_value(filter_value, r_filter->related_group); if(r_filter->related_group == -1) @@ -734,7 +792,7 @@ int os_report_configfilter(char *filter_by, char *filter_value, } else if(strcmp(filter_by, "rule") == 0) { - r_filter->related_rule = + r_filter->related_rule = _report_filter_value(filter_value, r_filter->related_rule); if(r_filter->related_rule == -1) @@ -742,7 +800,7 @@ int os_report_configfilter(char *filter_by, char *filter_value, } else if(strcmp(filter_by, "level") == 0) { - r_filter->related_level = + r_filter->related_level = _report_filter_value(filter_value, r_filter->related_level); if(r_filter->related_level == -1) @@ -750,7 +808,7 @@ int os_report_configfilter(char *filter_by, char *filter_value, } else if(strcmp(filter_by, "location") == 0) { - r_filter->related_location = + r_filter->related_location = _report_filter_value(filter_value, r_filter->related_location); if(r_filter->related_location == -1) @@ -758,7 +816,7 @@ int os_report_configfilter(char *filter_by, char *filter_value, } else if(strcmp(filter_by, "srcip") == 0) { - r_filter->related_srcip = + r_filter->related_srcip = _report_filter_value(filter_value, r_filter->related_srcip); if(r_filter->related_srcip == -1) @@ -766,12 +824,20 @@ int os_report_configfilter(char *filter_by, char *filter_value, } else if(strcmp(filter_by, "user") == 0) { - r_filter->related_user = + r_filter->related_user = _report_filter_value(filter_value, r_filter->related_user); - + if(r_filter->related_user == -1) return(-1); } + else if(strcmp(filter_by, "filename") == 0) + { + r_filter->related_file = + _report_filter_value(filter_value, r_filter->related_file); + + if(r_filter->related_file == -1) + return(-1); + } else { merror("%s: ERROR: Invalid related entry '%s'.", __local_name, filter_by); diff --git a/src/shared/rules_op.c b/src/shared/rules_op.c index 58481ec..d4a6b5f 100755 --- a/src/shared/rules_op.c +++ b/src/shared/rules_op.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/shared/rules_op.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -24,7 +25,7 @@ /** Prototypes **/ -int _OS_GetRulesAttributes(char **attributes, +int _OS_GetRulesAttributes(char **attributes, char **values, RuleInfo *ruleinfo_pt); RuleInfo *_OS_AllocateRule(); @@ -35,8 +36,8 @@ RuleInfo *_OS_AllocateRule(); /* Rules_OP_ReadRules, v0.3, 2005/03/21 * Read the log rules. * v0.3: Fixed many memory problems. - */ -int OS_ReadXMLRules(char *rulefile, + */ +int OS_ReadXMLRules(char *rulefile, void *(*ruleact_function)(RuleInfo *rule, void *data), void *data) { @@ -44,9 +45,9 @@ int OS_ReadXMLRules(char *rulefile, XML_NODE node = NULL; - /** XML variables **/ + /** XML variables **/ /* These are the available options for the rule configuration */ - + char *xml_group = "group"; char *xml_rule = "rule"; @@ -61,7 +62,7 @@ int OS_ReadXMLRules(char *rulefile, char *xml_comment = "description"; char *xml_ignore = "ignore"; char *xml_check_if_ignored = "check_if_ignored"; - + char *xml_srcip = "srcip"; char *xml_srcport = "srcport"; char *xml_dstip = "dstip"; @@ -75,16 +76,16 @@ int OS_ReadXMLRules(char *rulefile, char *xml_status = "status"; char *xml_action = "action"; char *xml_compiled = "compiled_rule"; - + char *xml_if_sid = "if_sid"; char *xml_if_group = "if_group"; char *xml_if_level = "if_level"; char *xml_fts = "if_fts"; - + char *xml_if_matched_regex = "if_matched_regex"; char *xml_if_matched_group = "if_matched_group"; char *xml_if_matched_sid = "if_matched_sid"; - + char *xml_same_source_ip = "same_source_ip"; char *xml_same_src_port = "same_src_port"; char *xml_same_dst_port = "same_dst_port"; @@ -94,16 +95,16 @@ int OS_ReadXMLRules(char *rulefile, char *xml_dodiff = "check_diff"; char *xml_different_url = "different_url"; - + char *xml_notsame_source_ip = "not_same_source_ip"; char *xml_notsame_user = "not_same_user"; char *xml_notsame_agent = "not_same_agent"; char *xml_notsame_id = "not_same_id"; char *xml_options = "options"; - + char *rulepath; - + int i; @@ -125,9 +126,9 @@ int OS_ReadXMLRules(char *rulefile, debug1("%s is the rulefile", rulefile); debug1("Not modifing the rule path"); } - - - /* Reading the XML */ + + + /* Reading the XML */ if(OS_ReadXML(rulepath,&xml) < 0) { merror(XML_ERROR, __local_name, rulepath, xml.err, xml.err_line); @@ -138,7 +139,7 @@ int OS_ReadXMLRules(char *rulefile, /* Debug wrapper */ debug1("%s: DEBUG: read xml for rule '%s'.", __local_name, rulepath); - + /* Applying any variable found */ if(OS_ApplyVariables(&xml) != 0) @@ -150,7 +151,7 @@ int OS_ReadXMLRules(char *rulefile, /* Debug wrapper */ debug1("%s: DEBUG: XML Variables applied.", __local_name); - + /* Getting the root elements */ node = OS_GetElementsbyNode(&xml, NULL); @@ -158,13 +159,13 @@ int OS_ReadXMLRules(char *rulefile, { merror(CONFIG_ERROR, __local_name, rulepath); OS_ClearXML(&xml); - return(-1); + return(-1); } /* Zeroing the rule memory -- not used anymore */ free(rulepath); - + /* Checking if there is any invalid global option */ i = 0; @@ -200,7 +201,7 @@ int OS_ReadXMLRules(char *rulefile, } - /* Getting the rules now */ + /* Getting the rules now */ i = 0; while(node[i]) { @@ -208,7 +209,7 @@ int OS_ReadXMLRules(char *rulefile, XML_NODE rule = NULL; - /* Getting all rules for a global group */ + /* Getting all rules for a global group */ rule = OS_GetElementsbyNode(&xml,node[i]); if(rule == NULL) { @@ -221,15 +222,15 @@ int OS_ReadXMLRules(char *rulefile, { /* Rules options */ int k = 0; - char *regex = NULL, *match = NULL, *url = NULL, + char *regex = NULL, *match = NULL, *url = NULL, *if_matched_regex = NULL, *if_matched_group = NULL, *user = NULL, *id = NULL, *srcport = NULL, *dstport = NULL, *status = NULL, *hostname = NULL, *extra_data = NULL, *program_name = NULL; - + RuleInfo *config_ruleinfo = NULL; XML_NODE rule_opt = NULL; - + /* Checking if the rule element is correct */ if((!rule[j]->element)|| @@ -244,12 +245,12 @@ int OS_ReadXMLRules(char *rulefile, /* Checking for the attributes of the rule */ if((!rule[j]->attributes) || (!rule[j]->values)) { - merror(RL_INV_RULE, __local_name, rulefile); + merror(RL_INV_RULE, __local_name, rulefile); OS_ClearXML(&xml); return(-1); } - + /* Attribute block */ config_ruleinfo = _OS_AllocateRule(); @@ -275,19 +276,19 @@ int OS_ReadXMLRules(char *rulefile, * be fine */ os_strdup(node[i]->values[0], config_ruleinfo->group); - - /* Getting rules options */ + + /* Getting rules options */ rule_opt = OS_GetElementsbyNode(&xml, rule[j]); if(rule_opt == NULL) { merror(RL_NO_OPT, __local_name, config_ruleinfo->sigid); OS_ClearXML(&xml); - return(-1); + return(-1); } - - /* Reading the whole rule block */ + + /* Reading the whole rule block */ while(rule_opt[k]) { if((!rule_opt[k]->element)||(!rule_opt[k]->content)) @@ -317,7 +318,7 @@ int OS_ReadXMLRules(char *rulefile, } else if(strcasecmp(rule_opt[k]->element,xml_day_time) == 0) { - config_ruleinfo->day_time = + config_ruleinfo->day_time = OS_IsValidTime(rule_opt[k]->content); if(!config_ruleinfo->day_time) { @@ -332,7 +333,7 @@ int OS_ReadXMLRules(char *rulefile, } else if(strcasecmp(rule_opt[k]->element,xml_week_day) == 0) { - config_ruleinfo->week_day = + config_ruleinfo->week_day = OS_IsValidDay(rule_opt[k]->content); if(!config_ruleinfo->week_day) @@ -375,25 +376,25 @@ int OS_ReadXMLRules(char *rulefile, int ip_s = 0; /* Getting size of source ip list */ - while(config_ruleinfo->srcip && + while(config_ruleinfo->srcip && config_ruleinfo->srcip[ip_s]) { ip_s++; } - config_ruleinfo->srcip = + config_ruleinfo->srcip = realloc(config_ruleinfo->srcip, (ip_s + 2) * sizeof(os_ip *)); /* Allocating memory for the individual entries */ - os_calloc(1, sizeof(os_ip), + os_calloc(1, sizeof(os_ip), config_ruleinfo->srcip[ip_s]); config_ruleinfo->srcip[ip_s +1] = NULL; /* Checking if the ip is valid */ - if(!OS_IsValidIP(rule_opt[k]->content, + if(!OS_IsValidIP(rule_opt[k]->content, config_ruleinfo->srcip[ip_s])) { merror(INVALID_IP, __local_name, rule_opt[k]->content); @@ -450,7 +451,7 @@ int OS_ReadXMLRules(char *rulefile, else if(strcasecmp(rule_opt[k]->element,xml_srcport) == 0) { srcport = os_LoadString(srcport, rule_opt[k]->content); - + if(!(config_ruleinfo->alert_opts & DO_PACKETINFO)) config_ruleinfo->alert_opts |= DO_PACKETINFO; } @@ -490,7 +491,7 @@ int OS_ReadXMLRules(char *rulefile, } else if(strcasecmp(rule_opt[k]->element,xml_action) == 0) { - config_ruleinfo->action = + config_ruleinfo->action = os_LoadString(config_ruleinfo->action, rule_opt[k]->content); } @@ -551,9 +552,9 @@ int OS_ReadXMLRules(char *rulefile, { if(!OS_StrIsNum(rule_opt[k]->content)) { - merror(INVALID_CONFIG, __local_name, + merror(INVALID_CONFIG, __local_name, xml_if_level, - rule_opt[k]->content); + rule_opt[k]->content); return(-1); } @@ -594,7 +595,7 @@ int OS_ReadXMLRules(char *rulefile, rule_opt[k]->content); return(-1); } - config_ruleinfo->if_matched_sid = + config_ruleinfo->if_matched_sid = atoi(rule_opt[k]->content); } @@ -683,7 +684,7 @@ int OS_ReadXMLRules(char *rulefile, else if(strcasecmp(rule_opt[k]->element, xml_options) == 0) { - if(strcmp("alert_by_email", + if(strcmp("alert_by_email", rule_opt[k]->content) == 0) { if(!(config_ruleinfo->alert_opts & DO_MAILALERT)) @@ -699,7 +700,7 @@ int OS_ReadXMLRules(char *rulefile, config_ruleinfo->alert_opts&=0xfff-DO_MAILALERT; } } - else if(strcmp("log_alert", + else if(strcmp("log_alert", rule_opt[k]->content) == 0) { if(!(config_ruleinfo->alert_opts & DO_LOGALERT)) @@ -722,7 +723,7 @@ int OS_ReadXMLRules(char *rulefile, } } else - { + { merror(XML_VALUEERR, __local_name, xml_options, rule_opt[k]->content); @@ -731,7 +732,7 @@ int OS_ReadXMLRules(char *rulefile, rule_opt[k]->content); OS_ClearXML(&xml); return(-1); - } + } } else if(strcasecmp(rule_opt[k]->element, xml_ignore) == 0) @@ -815,13 +816,13 @@ int OS_ReadXMLRules(char *rulefile, return(-1); } } - /* XXX As new features are added into ../analysisd/rules.c - * This code needs to be updated to match, but is out of date - * it's become a nightmare to correct with out just make the - * problem for someone later. + /* XXX As new features are added into ../analysisd/rules.c + * This code needs to be updated to match, but is out of date + * it's become a nightmare to correct with out just make the + * problem for someone later. * - * This hack will allow any crap xml to pass without an - * error. The correct fix is to refactor the code so that + * This hack will allow any crap xml to pass without an + * error. The correct fix is to refactor the code so that * ../analysisd/rules* and this code are not duplicates * else @@ -857,7 +858,7 @@ int OS_ReadXMLRules(char *rulefile, os_strdup(if_matched_group, config_ruleinfo->if_group); } } - + /* If_matched_sid, we need to get the if_sid */ if(config_ruleinfo->if_matched_sid && @@ -1074,14 +1075,14 @@ int OS_ReadXMLRules(char *rulefile, /* Calling the function provided. */ ruleact_function(config_ruleinfo, data); - + j++; /* next rule */ } /* while(rule[j]) */ OS_ClearNode(rule); i++; - + } /* while (node[i]) */ /* Cleaning global node */ @@ -1101,15 +1102,15 @@ int OS_ReadXMLRules(char *rulefile, RuleInfo *_OS_AllocateRule() { RuleInfo *ruleinfo_pt = NULL; - - + + /* Allocation memory for structure */ ruleinfo_pt = (RuleInfo *)calloc(1,sizeof(RuleInfo)); if(ruleinfo_pt == NULL) { ErrorExit(MEM_ERROR,__local_name); } - + /* Default values */ ruleinfo_pt->level = -1; @@ -1117,10 +1118,10 @@ RuleInfo *_OS_AllocateRule() /* Default category is syslog */ ruleinfo_pt->category = SYSLOG; - ruleinfo_pt->ar = NULL; - + ruleinfo_pt->ar = NULL; + ruleinfo_pt->context = 0; - + /* Default sigid of -1 */ ruleinfo_pt->sigid = -1; ruleinfo_pt->firedtimes = 0; @@ -1129,11 +1130,11 @@ RuleInfo *_OS_AllocateRule() ruleinfo_pt->ignore_time = 0; ruleinfo_pt->timeframe = 0; ruleinfo_pt->time_ignored = 0; - - ruleinfo_pt->context_opts = 0; - ruleinfo_pt->alert_opts = 0; - ruleinfo_pt->ignore = 0; - ruleinfo_pt->ckignore = 0; + + ruleinfo_pt->context_opts = 0; + ruleinfo_pt->alert_opts = 0; + ruleinfo_pt->ignore = 0; + ruleinfo_pt->ckignore = 0; ruleinfo_pt->day_time = NULL; ruleinfo_pt->week_day = NULL; @@ -1146,16 +1147,16 @@ RuleInfo *_OS_AllocateRule() ruleinfo_pt->comment = NULL; ruleinfo_pt->info = NULL; ruleinfo_pt->cve = NULL; - + ruleinfo_pt->if_sid = NULL; ruleinfo_pt->if_group = NULL; ruleinfo_pt->if_level = NULL; - + ruleinfo_pt->if_matched_regex = NULL; ruleinfo_pt->if_matched_group = NULL; ruleinfo_pt->if_matched_sid = 0; - - ruleinfo_pt->user = NULL; + + ruleinfo_pt->user = NULL; ruleinfo_pt->srcip = NULL; ruleinfo_pt->srcport = NULL; ruleinfo_pt->dstip = NULL; @@ -1166,7 +1167,7 @@ RuleInfo *_OS_AllocateRule() ruleinfo_pt->hostname = NULL; ruleinfo_pt->program_name = NULL; ruleinfo_pt->action = NULL; - + /* Zeroing last matched events */ ruleinfo_pt->__frequency = 0; ruleinfo_pt->last_events = NULL; @@ -1174,10 +1175,10 @@ RuleInfo *_OS_AllocateRule() /* zeroing the list of previous matches */ ruleinfo_pt->sid_prev_matched = NULL; ruleinfo_pt->group_prev_matched = NULL; - + ruleinfo_pt->sid_search = NULL; ruleinfo_pt->group_search = NULL; - + ruleinfo_pt->event_search = NULL; return(ruleinfo_pt); @@ -1192,7 +1193,7 @@ int _OS_GetRulesAttributes(char **attributes, char **values, RuleInfo *ruleinfo_pt) { int k = 0; - + char *xml_id = "id"; char *xml_level = "level"; char *xml_maxsize = "maxsize"; @@ -1202,8 +1203,8 @@ int _OS_GetRulesAttributes(char **attributes, char **values, char *xml_noalert = "noalert"; char *xml_ignore_time = "ignore"; char *xml_overwrite = "overwrite"; - - + + /* Getting attributes */ while(attributes[k]) { @@ -1217,7 +1218,7 @@ int _OS_GetRulesAttributes(char **attributes, char **values, { if(OS_StrIsNum(values[k]) && (strlen(values[k]) <= 6 )) { - ruleinfo_pt->sigid = atoi(values[k]); + ruleinfo_pt->sigid = atoi(values[k]); } else { @@ -1246,7 +1247,7 @@ int _OS_GetRulesAttributes(char **attributes, char **values, ruleinfo_pt->maxsize = atoi(values[k]); /* adding EXTRAINFO options */ - if(ruleinfo_pt->maxsize > 0 && + if(ruleinfo_pt->maxsize > 0 && !(ruleinfo_pt->alert_opts & DO_EXTRAINFO)) { ruleinfo_pt->alert_opts |= DO_EXTRAINFO; @@ -1287,7 +1288,7 @@ int _OS_GetRulesAttributes(char **attributes, char **values, /* Rule accuracy */ else if(strcasecmp(attributes[k],xml_accuracy) == 0) { - merror("%s: XXX: Use of 'accuracy' isn't supported. Ignoring.", + merror("%s: XXX: Use of 'accuracy' isn't supported. Ignoring.", __local_name); } /* Rule ignore_time */ @@ -1300,7 +1301,7 @@ int _OS_GetRulesAttributes(char **attributes, char **values, else { merror(XML_VALUEERR,__local_name, attributes[k], values[k]); - return(-1); + return(-1); } } /* Rule noalert */ @@ -1338,9 +1339,9 @@ int _OS_GetRulesAttributes(char **attributes, char **values, /* print rule */ void OS_PrintRuleinfo(RuleInfo *rule) { - debug1("%s: __local_name: Print Rule:%d, level %d, ignore: %d, frequency:%d", + debug1("%s: __local_name: Print Rule:%d, level %d, ignore: %d, frequency:%d", __local_name, - rule->sigid, + rule->sigid, rule->level, rule->ignore_time, rule->frequency); diff --git a/src/shared/sig_op.c b/src/shared/sig_op.c index bde3a72..f31a654 100755 --- a/src/shared/sig_op.c +++ b/src/shared/sig_op.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/shared/sig_op.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -30,9 +31,9 @@ char *pidfile = NULL; void HandleSIG() { merror(SIGNAL_RECV, pidfile); - + DeletePID(pidfile); - + exit(1); } @@ -49,7 +50,7 @@ void StartSIG(char *process_name) go to HandleSIG() */ pidfile = process_name; - signal(SIGHUP, SIG_IGN); + signal(SIGHUP, SIG_IGN); signal(SIGINT, HandleSIG); signal(SIGQUIT, HandleSIG); signal(SIGTERM, HandleSIG); diff --git a/src/shared/store_op.c b/src/shared/store_op.c index 6794f8f..c3feacc 100644 --- a/src/shared/store_op.c +++ b/src/shared/store_op.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/shared/store_op.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -11,13 +12,13 @@ /* Common API for dealing with ordered lists. * Provides a fast search on average (n/2). - */ + */ #include "shared.h" -/* Create the list storage +/* Create the list storage * Return NULL on error */ OSStore *OSStore_Create() @@ -27,20 +28,20 @@ OSStore *OSStore_Create() my_list = calloc(1, sizeof(OSStore)); if(!my_list) return(NULL); - + my_list->first_node = NULL; my_list->last_node = NULL; my_list->cur_node = NULL; my_list->currently_size = 0; my_list->max_size = 0; my_list->free_data_function = NULL; - + return(my_list); } -/* Deletes the list storage +/* Deletes the list storage * Return NULL on error */ OSStore *OSStore_Free(OSStore *list) @@ -72,7 +73,7 @@ OSStore *OSStore_Free(OSStore *list) free(list); list = NULL; - + return(list); } @@ -88,7 +89,7 @@ int OSStore_SetMaxSize(OSStore *list, int max_size) { return(0); } - + /* Minimum size is 1 */ if(max_size <= 1) { @@ -111,7 +112,7 @@ int OSStore_SetFreeDataPointer(OSStore *list, void *free_data_function) { return(0); } - + list->free_data_function = free_data_function; return(1); } @@ -143,34 +144,34 @@ int OSStore_Sort(OSStore *list, void*(sort_data_function)(void *d1, void *d2)) /* In here, this node should stay where it is. */ else if(movenode == list->cur_node->prev) { - break; + break; } /* In here we need to replace the nodes. */ else { newnode = list->cur_node; - + if(list->cur_node->prev) list->cur_node->prev->next = list->cur_node->next; - + if(list->cur_node->next) list->cur_node->next->prev = list->cur_node->prev; else - list->last_node = list->cur_node->prev; - - list->cur_node = list->cur_node->prev; + list->last_node = list->cur_node->prev; + + list->cur_node = list->cur_node->prev; + - newnode->next = movenode->next; newnode->prev = movenode; if(movenode->next) movenode->next->prev = newnode; - + movenode->next = newnode; - + break; } } @@ -183,21 +184,21 @@ int OSStore_Sort(OSStore *list, void*(sort_data_function)(void *d1, void *d2)) if(list->cur_node->prev) list->cur_node->prev->next = list->cur_node->next; - + if(list->cur_node->next) list->cur_node->next->prev = list->cur_node->prev; - else - list->last_node = list->cur_node->prev; - + else + list->last_node = list->cur_node->prev; + list->cur_node = list->cur_node->prev; - + newnode->prev = NULL; newnode->next = list->first_node; list->first_node->prev = newnode; - - list->first_node = newnode; + + list->first_node = newnode; } - + list->cur_node = list->cur_node->next; } @@ -253,7 +254,7 @@ void *OSStore_Get(OSStore *list, char *key) { int chk_rc; list->cur_node = list->first_node; - + while(list->cur_node) { if((chk_rc = strcmp(list->cur_node->key, key)) >= 0) @@ -262,7 +263,7 @@ void *OSStore_Get(OSStore *list, char *key) if(chk_rc == 0) return(list->cur_node->data); - /* Not found */ + /* Not found */ return(NULL); } @@ -280,7 +281,7 @@ int OSStore_Check(OSStore *list, char *key) { int chk_rc; list->cur_node = list->first_node; - + while(list->cur_node) { if((chk_rc = strcmp(list->cur_node->key, key)) >= 0) @@ -289,7 +290,7 @@ int OSStore_Check(OSStore *list, char *key) if(chk_rc == 0) return(1); - /* Not found */ + /* Not found */ return(0); } @@ -310,7 +311,7 @@ int OSStore_NCheck(OSStore *list, char *key) while(list->cur_node) { - if((chk_rc = strncmp(list->cur_node->key, key, + if((chk_rc = strncmp(list->cur_node->key, key, list->cur_node->key_size)) >= 0) { /* Found */ @@ -367,7 +368,7 @@ void OSStore_Delete(OSStore *list, char *key) int OSStore_Put(OSStore *list, char *key, void *data) { int chk_rc; - OSStoreNode *newnode; + OSStoreNode *newnode; /* Allocating memory for new node */ @@ -391,9 +392,9 @@ int OSStore_Put(OSStore *list, char *key, void *data) list->first_node = newnode; list->last_node = newnode; } - - - /* Store the data in order */ + + + /* Store the data in order */ else { list->cur_node = list->first_node; @@ -406,18 +407,18 @@ int OSStore_Put(OSStore *list, char *key, void *data) { return(1); } - + /* If there is no prev node, it is because - * this is the first node. + * this is the first node. */ if(list->cur_node->prev) list->cur_node->prev->next = newnode; else list->first_node = newnode; - - + + newnode->prev = list->cur_node->prev; - + list->cur_node->prev = newnode; newnode->next = list->cur_node; break; @@ -434,11 +435,11 @@ int OSStore_Put(OSStore *list, char *key, void *data) list->last_node = newnode; } } - + /* Increment list size */ list->currently_size++; - + return(1); } diff --git a/src/shared/string_op.c b/src/shared/string_op.c new file mode 100755 index 0000000..f458793 --- /dev/null +++ b/src/shared/string_op.c @@ -0,0 +1,91 @@ +/* @(#) $Id: ./src/shared/string_op.c, 2011/11/01 dcid Exp $ + */ + +/* Copyright (C) 2009 Trend Micro Inc. + * All rights reserved. + * + * This program is a free software; you can redistribute it + * and/or modify it under the terms of the GNU General Public + * License (version 2) as published by the FSF - Free Software + * Foundation + * + * License details at the LICENSE file included with OSSEC or + * online at: http://www.ossec.net/en/licensing.html + */ + + +#include "shared.h" +#include "string.h" + +/** os_trimcrlf + * Trims the cr and/or LF from the last positions of a string + */ +void os_trimcrlf(char *str) +{ + int len; + + len=strlen(str); + len--; + + while (str[len]=='\n' || str[len]=='\r') + { + str[len]='\0'; + len--; + } +} + +/* Remove offending char (e.g., double quotes) from source */ +char *os_strip_char(char *source, char remove) { + char *clean; + char *iterator = source; + int length = 0; + int i; + + // Figure out how much memory to allocate + for( ; *iterator; iterator++ ) { + if ( *iterator != remove ) { + length++; + } + } + + // Allocate the memory + if( (clean = malloc( length + 1 )) == NULL ) { + // Return NULL + return NULL; + } + memset(clean, '\0', length + 1); + + // Remove the characters + iterator=source; + for( i=0; *iterator; iterator++ ) { + if ( *iterator != remove ) { + clean[i] = *iterator; + i++; + } + } + + return clean; +} + +/* Do a substring */ +int os_substr(char *dest, const char *src, int position, int length) { + dest[0]='\0'; + + if( length <= 0 ) { + // Unsupported negative length string + return -3; + } + if( src == NULL ) { + return -2; + } + if( position >= strlen(src) ) { + return -1; + } + + strncat(dest, (src + position), length); + // Return Success + return 0; +} + + +/* EOF */ diff --git a/src/shared/tests/hash_test.c b/src/shared/tests/hash_test.c index d1464cf..367d028 100755 --- a/src/shared/tests/hash_test.c +++ b/src/shared/tests/hash_test.c @@ -9,7 +9,7 @@ int main(int argc, char **argv) char *tmp; char buf[1024]; OSHash *mhash; - + mhash = OSHash_Create(); while(1) @@ -22,13 +22,13 @@ int main(int argc, char **argv) if(strncmp(buf, "get ", 4) == 0) { printf("Getting key: '%s'\n", buf + 4); - printf("Found: '%s'\n", (char *)OSHash_Get(mhash, buf + 4)); + printf("Found: '%s'\n", (char *)OSHash_Get(mhash, buf + 4)); } else { printf("Adding key: '%s'\n", buf); i = OSHash_Add(mhash, strdup(buf), strdup(buf)); - + printf("rc = %d\n", i); } } diff --git a/src/shared/tests/ip_test.c b/src/shared/tests/ip_test.c index 149f1b9..685905a 100755 --- a/src/shared/tests/ip_test.c +++ b/src/shared/tests/ip_test.c @@ -14,7 +14,7 @@ int main(int argc, char **argv) { printf("Invalid ip\n"); } - + if(OS_IPFound(argv[2], &myip)) { printf("IP MATCHED!\n"); diff --git a/src/shared/validate_op.c b/src/shared/validate_op.c index 226bd33..25132ee 100755 --- a/src/shared/validate_op.c +++ b/src/shared/validate_op.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/shared/validate_op.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -16,8 +17,8 @@ #include "shared.h" -char *ip_address_regex = - "^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}/?" +char *ip_address_regex = + "^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}/?" "([0-9]{0,2}|[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3})$"; /* Global vars */ @@ -37,7 +38,7 @@ static char *_read_file(char *high_name, char *low_name, char *defines_file) char *buf_pt; char *tmp_buffer; char *ret; - + #ifndef WIN32 if(isChroot()) { @@ -51,7 +52,7 @@ static char *_read_file(char *high_name, char *low_name, char *defines_file) snprintf(def_file,OS_FLSIZE,"%s", defines_file); #endif - + fp = fopen(def_file, "r"); if(!fp) { @@ -96,7 +97,7 @@ static char *_read_file(char *high_name, char *low_name, char *defines_file) } tmp_buffer = buf_pt; - + /* Getting the equal */ buf_pt = strchr(buf_pt, '='); if(!buf_pt) @@ -124,12 +125,12 @@ static char *_read_file(char *high_name, char *low_name, char *defines_file) { *tmp_buffer = '\0'; } - + os_strdup(buf_pt, ret); fclose(fp); return(ret); } - + fclose(fp); return(NULL); } @@ -213,7 +214,7 @@ int getDefine_Int(char *high_name, char *low_name, int min, int max) char *value; char *pt; - + /* We first try to read from the local define file. */ value = _read_file(high_name, low_name, OSSEC_LDEFINES); if(!value) @@ -260,13 +261,13 @@ int OS_IPFound(char *ip_address, os_ip *that_ip) { return(!_true); } - + /* If negate is set */ if(that_ip->ip[0] == '!') { _true = 0; } - + /* Checking if ip is in thatip & netmask */ if((net.s_addr & that_ip->netmask) == that_ip->ip_address) { @@ -277,7 +278,7 @@ int OS_IPFound(char *ip_address, os_ip *that_ip) return(!_true); } - + /** int OS_IPFoundList(char *ip_address, os_ip **list_of_ips) * Checks if ip_address is present on the "list_of_ips". * Returns 1 on success or 0 on failure. @@ -293,16 +294,16 @@ int OS_IPFoundList(char *ip_address, os_ip **list_of_ips) { return(!_true); } - + while(*list_of_ips) { os_ip *l_ip = *list_of_ips; - + if(l_ip->ip[0] == '!') { _true = 0; } - + if((net.s_addr & l_ip->netmask) == l_ip->ip_address) { return(_true); @@ -311,9 +312,9 @@ int OS_IPFoundList(char *ip_address, os_ip **list_of_ips) } return(!_true); -} +} + - /** int OS_IsValidIP(char *ip) * Validates if an ip address is in the right * format. @@ -336,13 +337,13 @@ int OS_IsValidIP(char *ip_address, os_ip *final_ip) { os_strdup(ip_address, final_ip->ip); } - + if(*ip_address == '!') { ip_address++; } - - #ifndef WIN32 + + #ifndef WIN32 /* checking against the basic regex */ if(!OS_PRegex(ip_address, ip_address_regex)) { @@ -360,8 +361,8 @@ int OS_IsValidIP(char *ip_address, os_ip *final_ip) tmp_ip = ip_address; while(*tmp_ip != '\0') { - if((*tmp_ip < '0' || - *tmp_ip > '9') && + if((*tmp_ip < '0' || + *tmp_ip > '9') && *tmp_ip != '.' && *tmp_ip != '/') { @@ -379,13 +380,13 @@ int OS_IsValidIP(char *ip_address, os_ip *final_ip) - /* Getting the cidr/netmask if available */ + /* Getting the cidr/netmask if available */ tmp_str = strchr(ip_address,'/'); if(tmp_str) { int cidr; struct in_addr net; - + *tmp_str = '\0'; tmp_str++; @@ -424,7 +425,7 @@ int OS_IsValidIP(char *ip_address, os_ip *final_ip) } } } - + if((net.s_addr = inet_addr(ip_address)) <= 0) { if(strcmp("0.0.0.0", ip_address) == 0) @@ -454,7 +455,7 @@ int OS_IsValidIP(char *ip_address, os_ip *final_ip) { struct in_addr net; nmask = 32; - + if(strcmp("any", ip_address) == 0) { net.s_addr = 0; @@ -464,14 +465,14 @@ int OS_IsValidIP(char *ip_address, os_ip *final_ip) { return(0); } - + if(final_ip) { final_ip->ip_address = net.s_addr; if(!_mask_inited) _init_masks(); - + final_ip->netmask = htonl(_netmasks[nmask]); } @@ -505,11 +506,11 @@ int OS_IsonTime(char *time_str, char *ossec_time) /* Comparing against min/max value */ if((strncmp(time_str, ossec_time, 5) >= 0)&& - (strncmp(time_str, ossec_time+5,5) <= 0)) + (strncmp(time_str, ossec_time+5,5) <= 0)) { return(_true); } - + return(!_true); } @@ -533,13 +534,13 @@ char *__gethour(char *str, char *ossec_hour) int _size = 0; int chour = 0; int cmin = 0; - + /* Invalid time format */ if(!isdigit((int)*str)) { merror(INVALID_TIME, __local_name, str); } - + /* Hour */ chour = atoi(str); @@ -552,7 +553,7 @@ char *__gethour(char *str, char *ossec_hour) return(NULL); } - + /* Going after the hour */ while(isdigit((int)*str)) { @@ -566,8 +567,8 @@ char *__gethour(char *str, char *ossec_hour) merror(INVALID_TIME, __local_name, str); return(NULL); } - - + + /* Getting minute */ if(*str == ':') { @@ -585,7 +586,7 @@ char *__gethour(char *str, char *ossec_hour) /* Removing spaces */ RM_WHITE(str); - + if((*str == 'a') || (*str == 'A')) { str++; @@ -602,19 +603,19 @@ char *__gethour(char *str, char *ossec_hour) if((*str == 'm') || (*str == 'M')) { chour += 12; - + /* New hour must be valid */ if(chour < 0 || chour >= 24) { merror(INVALID_TIME, __local_name, str); return(NULL); } - + snprintf(ossec_hour, 6, "%02d:%02d", chour, cmin); str++; return(str); } - + } else { @@ -634,17 +635,17 @@ char *OS_IsValidTime(char *time_str) char first_hour[7]; char second_hour[7]; int ng = 0; - + /* Must be not null */ if(!time_str) return(NULL); - - + + /* Clearing memory */ memset(first_hour, '\0', 7); memset(second_hour, '\0', 7); - - + + /* Removing white spaces */ RM_WHITE(time_str); @@ -659,7 +660,7 @@ char *OS_IsValidTime(char *time_str) RM_WHITE(time_str); } - + /* Getting first hour */ time_str = __gethour(time_str, first_hour); if(!time_str) @@ -667,7 +668,7 @@ char *OS_IsValidTime(char *time_str) /* Removing white spaces */ RM_WHITE(time_str); - + if(*time_str != '-') { return(NULL); @@ -682,7 +683,7 @@ char *OS_IsValidTime(char *time_str) time_str = __gethour(time_str, second_hour); if(!time_str) return(NULL); - + RM_WHITE(time_str); if(*time_str != '\0') { @@ -690,14 +691,14 @@ char *OS_IsValidTime(char *time_str) } os_calloc(13, sizeof(char), ret); - + /* Fixing dump hours */ if(strcmp(first_hour,second_hour) > 0) { snprintf(ret, 12, "!%s%s", second_hour, first_hour); return(ret); } - + /* For the normal times */ snprintf(ret, 12, "%c%s%s", ng == 0?'.':'!', first_hour, second_hour); return(ret); @@ -714,8 +715,8 @@ int OS_IsAfterTime(char *time_str, char *ossec_time) /* Unique times can't have a !. */ if(*ossec_time == '!') return(0); - - + + ossec_time++; /* Comparing against min/max value */ @@ -759,7 +760,7 @@ int OS_IsonDay(int week_day, char *ossec_day) /* Negative */ if(ossec_day[7] == '!') _true = 0; - + if(week_day < 0 || week_day > 7) { return(0); @@ -768,8 +769,8 @@ int OS_IsonDay(int week_day, char *ossec_day) /* It is on the right day */ if(ossec_day[week_day] == 1) return(_true); - - return(!_true); + + return(!_true); } @@ -792,7 +793,7 @@ char *OS_IsValidDay(char *day_str) int i = 0, ng = 0; char *ret; char day_ret[9] = {0,0,0,0,0,0,0,0,0}; - char *(days[]) = + char *(days[]) = { "sunday", "sun", "monday", "mon", "tuesday", "tue", "wednesday", "wed", "thursday", "thu", "friday", @@ -803,10 +804,10 @@ char *OS_IsValidDay(char *day_str) /* Must be a valid string */ if(!day_str) return(NULL); - - + + RM_WHITE(day_str); - + /* checking for negatives */ if(*day_str == '!') { @@ -850,7 +851,7 @@ char *OS_IsValidDay(char *day_str) merror(INVALID_DAY, __local_name, day_str); return(NULL); } - + day_str += strlen(days[i]); if(IS_SEP(day_str)) @@ -891,7 +892,7 @@ char *OS_IsValidDay(char *day_str) merror(INVALID_DAY, __local_name, day_str); return(NULL); } - + return(ret); } diff --git a/src/shared/wait_op.c b/src/shared/wait_op.c index 3e98d05..53bc664 100755 --- a/src/shared/wait_op.c +++ b/src/shared/wait_op.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/shared/wait_op.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -23,7 +24,7 @@ void os_setwait() /* For same threads. */ __wait_lock = 1; - + if(isChroot()) { fp = fopen(WAIT_FILE, "w"); @@ -47,7 +48,7 @@ void os_setwait() void os_delwait() { __wait_lock = 0; - + if(isChroot()) { unlink(WAIT_FILE); @@ -65,7 +66,7 @@ void os_delwait() * Works as a simple inter process lock (only the main * process is allowed to lock). */ -#ifdef WIN32 +#ifdef WIN32 void os_wait() { if(!__wait_lock) @@ -94,7 +95,7 @@ void os_wait() void os_wait() { struct stat file_status; - + /* If the wait file is not present, keep going. */ @@ -108,7 +109,7 @@ void os_wait() if(stat(WAIT_FILE_PATH, &file_status) == -1) return; } - + /* Wait until the lock is gone. */ verbose(WAITING_MSG, __local_name); diff --git a/src/syscheckd/config.c b/src/syscheckd/config.c index 500c612..0ee30e4 100755 --- a/src/syscheckd/config.c +++ b/src/syscheckd/config.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/syscheckd/config.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -14,6 +15,8 @@ #include "syscheck.h" #include "config/config.h" +char *SYSCHECK_EMPTY[] = { NULL }; + int Read_Syscheck_Config(char * cfgfile) { int modules = 0; @@ -35,7 +38,10 @@ int Read_Syscheck_Config(char * cfgfile) syscheck.registry = NULL; syscheck.reg_fp = NULL; #endif + syscheck.prefilter_cmd = NULL; + + debug2("%s: Reading Configuration [%s]", "syscheckd", cfgfile); /* Reading config */ if(ReadConfig(modules, cfgfile, &syscheck, NULL) < 0) @@ -43,18 +49,36 @@ int Read_Syscheck_Config(char * cfgfile) #ifdef CLIENT + debug2("%s: Reading Client Configuration [%s]", "syscheckd", cfgfile); + /* Reading shared config */ modules|= CAGENT_CONFIG; ReadConfig(modules, AGENTCONFIG, &syscheck, NULL); #endif - + + #ifndef WIN32 /* We must have at least one directory to check */ if(!syscheck.dir || syscheck.dir[0] == NULL) { return(1); } - + + #else + /* We must have at least one directory or registry key to check. Since + it's possible on Windows to have syscheck enabled but only monitoring + either the filesystem or the registry, both lists must be valid, + even if empty. + */ + if(!syscheck.dir) syscheck.dir = SYSCHECK_EMPTY; + if(!syscheck.registry) syscheck.registry = SYSCHECK_EMPTY; + + if((syscheck.dir[0] == NULL) && (syscheck.registry[0] == NULL)) + { + return(1); + } + #endif + return(0); } diff --git a/src/syscheckd/create_db.c b/src/syscheckd/create_db.c index ff2a72b..91875cf 100755 --- a/src/syscheckd/create_db.c +++ b/src/syscheckd/create_db.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/syscheckd/create_db.c, 2011/11/02 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -39,7 +40,7 @@ int check_file(char *file_name) /* New file */ sleep(1); - + debug2("%s: DEBUG: new file '%s'.", ARGV0, file_name); return(0); } @@ -54,7 +55,7 @@ int read_file(char *file_name, int opts, OSMatch *restriction) char *buf; char sha1s = '+'; struct stat statbuf; - + /* Checking if file is to be ignored */ if(syscheck.ignore) @@ -62,10 +63,10 @@ int read_file(char *file_name, int opts, OSMatch *restriction) int i = 0; while(syscheck.ignore[i] != NULL) { - if(strncasecmp(syscheck.ignore[i], file_name, + if(strncasecmp(syscheck.ignore[i], file_name, strlen(syscheck.ignore[i])) == 0) { - return(0); + return(0); } i++; @@ -78,7 +79,7 @@ int read_file(char *file_name, int opts, OSMatch *restriction) int i = 0; while(syscheck.ignore_regex[i] != NULL) { - if(OSMatch_Execute(file_name, strlen(file_name), + if(OSMatch_Execute(file_name, strlen(file_name), syscheck.ignore_regex[i])) { return(0); @@ -98,7 +99,7 @@ int read_file(char *file_name, int opts, OSMatch *restriction) merror("%s: Error accessing '%s'.",ARGV0, file_name); return(-1); } - + if(S_ISDIR(statbuf.st_mode)) { #ifdef DEBUG @@ -112,20 +113,20 @@ int read_file(char *file_name, int opts, OSMatch *restriction) /* restricting file types. */ if(restriction) { - if(!OSMatch_Execute(file_name, strlen(file_name), + if(!OSMatch_Execute(file_name, strlen(file_name), restriction)) { return(0); } } - - + + /* No S_ISLNK on windows */ #ifdef WIN32 - else if(S_ISREG(statbuf.st_mode)) + if(S_ISREG(statbuf.st_mode)) #else - else if(S_ISREG(statbuf.st_mode) || S_ISLNK(statbuf.st_mode)) - #endif + if(S_ISREG(statbuf.st_mode) || S_ISLNK(statbuf.st_mode)) + #endif { os_md5 mf_sum; os_sha1 sf_sum; @@ -152,7 +153,7 @@ int read_file(char *file_name, int opts, OSMatch *restriction) { if(S_ISREG(statbuf_lnk.st_mode)) { - if(OS_MD5_SHA1_File(file_name, mf_sum, sf_sum) < 0) + if(OS_MD5_SHA1_File(file_name, syscheck.prefilter_cmd, mf_sum, sf_sum) < 0) { strncpy(mf_sum, "xxx", 4); strncpy(sf_sum, "xxx", 4); @@ -160,12 +161,12 @@ int read_file(char *file_name, int opts, OSMatch *restriction) } } } - else if(OS_MD5_SHA1_File(file_name, mf_sum, sf_sum) < 0) + else if(OS_MD5_SHA1_File(file_name, syscheck.prefilter_cmd, mf_sum, sf_sum) < 0) #else - if(OS_MD5_SHA1_File(file_name, mf_sum, sf_sum) < 0) + if(OS_MD5_SHA1_File(file_name, syscheck.prefilter_cmd, mf_sum, sf_sum) < 0) #endif - + { strncpy(mf_sum, "xxx", 4); strncpy(sf_sum, "xxx", 4); @@ -182,15 +183,15 @@ int read_file(char *file_name, int opts, OSMatch *restriction) if(opts & CHECK_SEECHANGES) sha1s = 'n'; else - sha1s = '-'; + sha1s = '-'; } - - + + buf = OSHash_Get(syscheck.fp, file_name); if(!buf) { char alert_msg[912 +1]; - + alert_msg[912] = '\0'; if(opts & CHECK_SEECHANGES) @@ -203,7 +204,7 @@ int read_file(char *file_name, int opts, OSMatch *restriction) } } - + snprintf(alert_msg, 912, "%c%c%c%c%c%c%d:%d:%d:%d:%s:%s", opts & CHECK_SIZE?'+':'-', opts & CHECK_PERM?'+':'-', @@ -225,8 +226,8 @@ int read_file(char *file_name, int opts, OSMatch *restriction) /* Sending the new checksum to the analysis server */ - alert_msg[912 +1] = '\0'; - snprintf(alert_msg, 912, "%d:%d:%d:%d:%s:%s %s", + alert_msg[912] = '\0'; + snprintf(alert_msg, 912, "%d:%d:%d:%d:%s:%s %s", opts & CHECK_SIZE?(int)statbuf.st_size:0, opts & CHECK_PERM?(int)statbuf.st_mode:0, opts & CHECK_OWNER?(int)statbuf.st_uid:0, @@ -240,7 +241,7 @@ int read_file(char *file_name, int opts, OSMatch *restriction) { char alert_msg[OS_MAXSTR +1]; char c_sum[256 +2]; - + c_sum[0] = '\0'; c_sum[256] = '\0'; alert_msg[0] = '\0'; @@ -276,8 +277,8 @@ int read_file(char *file_name, int opts, OSMatch *restriction) send_syscheck_msg(alert_msg); } } - - + + /* Sleeping in here too */ if(__counter >= (syscheck.sleep_after)) { @@ -287,7 +288,7 @@ int read_file(char *file_name, int opts, OSMatch *restriction) __counter++; - #ifdef DEBUG + #ifdef DEBUG verbose("%s: file '%s %s'",ARGV0, file_name, mf_sum); #endif } @@ -308,11 +309,11 @@ int read_file(char *file_name, int opts, OSMatch *restriction) int read_dir(char *dir_name, int opts, OSMatch *restriction) { int dir_size; - - char f_name[PATH_MAX +2]; + + char f_name[PATH_MAX +2]; DIR *dp; - - struct dirent *entry; + + struct dirent *entry; f_name[PATH_MAX +1] = '\0'; @@ -321,21 +322,21 @@ int read_dir(char *dir_name, int opts, OSMatch *restriction) if((dir_name == NULL)||((dir_size = strlen(dir_name)) > PATH_MAX)) { merror(NULL_ERROR, ARGV0); - + return(-1); } - - + + /* Opening the directory given */ dp = opendir(dir_name); - if(!dp) + if(!dp) { if(errno == ENOTDIR) { if(read_file(dir_name, opts, restriction) == 0) return(0); } - + #ifdef WIN32 int di = 0; char *(defaultfilesn[])= { @@ -359,20 +360,20 @@ int read_dir(char *dir_name, int opts, OSMatch *restriction) if(defaultfilesn[di] == NULL) { merror("%s: WARN: Error opening directory: '%s': %s ", - ARGV0, dir_name, strerror(errno)); + ARGV0, dir_name, strerror(errno)); } - + #else - + merror("%s: WARN: Error opening directory: '%s': %s ", ARGV0, dir_name, strerror(errno)); #endif - + return(-1); } - + /* Checking for real time flag. */ if(opts & CHECK_REALTIME) @@ -386,26 +387,28 @@ int read_dir(char *dir_name, int opts, OSMatch *restriction) while((entry = readdir(dp)) != NULL) { char *s_name; - + /* Just ignore . and .. */ if((strcmp(entry->d_name,".") == 0) || - (strcmp(entry->d_name,"..") == 0)) + (strcmp(entry->d_name,"..") == 0)) continue; - + strncpy(f_name, dir_name, PATH_MAX); - + s_name = f_name; - + s_name += dir_size; /* checking if the file name is already null terminated */ if(*(s_name-1) != '/') *s_name++ = '/'; - + *s_name = '\0'; - + strncpy(s_name, entry->d_name, PATH_MAX - dir_size -2); + + /* Check integrity of the file */ read_file(f_name, opts, restriction); } @@ -420,11 +423,11 @@ int run_dbcheck() int i = 0; __counter = 0; - do + while(syscheck.dir[i] != NULL) { read_dir(syscheck.dir[i], syscheck.opts[i], syscheck.filerestrict[i]); i++; - }while(syscheck.dir[i] != NULL); + } return(0); } @@ -443,7 +446,7 @@ int create_db() { ErrorExit("%s: Unable to create syscheck database." ". Exiting.",ARGV0); - return(0); + return(0); } if(!OSHash_setSize(syscheck.fp, 2048)) @@ -452,14 +455,14 @@ int create_db() return(0); } - + /* dir_name can't be null */ if((syscheck.dir == NULL) || (syscheck.dir[0] == NULL)) { merror("%s: No directories to check.",ARGV0); return(-1); } - + merror("%s: INFO: Starting syscheck database (pre-scan).", ARGV0); @@ -480,7 +483,11 @@ int create_db() i++; }while(syscheck.dir[i] != NULL); - + #if defined (USEINOTIFY) || defined (WIN32) + if(syscheck.realtime && (syscheck.realtime->fd >= 0)) + verbose("%s: INFO: Real time file monitoring started.", ARGV0); + #endif + merror("%s: INFO: Finished creating syscheck database (pre-scan " "completed).", ARGV0); return(0); diff --git a/src/syscheckd/run_check.c b/src/syscheckd/run_check.c index 12a364c..79afe55 100755 --- a/src/syscheckd/run_check.c +++ b/src/syscheckd/run_check.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/syscheckd/run_check.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2010 Trend Micro Inc. * All right reserved. @@ -91,7 +92,7 @@ void send_sk_db() } create_db(1); - + /* Sending scan ending message */ sleep(syscheck.tsleep +10); @@ -102,26 +103,26 @@ void send_sk_db() send_rootcheck_msg("Ending syscheck scan."); } } - - + + /* start_daemon - * Run periodicaly the integrity checking + * Run periodicaly the integrity checking */ void start_daemon() { int day_scanned = 0; int curr_day = 0; - + time_t curr_time = 0; - + time_t prev_time_rk = 0; time_t prev_time_sk = 0; char curr_hour[12]; struct tm *p; - + /* To be used by select. */ #ifdef USEINOTIFY @@ -129,11 +130,11 @@ void start_daemon() fd_set rfds; #endif - + /* - * SCHED_BATCH forces the kernel to assume this is a cpu intensive + * SCHED_BATCH forces the kernel to assume this is a cpu intensive * process - * and gives it a lower priority. This keeps ossec-syscheckd + * and gives it a lower priority. This keeps ossec-syscheckd * from reducing * the interactity of an ssh session when checksumming large files. * This is available in kernel flavors >= 2.6.16 @@ -141,28 +142,28 @@ void start_daemon() #ifdef SCHED_BATCH struct sched_param pri; int status; - + pri.sched_priority = 0; status = sched_setscheduler(0, SCHED_BATCH, &pri); - + debug1("%s: Setting SCHED_BATCH returned: %d", ARGV0, status); #endif - - + + #ifdef DEBUG verbose("%s: Starting daemon ..",ARGV0); #endif - - - + + + /* Some time to settle */ memset(curr_hour, '\0', 12); sleep(syscheck.tsleep * 10); - /* If the scan time/day is set, reset the - * syscheck.time/rootcheck.time + /* If the scan time/day is set, reset the + * syscheck.time/rootcheck.time */ if(syscheck.scan_time || syscheck.scan_day) { @@ -182,20 +183,20 @@ void start_daemon() { prev_time_rk = time(0); } - - + + /* Before entering in daemon mode itself */ prev_time_sk = time(0); sleep(syscheck.tsleep * 10); - + /* If the scan_time or scan_day is set, we need to handle the * current day/time on the loop. */ if(syscheck.scan_time || syscheck.scan_day) { - curr_time = time(0); + curr_time = time(0); p = localtime(&curr_time); @@ -209,7 +210,7 @@ void start_daemon() curr_day = p->tm_mday; - + if(syscheck.scan_time && syscheck.scan_day) { if((OS_IsAfterTime(curr_hour, syscheck.scan_time)) && @@ -235,24 +236,18 @@ void start_daemon() } } - - #if defined (USEINOTIFY) || defined (WIN32) - if(syscheck.realtime && (syscheck.realtime->fd >= 0)) - verbose("%s: INFO: Starting real time file monitoring.", ARGV0); - #endif - - /* Checking every SYSCHECK_WAIT */ + /* Checking every SYSCHECK_WAIT */ while(1) { int run_now = 0; curr_time = time(0); - + /* Checking if syscheck should be restarted, */ run_now = os_check_restart_syscheck(); - + /* Checking if a day_time or scan_time is set. */ if(syscheck.scan_time || syscheck.scan_day) { @@ -265,8 +260,8 @@ void start_daemon() day_scanned = 0; curr_day = p->tm_mday; } - - + + /* Checking for the time of the scan. */ if(!day_scanned && syscheck.scan_time && syscheck.scan_day) { @@ -277,11 +272,11 @@ void start_daemon() run_now = 1; } } - + else if(!day_scanned && syscheck.scan_time) { /* Assign hour/min/sec values */ - snprintf(curr_hour, 9, "%02d:%02d:%02d", + snprintf(curr_hour, 9, "%02d:%02d:%02d", p->tm_hour, p->tm_min, p->tm_sec); if(OS_IsAfterTime(curr_hour, syscheck.scan_time)) @@ -301,8 +296,8 @@ void start_daemon() } } } - - + + /* If time elapsed is higher than the rootcheck_time, * run it. @@ -316,7 +311,7 @@ void start_daemon() } } - + /* If time elapsed is higher than the syscheck time, * run syscheck time. */ @@ -331,8 +326,8 @@ void start_daemon() syscheck.scan_on_start = 1; } - - + + else { /* Sending scan start message */ @@ -353,7 +348,7 @@ void start_daemon() run_dbcheck(); } - + /* Sending scan ending message */ sleep(syscheck.tsleep + 20); if(syscheck.dir[0]) @@ -361,16 +356,16 @@ void start_daemon() merror("%s: INFO: Ending syscheck scan.", ARGV0); send_rootcheck_msg("Ending syscheck scan."); } - + /* Sending database completed message */ send_syscheck_msg(HC_SK_DB_COMPLETED); debug2("%s: DEBUG: Sending database completed message.", ARGV0); - + prev_time_sk = time(0); - } + } #ifdef USEINOTIFY @@ -384,7 +379,7 @@ void start_daemon() FD_SET(syscheck.realtime->fd, &rfds); - run_now = select(syscheck.realtime->fd + 1, &rfds, + run_now = select(syscheck.realtime->fd + 1, &rfds, NULL, NULL, &selecttime); if(run_now < 0) { @@ -441,7 +436,7 @@ void start_daemon() int c_read_file(char *file_name, char *oldsum, char *newsum) { int size = 0, perm = 0, owner = 0, group = 0, md5sum = 0, sha1sum = 0, seechanges = 0; - + struct stat statbuf; os_md5 mf_sum; @@ -451,8 +446,8 @@ int c_read_file(char *file_name, char *oldsum, char *newsum) /* Cleaning sums */ strncpy(mf_sum, "xxx", 4); strncpy(sf_sum, "xxx", 4); - - + + /* Stating the file */ #ifdef WIN32 @@ -482,12 +477,12 @@ int c_read_file(char *file_name, char *oldsum, char *newsum) /* owner */ if(oldsum[2] == '+') - owner = 1; - + owner = 1; + /* group */ if(oldsum[3] == '+') group = 1; - + /* md5 sum */ if(oldsum[4] == '+') md5sum = 1; @@ -506,8 +501,8 @@ int c_read_file(char *file_name, char *oldsum, char *newsum) sha1sum = 0; seechanges = 1; } - - + + /* Generating new checksum */ #ifdef WIN32 if(S_ISREG(statbuf.st_mode)) @@ -518,7 +513,7 @@ int c_read_file(char *file_name, char *oldsum, char *newsum) if(sha1sum || md5sum) { /* Generating checksums of the file. */ - if(OS_MD5_SHA1_File(file_name, mf_sum, sf_sum) < 0) + if(OS_MD5_SHA1_File(file_name, syscheck.prefilter_cmd, mf_sum, sf_sum) < 0) { strncpy(sf_sum, "xxx", 4); strncpy(mf_sum, "xxx", 4); @@ -537,7 +532,7 @@ int c_read_file(char *file_name, char *oldsum, char *newsum) if(sha1sum || md5sum) { /* Generating checksums of the file. */ - if(OS_MD5_SHA1_File(file_name, mf_sum, sf_sum) < 0) + if(OS_MD5_SHA1_File(file_name, syscheck.prefilter_cmd, mf_sum, sf_sum) < 0) { strncpy(sf_sum, "xxx", 4); strncpy(mf_sum, "xxx", 4); @@ -547,7 +542,7 @@ int c_read_file(char *file_name, char *oldsum, char *newsum) } } #endif - + newsum[0] = '\0'; newsum[255] = '\0'; snprintf(newsum,255,"%d:%d:%d:%d:%s:%s", diff --git a/src/syscheckd/run_realtime.c b/src/syscheckd/run_realtime.c index 19f7c7b..839e5b8 100755 --- a/src/syscheckd/run_realtime.c +++ b/src/syscheckd/run_realtime.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/syscheckd/run_realtime.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -113,7 +114,7 @@ int realtime_checksumfile(char *file_name) #include -#define REALTIME_MONITOR_FLAGS IN_MODIFY|IN_ATTRIB|IN_MOVED_TO|IN_DELETE|IN_MOVED_FROM +#define REALTIME_MONITOR_FLAGS IN_MODIFY|IN_ATTRIB|IN_MOVED_FROM|IN_MOVED_TO|IN_CREATE|IN_DELETE|IN_DELETE_SELF #define REALTIME_EVENT_SIZE (sizeof (struct inotify_event)) #define REALTIME_EVENT_BUFFER (2048 * (REALTIME_EVENT_SIZE + 16)) @@ -139,7 +140,7 @@ int realtime_start() merror("%s: ERROR: Unable to initialize inotify.", ARGV0); return(-1); } - #endif + #endif return(1); } @@ -166,10 +167,10 @@ int realtime_adddir(char *dir) wd = inotify_add_watch(syscheck.realtime->fd, dir, - REALTIME_MONITOR_FLAGS); + REALTIME_MONITOR_FLAGS); if(wd < 0) { - merror("%s: ERROR: Unable to add directory to real time " + merror("%s: ERROR: Unable to add directory to real time " "monitoring: '%s'. %d %d", ARGV0, dir, wd, errno); } else @@ -211,13 +212,13 @@ int realtime_process() len = read(syscheck.realtime->fd, buf, REALTIME_EVENT_BUFFER); - if (len < 0) + if (len < 0) { merror("%s: ERROR: Unable to read from real time buffer.", ARGV0); - } + } else if (len > 0) { - while (i < len) + while (i < len) { event = (struct inotify_event *) &buf[i]; @@ -231,7 +232,7 @@ int realtime_process() snprintf(wdchar, 32, "%d", event->wd); - snprintf(final_name, MAX_LINE, "%s/%s", + snprintf(final_name, MAX_LINE, "%s/%s", (char *)OSHash_Get(syscheck.realtime->dirtb, wdchar), event->name); realtime_checksumfile(final_name); @@ -280,7 +281,7 @@ void CALLBACK RTCallBack(DWORD dwerror, DWORD dwBytes, LPOVERLAPPED overlap) if(dwerror != ERROR_SUCCESS) { - merror("%s: ERROR: real time call back called, but error is set.", + merror("%s: ERROR: real time call back called, but error is set.", ARGV0); return; } @@ -292,12 +293,12 @@ void CALLBACK RTCallBack(DWORD dwerror, DWORD dwBytes, LPOVERLAPPED overlap) rtlocald = OSHash_Get(syscheck.realtime->dirtb, wdchar); if(rtlocald == NULL) { - merror("%s: ERROR: real time call back called, but hash is empty.", + merror("%s: ERROR: real time call back called, but hash is empty.", ARGV0); return; } - + do { @@ -369,11 +370,11 @@ int realtime_win32read(win32rtfim *rtlocald) TRUE, FILE_NOTIFY_CHANGE_FILE_NAME|FILE_NOTIFY_CHANGE_DIR_NAME|FILE_NOTIFY_CHANGE_SIZE|FILE_NOTIFY_CHANGE_LAST_WRITE, 0, - &rtlocald->overlap, + &rtlocald->overlap, RTCallBack); if(rc == 0) { - merror("%s: ERROR: Unable to set directory for monitoring: %s", + merror("%s: ERROR: Unable to set directory for monitoring: %s", ARGV0, rtlocald->dir); sleep(2); } @@ -403,7 +404,7 @@ int realtime_adddir(char *dir) os_calloc(1, sizeof(win32rtfim), rtlocald); - + rtlocald->h = CreateFile(dir, FILE_LIST_DIRECTORY, @@ -414,8 +415,8 @@ int realtime_adddir(char *dir) NULL); - if(rtlocald->h == INVALID_HANDLE_VALUE || - rtlocald->h == NULL) + if(rtlocald->h == INVALID_HANDLE_VALUE || + rtlocald->h == NULL) { free(rtlocald); rtlocald = NULL; @@ -435,7 +436,7 @@ int realtime_adddir(char *dir) if(OSHash_Get(syscheck.realtime->dirtb, wdchar)) { - merror("%s: ERROR: Entry already in the real time hash: %s", + merror("%s: ERROR: Entry already in the real time hash: %s", ARGV0, wdchar); CloseHandle(rtlocald->overlap.hEvent); free(rtlocald); diff --git a/src/syscheckd/seechanges.c b/src/syscheckd/seechanges.c index 39ee33f..15496c8 100755 --- a/src/syscheckd/seechanges.c +++ b/src/syscheckd/seechanges.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/syscheckd/seechanges.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -30,7 +31,7 @@ char *gen_diff_alert(char *filename, int alert_diff_time) snprintf(buf, OS_MAXSTR, "%s/local/%s/diff.%d", DIFF_DIR_PATH, filename, alert_diff_time); - + fp = fopen(buf, "r"); if(!fp) { @@ -55,7 +56,7 @@ char *gen_diff_alert(char *filename, int alert_diff_time) else { /* Weird diff with only one large line. */ - buf[256] = '\0'; + buf[256] = '\0'; } } else @@ -69,19 +70,19 @@ char *gen_diff_alert(char *filename, int alert_diff_time) /* Getting up to 20 line changes. */ tmp_str = buf; - + while(tmp_str && (*tmp_str != '\0')) { tmp_str = strchr(tmp_str, '\n'); if(!tmp_str) - break; + break; else if(n >= 19) { - *tmp_str = '\0'; + *tmp_str = '\0'; break; } n++; - tmp_str++; + tmp_str++; } @@ -90,8 +91,8 @@ char *gen_diff_alert(char *filename, int alert_diff_time) buf, n>=19? "\nMore changes..": ""); - - + + fclose(fp); return(strdup(diff_alert)); } @@ -133,7 +134,7 @@ int seechanges_createpath(char *filename) char *tmpstr = NULL; char *newdir = NULL; - + os_strdup(filename, buffer); newdir = buffer; tmpstr = strchr(buffer +1, '/'); @@ -153,9 +154,9 @@ int seechanges_createpath(char *filename) { #ifndef WIN32 if(mkdir(newdir, 0770) == -1) - #else + #else if(mkdir(newdir) == -1) - #endif + #endif { merror(MKDIR_ERROR, ARGV0, newdir); free(buffer); @@ -193,7 +194,7 @@ char *seechanges_addfile(char *filename) os_md5 md5sum_old; os_md5 md5sum_new; - + old_location[OS_MAXSTR] = '\0'; tmp_location[OS_MAXSTR] = '\0'; diff_cmd[OS_MAXSTR] = '\0'; @@ -221,7 +222,7 @@ char *seechanges_addfile(char *filename) if(OS_MD5_File(filename, md5sum_new) != 0) { //merror("%s: ERROR: Invalid internal state (missing '%s').", - // ARGV0, filename); + // ARGV0, filename); return(NULL); } @@ -247,15 +248,15 @@ char *seechanges_addfile(char *filename) /* Run diff. */ date_of_change = File_DateofChange(old_location); - snprintf(diff_cmd, 2048, "diff \"%s\" \"%s\" > \"%s/local/%s/diff.%d\" " + snprintf(diff_cmd, 2048, "diff \"%s\" \"%s\" > \"%s/local/%s/diff.%d\" " "2>/dev/null", - tmp_location, old_location, + tmp_location, old_location, DIFF_DIR_PATH, filename +1, date_of_change); if(system(diff_cmd) != 256) { merror("%s: ERROR: Unable to run diff for %s", ARGV0, filename); - return(NULL); + return(NULL); } diff --git a/src/syscheckd/syscheck-baseline.c b/src/syscheckd/syscheck-baseline.c index 2a77eb1..059aa25 100755 --- a/src/syscheckd/syscheck-baseline.c +++ b/src/syscheckd/syscheck-baseline.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/syscheckd/syscheck-baseline.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -58,20 +59,20 @@ int main(int argc, char **argv) { int c,r,no_stop = 1; int test_config = 0; - + char *cfg = DEFAULTCPATH; char *input_f = NULL; char *output_f = NULL; - - + + /* Zeroing the structure */ syscheck.workdir = NULL; /* Setting the name */ OS_SetName(ARGV0); - - + + while((c = getopt(argc, argv, "VtdshD:c:i:o:")) != -1) { switch(c) @@ -84,7 +85,7 @@ int main(int argc, char **argv) break; case 's': no_stop = 0; - break; + break; case 'd': nowDebug(); break; @@ -110,10 +111,10 @@ int main(int argc, char **argv) break; case 't': test_config = 1; - break; + break; default: help(ARGV0); - break; + break; } } @@ -140,13 +141,13 @@ int main(int argc, char **argv) /* Reading internal options */ read_internal(no_stop); - - + + /* Exit if testing config */ if(test_config) exit(0); - + /* Setting default values */ if(syscheck.workdir == NULL) syscheck.workdir = DEFAULTDIR; @@ -156,7 +157,7 @@ int main(int argc, char **argv) syscheck.db = (char *)calloc(1024,sizeof(char)); if(syscheck.db == NULL) ErrorExit(MEM_ERROR,ARGV0); - + snprintf(syscheck.db,1023, output_f); @@ -181,20 +182,20 @@ int main(int argc, char **argv) /* Start the signal handling */ StartSIG(ARGV0); - + /* Start up message */ verbose(STARTUP_MSG, ARGV0, getpid()); - + /* Create local database */ create_db(0); - + fflush(syscheck.fp); - return(0); + return(0); } diff --git a/src/syscheckd/syscheck.c b/src/syscheckd/syscheck.c index 67a5879..d66aa10 100755 --- a/src/syscheckd/syscheck.c +++ b/src/syscheckd/syscheck.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/syscheckd/syscheck.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -29,7 +30,7 @@ #include "rootcheck/rootcheck.h" -int dump_syscheck_entry(config *syscheck, char *entry, int vals, int reg); +int dump_syscheck_entry(config *syscheck, char *entry, int vals, int reg, char *restrictfile); @@ -75,7 +76,7 @@ int Start_win32_Syscheck() if(!syscheck.dir) { merror(SK_NO_DIR, ARGV0); - dump_syscheck_entry(&syscheck, "", 0, 0); + dump_syscheck_entry(&syscheck, "", 0, 0, NULL); } else if(!syscheck.dir[0]) { @@ -85,7 +86,7 @@ int Start_win32_Syscheck() if(!syscheck.registry) { - dump_syscheck_entry(&syscheck, "", 0, 1); + dump_syscheck_entry(&syscheck, "", 0, 1, NULL); } syscheck.registry[0] = NULL; @@ -107,18 +108,18 @@ int Start_win32_Syscheck() syscheck.rootcheck = 0; merror("%s: WARN: Rootcheck module disabled.", ARGV0); } - + /* Printing options */ r = 0; while(syscheck.registry[r] != NULL) { - verbose("%s: INFO: Monitoring registry entry: '%s'.", + verbose("%s: INFO: Monitoring registry entry: '%s'.", ARGV0, syscheck.registry[r]); r++; } - + r = 0; while(syscheck.dir[r] != NULL) { @@ -130,9 +131,9 @@ int Start_win32_Syscheck() /* Start up message */ verbose(STARTUP_MSG, ARGV0, getpid()); - - - + + + /* Some sync time */ sleep(syscheck.tsleep + 10); @@ -140,35 +141,35 @@ int Start_win32_Syscheck() /* Waiting if agent started properly. */ os_wait(); - + start_daemon(); exit(0); -} +} #endif /* Syscheck unix main. */ -#ifndef WIN32 +#ifndef WIN32 int main(int argc, char **argv) { int c,r; int test_config = 0,run_foreground = 0; - + char *cfg = DEFAULTCPATH; - - + + /* Zeroing the structure */ syscheck.workdir = NULL; /* Setting the name */ OS_SetName(ARGV0); - - + + while((c = getopt(argc, argv, "VtdhfD:c:")) != -1) { switch(c) @@ -197,10 +198,10 @@ int main(int argc, char **argv) break; case 't': test_config = 1; - break; + break; default: help(ARGV0); - break; + break; } } @@ -221,7 +222,7 @@ int main(int argc, char **argv) { if(!test_config) merror(SK_NO_DIR, ARGV0); - dump_syscheck_entry(&syscheck, "", 0, 0); + dump_syscheck_entry(&syscheck, "", 0, 0, NULL); } else if(!syscheck.dir[0]) { @@ -238,8 +239,8 @@ int main(int argc, char **argv) /* Reading internal options */ read_internal(); - - + + /* Rootcheck config */ if(rootcheck_init(test_config) == 0) @@ -252,30 +253,30 @@ int main(int argc, char **argv) merror("%s: WARN: Rootcheck module disabled.", ARGV0); } - + /* Exit if testing config */ if(test_config) exit(0); - + /* Setting default values */ if(syscheck.workdir == NULL) syscheck.workdir = DEFAULTDIR; - if(!run_foreground) + if(!run_foreground) { nowDaemon(); goDaemon(); } - + /* Initial time to settle */ - sleep(syscheck.tsleep + 2); - - + sleep(syscheck.tsleep + 2); + + /* Connect to the queue */ if((syscheck.queue = StartMQ(DEFAULTQPATH,WRITE)) < 0) - { + { merror(QUEUE_ERROR, ARGV0, DEFAULTQPATH, strerror(errno)); sleep(5); @@ -292,7 +293,7 @@ int main(int argc, char **argv) /* Start the signal handling */ StartSIG(ARGV0); - + /* Creating pid */ if(CreatePID(ARGV0, getpid()) < 0) @@ -336,8 +337,8 @@ int main(int argc, char **argv) } r++; } - - + + /* Some sync time */ sleep(syscheck.tsleep + 10); @@ -345,7 +346,7 @@ int main(int argc, char **argv) /* Start the daemon */ start_daemon(); - return(0); + return(0); } #endif /* ifndef WIN32 */ diff --git a/src/syscheckd/syscheck.h b/src/syscheckd/syscheck.h index 1827b83..df51f0e 100755 --- a/src/syscheckd/syscheck.h +++ b/src/syscheckd/syscheck.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/syscheckd/syscheck.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation */ - + #ifndef __SYSCHECK_H @@ -49,11 +50,11 @@ int create_db(); /* int run_dbcheck() * Checks database for changes. */ -int run_dbcheck(); - +int run_dbcheck(); + /** void os_winreg_check() * Checks the registry for changes. - */ + */ void os_winreg_check(); /* starts real time */ diff --git a/src/syscheckd/win-registry.c b/src/syscheckd/win-registry.c index b0e6bd3..25791d7 100644 --- a/src/syscheckd/win-registry.c +++ b/src/syscheckd/win-registry.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/syscheckd/win-registry.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,20 +9,20 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ - + /* Windows only */ #ifdef WIN32 - + #include "shared.h" #include "syscheck.h" #include "os_crypto/md5/md5_op.h" #include "os_crypto/sha1/sha1_op.h" -#include "os_crypto/md5_sha1/md5_sha1_op.h" +#include "os_crypto/md5_sha1/md5_sha1_op.h" /* Default values */ @@ -33,8 +34,8 @@ #define SYS_WIN_REG "syscheck/syscheckregistry.db" #define SYS_REG_TMP "syscheck/syscheck_sum.tmp" - - + + /* Global variables */ HKEY sub_tree; int ig_count = 0; @@ -50,7 +51,7 @@ void os_winreg_open_key(char *subkey, char *fullkey_name); int os_winreg_changed(char *key, char *md5, char *sha1) { char buf[MAX_LINE +1]; - + buf[MAX_LINE] = '\0'; @@ -68,17 +69,17 @@ int os_winreg_changed(char *key, char *md5, char *sha1) if(n_buf == NULL) continue; - *n_buf = '\0'; - + *n_buf = '\0'; + n_buf = strchr(buf, ' '); if(n_buf == NULL) continue; - + if(strcmp(n_buf +1, key) != 0) continue; - + /* Entry found, checking if checksum is the same */ - *n_buf = '\0'; + *n_buf = '\0'; if((strncmp(buf, md5, sizeof(os_md5) -1) == 0)&& (strcmp(buf + sizeof(os_md5) -1, sha1) == 0)) { @@ -164,11 +165,11 @@ char *os_winreg_sethkey(char *reg_entry) /* Checking if ret has nothing else. */ if(ret && (*ret == '\0')) ret = NULL; - - /* fixing tmp_str and the real name of the registry */ + + /* fixing tmp_str and the real name of the registry */ if(tmp_str && (*tmp_str == '\0')) *tmp_str = '\\'; - + return(ret); } @@ -176,7 +177,7 @@ char *os_winreg_sethkey(char *reg_entry) /* void os_winreg_querykey(HKEY hKey, char *p_key) * Query the key and get all its values. */ -void os_winreg_querykey(HKEY hKey, char *p_key, char *full_key_name) +void os_winreg_querykey(HKEY hKey, char *p_key, char *full_key_name) { int i, rc; DWORD j; @@ -194,8 +195,8 @@ void os_winreg_querykey(HKEY hKey, char *p_key, char *full_key_name) DWORD value_count; /* Variables for RegEnumValue */ - TCHAR value_buffer[MAX_VALUE_NAME +1]; - TCHAR data_buffer[MAX_VALUE_NAME +1]; + TCHAR value_buffer[MAX_VALUE_NAME +1]; + TCHAR data_buffer[MAX_VALUE_NAME +1]; DWORD value_size; DWORD data_size; @@ -209,7 +210,7 @@ void os_winreg_querykey(HKEY hKey, char *p_key, char *full_key_name) sub_key_name_b[0] = '\0'; sub_key_name_b[MAX_KEY_LENGTH] = '\0'; sub_key_name_b[MAX_KEY_LENGTH +1] = '\0'; - + /* We use the class_name, subkey_count and the value count. */ rc = RegQueryInfoKey(hKey, class_name_b, &class_name_s, NULL, @@ -228,14 +229,14 @@ void os_winreg_querykey(HKEY hKey, char *p_key, char *full_key_name) if(subkey_count) { /* We open each subkey and call open_key */ - for(i=0;iip->netmask, final_mask, 128); - snprintf(final_ip, 128, "%s%s",keys.keyentries[agt_id]->ip->ip, + snprintf(final_ip, 128, "%s%s",keys.keyentries[agt_id]->ip->ip, final_mask); @@ -329,16 +330,16 @@ int main(int argc, char **argv) } else { - printf("%s,%s,%s,%s,", + printf("%s,%s,%s,%s,", keys.keyentries[agt_id]->id, keys.keyentries[agt_id]->name, final_ip, - print_agent_status(agt_status)); + print_agent_status(agt_status)); } } else { - agt_status = get_agent_status(NULL, NULL); + agt_status = get_agent_status(NULL, NULL); agt_info = get_agent_info(NULL, "127.0.0.1"); if(!csv_output) @@ -354,17 +355,17 @@ int main(int argc, char **argv) printf("000,%s,127.0.0.1,%s/Local,", shost, print_agent_status(agt_status)); - + } } - + if(!csv_output) { printf(" Operating system: %s\n", agt_info->os); printf(" Client version: %s\n", agt_info->version); printf(" Last keep alive: %s\n\n", agt_info->last_keepalive); - + if(end_time) { @@ -381,14 +382,14 @@ int main(int argc, char **argv) } else { - printf("%s,%s,%s,%s,%s,\n", + printf("%s,%s,%s,%s,%s,\n", agt_info->os, agt_info->version, agt_info->last_keepalive, agt_info->syscheck_time, agt_info->rootcheck_time); } - + exit(0); } @@ -423,7 +424,7 @@ int main(int argc, char **argv) exit(0); } - + if(restart_syscheck && agent_id) @@ -466,8 +467,8 @@ int main(int argc, char **argv) exit(0); } - - + + if(restart_agent && agent_id) { /* Connecting to remoted. */ @@ -523,7 +524,7 @@ int main(int argc, char **argv) exit(0); } - + printf("\n** Invalid argument combination.\n"); helpmsg(); diff --git a/src/util/clear_stats.c b/src/util/clear_stats.c index 6060159..068b573 100755 --- a/src/util/clear_stats.c +++ b/src/util/clear_stats.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/util/clear_stats.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -36,24 +37,24 @@ int main(int argc, char **argv) { int clear_daily = 0; int clear_weekly = 0; - + char *dir = DEFAULTDIR; char *group = GROUPGLOBAL; char *user = USER; int gid; int uid; - + /* Setting the name */ OS_SetName(ARGV0); - - + + /* user arguments */ if(argc != 2) { helpmsg(); } - + /* Getting the group name */ gid = Privsep_GetGroup(group); uid = Privsep_GetUser(user); @@ -62,14 +63,14 @@ int main(int argc, char **argv) ErrorExit(USER_ERROR, ARGV0, user, group); } - + /* Setting the group */ if(Privsep_SetGroup(gid) < 0) { ErrorExit(SETGID_ERROR,ARGV0, group); } - - + + /* Chrooting to the default directory */ if(Privsep_Chroot(dir) < 0) { @@ -79,14 +80,14 @@ int main(int argc, char **argv) /* Inside chroot now */ nowChroot(); - + /* Setting the user */ if(Privsep_SetUser(uid) < 0) { ErrorExit(SETUID_ERROR, ARGV0, user); } - + /* User options */ if(strcmp(argv[1], "-h") == 0) { @@ -124,28 +125,28 @@ int main(int argc, char **argv) { ErrorExit("%s: Unable to open: '%s'", ARGV0, daily_dir); } - + while((entry = readdir(daily)) != NULL) { char full_path[OS_MAXSTR +1]; - - /* Do not even attempt to delete . and .. :) */ + + /* Do not even attempt to delete . and .. :) */ if((strcmp(entry->d_name,".") == 0)|| (strcmp(entry->d_name,"..") == 0)) { continue; } - + /* Remove file */ full_path[OS_MAXSTR] = '\0'; snprintf(full_path, OS_MAXSTR, "%s/%s", daily_dir, entry->d_name); unlink(full_path); } - + closedir(daily); } - - + + /* Clear weekly averages */ if(clear_weekly) { @@ -161,7 +162,7 @@ int main(int argc, char **argv) daily = opendir(dir_path); if(!daily) { - ErrorExit("%s: Unable to open: '%s' (no stats)", + ErrorExit("%s: Unable to open: '%s' (no stats)", ARGV0, dir_path); } @@ -178,17 +179,17 @@ int main(int argc, char **argv) /* Remove file */ full_path[OS_MAXSTR] = '\0'; - snprintf(full_path, OS_MAXSTR, "%s/%s", dir_path, + snprintf(full_path, OS_MAXSTR, "%s/%s", dir_path, entry->d_name); unlink(full_path); } - + i++; closedir(daily); } } - - printf("\n** Internal stats clear.\n\n"); + + printf("\n** Internal stats clear.\n\n"); return(0); } diff --git a/src/util/list_agents.c b/src/util/list_agents.c index f1781b1..c363ab6 100755 --- a/src/util/list_agents.c +++ b/src/util/list_agents.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/util/list_agents.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -35,24 +36,24 @@ int main(int argc, char **argv) char *dir = DEFAULTDIR; char *group = GROUPGLOBAL; char *user = USER; - + char *msg; char **agent_list; int gid; int uid; int flag; - + /* Setting the name */ OS_SetName(ARGV0); - - + + /* user arguments */ if(argc < 2) { helpmsg(); } - + /* Getting the group name */ gid = Privsep_GetGroup(group); uid = Privsep_GetUser(user); @@ -61,14 +62,14 @@ int main(int argc, char **argv) ErrorExit(USER_ERROR, ARGV0, user, group); } - + /* Setting the group */ if(Privsep_SetGroup(gid) < 0) { ErrorExit(SETGID_ERROR,ARGV0, group); } - - + + /* Chrooting to the default directory */ if(Privsep_Chroot(dir) < 0) { @@ -78,14 +79,14 @@ int main(int argc, char **argv) /* Inside chroot now */ nowChroot(); - + /* Setting the user */ if(Privsep_SetUser(uid) < 0) { ErrorExit(SETUID_ERROR, ARGV0, user); } - + /* User options */ if(strcmp(argv[1], "-h") == 0) { @@ -117,7 +118,7 @@ int main(int argc, char **argv) if(agent_list) { char **agent_list_pt = agent_list; - + while(*agent_list) { printf("%s %s\n", *agent_list, msg); diff --git a/src/util/ossec-regex.c b/src/util/ossec-regex.c index 70df990..bffba67 100644 --- a/src/util/ossec-regex.c +++ b/src/util/ossec-regex.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/util/ossec-regex.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -30,22 +31,22 @@ void helpmsg() int main(int argc, char **argv) { char *pattern; - + char msg[OS_MAXSTR +1]; memset(msg, '\0', OS_MAXSTR +1); - OSRegex regex; - OSMatch matcher; + OSRegex regex; + OSMatch matcher; OS_SetName(ARGV0); - - + + /* user arguments */ if(argc != 2) { helpmsg(); return(-1); } - + /* User options */ if(strcmp(argv[1], "-h") == 0) { @@ -54,10 +55,10 @@ int main(int argc, char **argv) } os_strdup(argv[1], pattern); - if(!OSRegex_Compile(pattern, ®ex, 0)) - { + if(!OSRegex_Compile(pattern, ®ex, 0)) + { printf("pattern does not compile with OSRegex_Compile\n"); - return(-1); + return(-1); } if(!OSMatch_Compile(pattern, &matcher, 0)) { @@ -67,33 +68,33 @@ int main(int argc, char **argv) while((fgets(msg, OS_MAXSTR, stdin)) != NULL) - { - /* Removing new line. */ + { + /* Removing new line. */ if(msg[strlen(msg) -1] == '\n') msg[strlen(msg) -1] = '\0'; - /* Make sure we ignore blank lines. */ - if(strlen(msg) < 2) { continue; } + /* Make sure we ignore blank lines. */ + if(strlen(msg) < 2) { continue; } if(OSRegex_Execute(msg, ®ex)) - printf("+OSRegex_Execute: %s\n",msg); + printf("+OSRegex_Execute: %s\n",msg); /* else - printf("-OSRegex_Execute: \n"); + printf("-OSRegex_Execute: \n"); */ - if(OS_Regex(pattern, msg)) + if(OS_Regex(pattern, msg)) printf("+OS_Regex : %s\n", msg); /* else - printf("-OS_Regex: \n"); + printf("-OS_Regex: \n"); */ - if(OSMatch_Execute(msg, strlen(msg), &matcher)) - printf("+OSMatch_Compile: %s\n", msg); - - if(OS_Match2(pattern, msg)) - printf("+OS_Match2 : %s\n", msg); + if(OSMatch_Execute(msg, strlen(msg), &matcher)) + printf("+OSMatch_Compile: %s\n", msg); + + if(OS_Match2(pattern, msg)) + printf("+OS_Match2 : %s\n", msg); } return(0); } diff --git a/src/util/rootcheck_control.c b/src/util/rootcheck_control.c index fff7a55..dc1c62f 100755 --- a/src/util/rootcheck_control.c +++ b/src/util/rootcheck_control.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/util/rootcheck_control.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -21,7 +22,7 @@ /** help **/ void helpmsg() { - printf("\nOSSEC HIDS %s: Manages the policy and auditing database.\n", + printf("\nOSSEC HIDS %s: Manages the policy and auditing database.\n", ARGV0); printf("Available options:\n"); printf("\t-h This help message.\n"); @@ -54,13 +55,13 @@ int main(int argc, char **argv) int active_only = 0, csv_output = 0; char shost[512]; - - - + + + /* Setting the name */ OS_SetName(ARGV0); - - + + /* user arguments */ if(argc < 2) { @@ -84,17 +85,17 @@ int main(int argc, char **argv) list_agents++; break; case 's': - csv_output = 1; + csv_output = 1; break; case 'c': active_only++; - break; + break; case 'r': resolved_only = 1; - break; + break; case 'q': resolved_only = 2; - break; + break; case 'L': show_last = 1; break; @@ -122,8 +123,8 @@ int main(int argc, char **argv) } } - - + + /* Getting the group name */ gid = Privsep_GetGroup(group); uid = Privsep_GetUser(user); @@ -132,14 +133,14 @@ int main(int argc, char **argv) ErrorExit(USER_ERROR, ARGV0, user, group); } - + /* Setting the group */ if(Privsep_SetGroup(gid) < 0) { ErrorExit(SETGID_ERROR,ARGV0, group); } - - + + /* Chrooting to the default directory */ if(Privsep_Chroot(dir) < 0) { @@ -149,7 +150,7 @@ int main(int argc, char **argv) /* Inside chroot now */ nowChroot(); - + /* Setting the user */ if(Privsep_SetUser(uid) < 0) @@ -168,13 +169,13 @@ int main(int argc, char **argv) } - + /* Listing available agents. */ if(list_agents) { if(!csv_output) { - printf("\nOSSEC HIDS %s. List of available agents:", + printf("\nOSSEC HIDS %s. List of available agents:", ARGV0); printf("\n ID: 000, Name: %s (server), IP: 127.0.0.1, " "Active/Local\n", shost); @@ -187,7 +188,7 @@ int main(int argc, char **argv) printf("\n"); exit(0); } - + /* Update rootcheck database. */ @@ -217,7 +218,7 @@ int main(int argc, char **argv) continue; } - snprintf(full_path, OS_MAXSTR,"%s/%s", ROOTCHECK_DIR, + snprintf(full_path, OS_MAXSTR,"%s/%s", ROOTCHECK_DIR, entry->d_name); fp = fopen(full_path, "w"); @@ -236,7 +237,7 @@ int main(int argc, char **argv) exit(0); } - else if((strcmp(agent_id, "000") == 0) || + else if((strcmp(agent_id, "000") == 0) || (strcmp(agent_id, "local") == 0)) { char final_dir[1024]; @@ -277,7 +278,7 @@ int main(int argc, char **argv) } } - + /* Printing information from an agent. */ if(info_agent) { @@ -293,9 +294,9 @@ int main(int argc, char **argv) if(!csv_output) printf("\nPolicy and auditing events for local system '%s - %s':\n", shost, "127.0.0.1"); - + print_rootcheck(NULL, - NULL, NULL, resolved_only, csv_output, show_last); + NULL, NULL, resolved_only, csv_output, show_last); } else { @@ -312,7 +313,7 @@ int main(int argc, char **argv) /* Getting netmask from ip. */ final_ip[128] = '\0'; final_mask[128] = '\0'; - getNetmask(keys.keyentries[i]->ip->netmask, + getNetmask(keys.keyentries[i]->ip->netmask, final_mask, 128); snprintf(final_ip, 128, "%s%s",keys.keyentries[i]->ip->ip, final_mask); @@ -320,20 +321,20 @@ int main(int argc, char **argv) if(!csv_output) printf("\nPolicy and auditing events for agent " "'%s (%s) - %s':\n", - keys.keyentries[i]->name, keys.keyentries[i]->id, + keys.keyentries[i]->name, keys.keyentries[i]->id, final_ip); print_rootcheck(keys.keyentries[i]->name, - keys.keyentries[i]->ip->ip, NULL, + keys.keyentries[i]->ip->ip, NULL, resolved_only, csv_output, show_last); } - + exit(0); } - + printf("\n** Invalid argument combination.\n"); helpmsg(); diff --git a/src/util/syscheck_control.c b/src/util/syscheck_control.c index 7f7a7e7..43b2e38 100755 --- a/src/util/syscheck_control.c +++ b/src/util/syscheck_control.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/util/syscheck_control.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -21,7 +22,7 @@ /** help **/ void helpmsg() { - printf("\nOSSEC HIDS %s: Manages the integrity checking database.\n", + printf("\nOSSEC HIDS %s: Manages the integrity checking database.\n", ARGV0); printf("Available options:\n"); printf("\t-h This help message.\n"); @@ -57,13 +58,13 @@ int main(int argc, char **argv) int active_only = 0, csv_output = 0; char shost[512]; - - - + + + /* Setting the name */ OS_SetName(ARGV0); - - + + /* user arguments */ if(argc < 2) { @@ -91,15 +92,15 @@ int main(int argc, char **argv) break; case 'd': zero_counter = 2; - break; + break; case 's': - csv_output = 1; + csv_output = 1; case 'c': active_only++; - break; + break; case 'r': registry_only = 1; - break; + break; case 'i': info_agent++; if(!optarg) @@ -132,8 +133,8 @@ int main(int argc, char **argv) } } - - + + /* Getting the group name */ gid = Privsep_GetGroup(group); uid = Privsep_GetUser(user); @@ -142,14 +143,14 @@ int main(int argc, char **argv) ErrorExit(USER_ERROR, ARGV0, user, group); } - + /* Setting the group */ if(Privsep_SetGroup(gid) < 0) { ErrorExit(SETGID_ERROR,ARGV0, group); } - - + + /* Chrooting to the default directory */ if(Privsep_Chroot(dir) < 0) { @@ -159,7 +160,7 @@ int main(int argc, char **argv) /* Inside chroot now */ nowChroot(); - + /* Setting the user */ if(Privsep_SetUser(uid) < 0) @@ -178,13 +179,13 @@ int main(int argc, char **argv) } - + /* Listing available agents. */ if(list_agents) { if(!csv_output) { - printf("\nOSSEC HIDS %s. List of available agents:", + printf("\nOSSEC HIDS %s. List of available agents:", ARGV0); printf("\n ID: 000, Name: %s (server), IP: 127.0.0.1, " "Active/Local\n", shost); @@ -197,7 +198,7 @@ int main(int argc, char **argv) printf("\n"); exit(0); } - + /* Update syscheck database. */ @@ -227,7 +228,7 @@ int main(int argc, char **argv) continue; } - snprintf(full_path, OS_MAXSTR,"%s/%s", SYSCHECK_DIR, + snprintf(full_path, OS_MAXSTR,"%s/%s", SYSCHECK_DIR, entry->d_name); fp = fopen(full_path, "w"); @@ -246,7 +247,7 @@ int main(int argc, char **argv) exit(0); } - else if((strcmp(agent_id, "000") == 0) || + else if((strcmp(agent_id, "000") == 0) || (strcmp(agent_id, "local") == 0)) { char final_dir[1024]; @@ -299,7 +300,7 @@ int main(int argc, char **argv) } } - + /* Printing information from an agent. */ if(info_agent) { @@ -316,19 +317,19 @@ int main(int argc, char **argv) shost, "127.0.0.1"); if(fname) { - printf("Detailed information for entries matching: '%s'\n", + printf("Detailed information for entries matching: '%s'\n", fname); } - + print_syscheck(NULL, - NULL, fname, 0, 0, + NULL, fname, 0, 0, csv_output, zero_counter); } else if(strchr(agent_id, '@')) { if(fname) { - printf("Detailed information for entries matching: '%s'\n", + printf("Detailed information for entries matching: '%s'\n", fname); } print_syscheck(agent_id, NULL, fname, registry_only, 0, @@ -357,33 +358,33 @@ int main(int argc, char **argv) { printf("\nIntegrity changes for 'Windows Registry' of" " agent '%s (%s) - %s':\n", - keys.keyentries[i]->name, keys.keyentries[i]->id, - final_ip); + keys.keyentries[i]->name, keys.keyentries[i]->id, + final_ip); } else { printf("\nIntegrity changes for agent " "'%s (%s) - %s':\n", - keys.keyentries[i]->name, keys.keyentries[i]->id, + keys.keyentries[i]->name, keys.keyentries[i]->id, final_ip); } if(fname) { - printf("Detailed information for entries matching: '%s'\n", + printf("Detailed information for entries matching: '%s'\n", fname); } print_syscheck(keys.keyentries[i]->name, - keys.keyentries[i]->ip->ip, fname, + keys.keyentries[i]->ip->ip, fname, registry_only, 0, csv_output, zero_counter); } - + exit(0); } - + printf("\n** Invalid argument combination.\n"); helpmsg(); diff --git a/src/util/syscheck_update.c b/src/util/syscheck_update.c index 1a7f25a..e39e3c8 100755 --- a/src/util/syscheck_update.c +++ b/src/util/syscheck_update.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/util/syscheck_update.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -20,17 +21,16 @@ /** help **/ void helpmsg() { - printf("\nOSSEC HIDS %s: Updates the integrity check database.\n", ARGV0); + printf("\nOSSEC HIDS %s: Updates (clears) the integrity check database.\n", ARGV0); printf("Available options:\n"); printf("\t-h This help message.\n"); printf("\t-l List available agents.\n"); - printf("\t-a Update syscheck database for all agents.\n"); - printf("\t-u Update syscheck database for a specific agent.\n"); - printf("\t-u local Update syscheck database locally.\n\n"); + printf("\t-a Update (clear) syscheck database for all agents.\n"); + printf("\t-u Update (clear) syscheck database for a specific agent.\n"); + printf("\t-u local Update (clear) syscheck database locally.\n\n"); exit(1); } - /** main **/ int main(int argc, char **argv) { @@ -39,18 +39,18 @@ int main(int argc, char **argv) char *user = USER; int gid; int uid; - + /* Setting the name */ OS_SetName(ARGV0); - - + + /* user arguments */ if(argc < 2) { helpmsg(); } - + /* Getting the group name */ gid = Privsep_GetGroup(group); uid = Privsep_GetUser(user); @@ -59,14 +59,14 @@ int main(int argc, char **argv) ErrorExit(USER_ERROR, ARGV0, user, group); } - + /* Setting the group */ if(Privsep_SetGroup(gid) < 0) { ErrorExit(SETGID_ERROR,ARGV0, group); } - - + + /* Chrooting to the default directory */ if(Privsep_Chroot(dir) < 0) { @@ -76,14 +76,14 @@ int main(int argc, char **argv) /* Inside chroot now */ nowChroot(); - + /* Setting the user */ if(Privsep_SetUser(uid) < 0) { ErrorExit(SETUID_ERROR, ARGV0, user); } - + /* User options */ if(strcmp(argv[1], "-h") == 0) { @@ -91,7 +91,7 @@ int main(int argc, char **argv) } else if(strcmp(argv[1], "-l") == 0) { - printf("\nOSSEC HIDS %s: Updates the integrity check database.", + printf("\nOSSEC HIDS %s: Updates the integrity check database.", ARGV0); print_agents(0, 0, 0); printf("\n"); @@ -129,7 +129,7 @@ int main(int argc, char **argv) } snprintf(full_path, OS_MAXSTR,"%s/%s", SYSCHECK_DIR, entry->d_name); - + fp = fopen(full_path, "w"); if(fp) { @@ -142,7 +142,7 @@ int main(int argc, char **argv) } closedir(sys_dir); - printf("\n** Integrity check database updated.\n\n"); + printf("\n** Integrity check database updated.\n\n"); exit(0); } else @@ -151,14 +151,14 @@ int main(int argc, char **argv) helpmsg(); } - + /* local */ if(strcmp(argv[2],"local") == 0) { char final_dir[1024]; FILE *fp; snprintf(final_dir, 1020, "/%s/syscheck", SYSCHECK_DIR); - + fp = fopen(final_dir, "w"); if(fp) { @@ -169,7 +169,7 @@ int main(int argc, char **argv) /* Deleting cpt file */ snprintf(final_dir, 1020, "/%s/.syscheck.cpt", SYSCHECK_DIR); - + fp = fopen(final_dir, "w"); if(fp) { @@ -192,12 +192,12 @@ int main(int argc, char **argv) printf("\n** Invalid agent id '%s'.\n", argv[2]); helpmsg(); } - + /* Deleting syscheck */ delete_syscheck(keys.keyentries[i]->name,keys.keyentries[i]->ip->ip,0); } - - printf("\n** Integrity check database updated.\n\n"); + + printf("\n** Integrity check database updated.\n\n"); return(0); } diff --git a/src/util/verify-agent-conf.c b/src/util/verify-agent-conf.c index ee684d0..f76745e 100755 --- a/src/util/verify-agent-conf.c +++ b/src/util/verify-agent-conf.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/util/verify-agent-conf.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2010 Trend Micro Inc. * All right reserved. @@ -20,27 +21,81 @@ #define ARGV0 "verify-agent-conf" +/** help **/ +void helpmsg() +{ + printf("\nOSSEC HIDS %s: Verify agent.conf syntax for errors.\n", ARGV0); + printf("Usage: %s [-f ]\n\n", ARGV0); + printf("Available options:\n"); + printf("\t-h This help message.\n"); + printf("\t-f Full file name and path to config file to be tested.\n"); + printf("\t If this option is not specified the following default\n"); + printf("\t will be used.\n"); + printf(" "); + printf("\t Validation is successful, if no errors are shown.\n"); + exit(1); +} + /* main: v0.3: 2005/04/04 */ int main(int argc, char **argv) { + char* ar=AGENTCONFIG; + int c=0; int modules = 0; logreader_config log_config; /* Setting the name */ OS_SetName(ARGV0); - + + + /* printf ("Agrc [%d], Argv [%s]\n", argc, *argv); */ + + /* user arguments */ + if(argc > 1) + { + while((c = getopt(argc, argv, "Vdhf:")) != -1) + { + switch(c){ + case 'V': + print_version(); + break; + case 'h': + helpmsg(); + break; + case 'd': + nowDebug(); + break; + case 'f': + if(!optarg) + { + merror("%s: -f needs an argument",ARGV0); + helpmsg(); + } + ar = optarg; + break; + default: + helpmsg(); + break; + } + + } + } + + + + printf("\n%s: Verifying [%s].\n\n", ARGV0, ar); modules|= CLOCALFILE; modules|= CAGENT_CONFIG; log_config.config = NULL; - if(ReadConfig(modules, AGENTCONFIG, &log_config, NULL) < 0) + if(ReadConfig(modules, ar, &log_config, NULL) < 0) { return(OS_INVALID); } - logff = log_config.config; + logff = log_config.config; return(0); diff --git a/src/win32/add-localfile.c b/src/win32/add-localfile.c index afba5b6..8cf11e4 100755 --- a/src/win32/add-localfile.c +++ b/src/win32/add-localfile.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/win32/add-localfile.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation */ - + #include #include @@ -48,7 +49,7 @@ int dogrep(char *file, char *str) /* Clearing memory */ memset(line, '\0', OS_MAXSTR +1); - /* Reading file and looking for str */ + /* Reading file and looking for str */ while(fgets(line, OS_MAXSTR, fp) != NULL) { if(OS_Match(str, line)) @@ -67,13 +68,11 @@ int dogrep(char *file, char *str) /* Check is syscheck is present in the config */ int config_file(char *name, char *file, int quiet) { - int add = 0; - char ffile[256]; FILE *fp; ffile[255] = '\0'; - + /* Checking if the file has a variable format */ if(strchr(file, '%') != NULL) @@ -93,8 +92,8 @@ int config_file(char *name, char *file, int quiet) { strncpy(ffile, file, 255); } - - + + /* Looking for ffile */ if(!fileexist(ffile)) { @@ -104,26 +103,26 @@ int config_file(char *name, char *file, int quiet) } return(-1); } - + if(dogrep(OSSECCONF, file)) { - printf("%s: Log file already configured: '%s'.\n", + printf("%s: Log file already configured: '%s'.\n", name, file); return(0); } - - + + /* Add iis config config */ fp = fopen(OSSECCONF, "a"); if(!fp) { printf("%s: Unable to edit configuration file.\n", name); - return(0); + return(0); } - + printf("%s: Adding log file to be monitored: '%s'.\n", name,file); - fprintf(fp, "\r\n" - "\r\n" + fprintf(fp, "\r\n" + "\r\n" "\r\n" "\r\n" " \r\n" @@ -137,14 +136,14 @@ int config_file(char *name, char *file, int quiet) fclose(fp); return(0); - + } /* Setup windows after install */ int main(int argc, char **argv) { int quiet = 0; - + if(argc < 2) { printf("%s: Invalid syntax.\n", argv[0]); @@ -157,7 +156,7 @@ int main(int argc, char **argv) quiet = 1; } - + /* Checking if ossec was installed already */ if(!fileexist(OSSECCONF)) { @@ -168,6 +167,6 @@ int main(int argc, char **argv) { config_file(argv[0], argv[1], quiet); } - + return(0); } diff --git a/src/win32/extract-win-el.c b/src/win32/extract-win-el.c index 53ba5aa..ee4c98d 100755 --- a/src/win32/extract-win-el.c +++ b/src/win32/extract-win-el.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/win32/extract-win-el.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All right reserved. @@ -40,7 +41,7 @@ int el_last = 0; /** int startEL(char *app, os_el *el) - * Starts the event logging for each el + * Starts the event logging for each el */ int startEL(char *app, os_el *el) { @@ -48,7 +49,7 @@ int startEL(char *app, os_el *el) el->h = OpenEventLog(NULL, app); if(!el->h) { - return(0); + return(0); } el->name = app; @@ -59,7 +60,7 @@ int startEL(char *app, os_el *el) -/** char *el_getCategory(int category_id) +/** char *el_getCategory(int category_id) * Returns a string related to the category id of the log. */ char *el_getCategory(int category_id) @@ -93,7 +94,7 @@ char *el_getCategory(int category_id) /** int el_getEventDLL(char *evt_name, char *source, char *event) * Returns the event. */ -int el_getEventDLL(char *evt_name, char *source, char *event) +int el_getEventDLL(char *evt_name, char *source, char *event) { HKEY key; DWORD ret; @@ -102,21 +103,21 @@ int el_getEventDLL(char *evt_name, char *source, char *event) keyname[255] = '\0'; - snprintf(keyname, 254, - "System\\CurrentControlSet\\Services\\EventLog\\%s\\%s", - evt_name, + snprintf(keyname, 254, + "System\\CurrentControlSet\\Services\\EventLog\\%s\\%s", + evt_name, source); - /* Opening registry */ + /* Opening registry */ if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyname, 0, KEY_ALL_ACCESS, &key) != ERROR_SUCCESS) { - return(0); + return(0); } ret = MAX_PATH -1; - if (RegQueryValueEx(key, "EventMessageFile", NULL, + if (RegQueryValueEx(key, "EventMessageFile", NULL, NULL, (LPBYTE)event, &ret) != ERROR_SUCCESS) { event[0] = '\0'; @@ -129,11 +130,11 @@ int el_getEventDLL(char *evt_name, char *source, char *event) -/** char *el_getmessage() +/** char *el_getmessage() * Returns a descriptive message of the event. */ -char *el_getMessage(EVENTLOGRECORD *er, char *name, - char * source, LPTSTR *el_sstring) +char *el_getMessage(EVENTLOGRECORD *er, char *name, + char * source, LPTSTR *el_sstring) { DWORD fm_flags = 0; char tmp_str[257]; @@ -156,12 +157,12 @@ char *el_getMessage(EVENTLOGRECORD *er, char *name, /* Get the file name from the registry (stored on event) */ if(!el_getEventDLL(name, source, event)) { - return(NULL); - } + return(NULL); + } curr_str = event; - /* If our event has multiple libraries, try each one of them */ + /* If our event has multiple libraries, try each one of them */ while((next_str = strchr(curr_str, ';'))) { *next_str = '\0'; @@ -171,11 +172,11 @@ char *el_getMessage(EVENTLOGRECORD *er, char *name, hevt = LoadLibraryEx(tmp_str, NULL, DONT_RESOLVE_DLL_REFERENCES); if(hevt) { - if(!FormatMessage(fm_flags, hevt, er->EventID, + if(!FormatMessage(fm_flags, hevt, er->EventID, 0, (LPTSTR) &message, 0, el_sstring)) { - message = NULL; + message = NULL; } FreeLibrary(hevt); @@ -191,12 +192,12 @@ char *el_getMessage(EVENTLOGRECORD *er, char *name, hevt = LoadLibraryEx(tmp_str, NULL, DONT_RESOLVE_DLL_REFERENCES); if(hevt) { - int hr; - if(!(hr = FormatMessage(fm_flags, hevt, er->EventID, + int hr; + if(!(hr = FormatMessage(fm_flags, hevt, er->EventID, 0, (LPTSTR) &message, 0, el_sstring))) { - message = NULL; + message = NULL; } FreeLibrary(hevt); @@ -212,7 +213,7 @@ char *el_getMessage(EVENTLOGRECORD *er, char *name, /** void readel(os_el *el) * Reads the event log. - */ + */ void readel(os_el *el, int printit) { DWORD nstr; @@ -238,7 +239,7 @@ void readel(os_el *el, int printit) LPSTR el_sstring[57]; /* Er must point to the mbuffer */ - el->er = (EVENTLOGRECORD *) &mbuffer; + el->er = (EVENTLOGRECORD *) &mbuffer; /* Zeroing the last values */ el_string[1024] = '\0'; @@ -247,8 +248,8 @@ void readel(os_el *el, int printit) final_msg[1023] = '\0'; el_sstring[56] = NULL; - /* Reading the event log */ - while(ReadEventLog(el->h, + /* Reading the event log */ + while(ReadEventLog(el->h, EVENTLOG_FORWARDS_READ | EVENTLOG_SEQUENTIAL_READ, 0, el->er, BUFFER_SIZE -1, &read, &needed)) @@ -294,27 +295,27 @@ void readel(os_el *el, int printit) el_sstring[nstr] = (LPSTR)sstr; sstr = strchr( (LPSTR)sstr, '\0'); - sstr++; + sstr++; } /* Get a more descriptive message (if available) */ - descriptive_msg = el_getMessage(el->er, el->name, source, + descriptive_msg = el_getMessage(el->er, el->name, source, el_sstring); if(descriptive_msg != NULL) { /* Remove any \n or \r */ - tmp_str = descriptive_msg; + tmp_str = descriptive_msg; while((tmp_str = strchr(tmp_str, '\n'))) { *tmp_str = ' '; - tmp_str++; + tmp_str++; } - tmp_str = descriptive_msg; + tmp_str = descriptive_msg; while((tmp_str = strchr(tmp_str, '\r'))) { *tmp_str = ' '; - tmp_str++; + tmp_str++; } } } @@ -346,20 +347,20 @@ void readel(os_el *el, int printit) if(printit) { - DWORD _evtid = 65535; - int id = (int)el->er->EventID & _evtid; - - snprintf(final_msg, 1022, + DWORD _evtid = 65535; + int id = (int)el->er->EventID & _evtid; + + snprintf(final_msg, 1022, "%d WinEvtLog: %s: %s(%d): %s: %s(%s): %s", (int)el->er->TimeGenerated, el->name, - category, + category, id, source, el_user, el_domain, descriptive_msg != NULL?descriptive_msg:el_string); - + fprintf(fp, "%s\n", final_msg); } @@ -404,18 +405,18 @@ int main(int argc, char **argv) } else if((argc == 3)&&(strcmp(argv[1], "-f") == 0)) { - file = argv[2]; - } + file = argv[2]; + } else help(); - + fp = fopen(file, "w"); if(!fp) { printf("Unable to open file '%s'\n", file); exit(1); } - + win_startel("Application"); win_startel("System"); win_startel("Security"); diff --git a/src/win32/help.txt b/src/win32/help.txt index 71eb11e..fa7c992 100755 --- a/src/win32/help.txt +++ b/src/win32/help.txt @@ -1,8 +1,8 @@ -** OSSEC Windows Agent v2.5.1 ** -** Copyright (C) 2010 Trend Micro Inc. ** +** OSSEC Windows Agent v2.7 ** +** Copyright (C) 2012 Trend Micro Inc. ** -Thanks for installing 'OSSEC Windows Agent version 2.5.1'. Before you continue, +Thanks for installing 'OSSEC Windows Agent version 2.7'. Before you continue, make sure that you have an instance of the OSSEC server running and configured to accept this system as an agent. diff --git a/src/win32/make.bat b/src/win32/make.bat index d3984c4..d88c4d3 100755 --- a/src/win32/make.bat +++ b/src/win32/make.bat @@ -1,14 +1,14 @@ echo Making windows agent "C:\MinGW\bin\windres.exe" -i icofile.rc -o icon.o -"C:\MinGW\bin\gcc.exe" -o "ossec-agent" -Wall -DARGV0=\"ossec-agent\" -DCLIENT -DWIN32 -DOSSECHIDS icon.o os_regex/*.c os_net/*.c os_xml/*.c zlib-1.2.3/*.c config/*.c shared/*.c os_execd/*.c os_crypto/blowfish/*.c os_crypto/md5/*.c os_crypto/sha1/*.c os_crypto/md5_sha1/*.c os_crypto/shared/*.c rootcheck/*.c *.c -Iheaders/ -I./ -lwsock32 -"C:\MinGW\bin\gcc.exe" -o "ossec-rootcheck" -Wall -DARGV0=\"ossec-rootcheck\" -DCLIENT -DWIN32 icon.o os_regex/*.c os_net/*.c os_xml/*.c config/*.c shared/*.c win_service.c rootcheck/*.c -Iheaders/ -I./ -lwsock32 -"C:\MinGW\bin\gcc.exe" -o "manage_agents" -Wall -DARGV0=\"ossec-agent\" -DCLIENT -DWIN32 -DMA os_regex/*.c zlib-1.2.3/*.c os_zlib.c shared/*.c os_crypto/blowfish/*.c os_crypto/md5/*.c os_crypto/shared/*.c addagent/*.c -Iheaders/ -I./ -lwsock32 -"C:\MinGW\bin\gcc.exe" -o setup-windows -Wall os_regex/*.c -DARGV0=\"setup-windows\" -DCLIENT -DWIN32 win_service.c shared/file_op.c shared/debug_op.c setup/setup-win.c setup/setup-shared.c -Iheaders/ -I./ -lwsock32 -"C:\MinGW\bin\gcc.exe" -o setup-syscheck -Wall os_regex/*.c os_xml/*.c setup/setup-syscheck.c setup/setup-shared.c -I./ -Iheaders/ -"C:\MinGW\bin\gcc.exe" -o service-start -Wall icon.o os_regex/*.c setup/service-start.c -I./ -"C:\MinGW\bin\gcc.exe" -o service-stop -Wall os_regex/*.c setup/service-stop.c -I./ -"C:\MinGW\bin\gcc.exe" -o setup-iis -Wall os_regex/*.c setup/setup-iis.c -I./ -"C:\MinGW\bin\gcc.exe" -o add-localfile -Wall os_regex/*.c setup/add-localfile.c -I./ +"C:\MinGW\bin\gcc.exe" -o "ossec-agent" -Wall -DARGV0=\"ossec-agent\" -DCLIENT -DWIN32 -DOSSECHIDS icon.o os_regex/*.c os_net/*.c os_xml/*.c zlib-1.2.3/*.c config/*.c shared/*.c os_execd/*.c os_crypto/blowfish/*.c os_crypto/md5/*.c os_crypto/sha1/*.c os_crypto/md5_sha1/*.c os_crypto/shared/*.c rootcheck/*.c *.c -I. -Iheaders/ -lwsock32 +"C:\MinGW\bin\gcc.exe" -o "ossec-rootcheck" -Wall -DARGV0=\"ossec-rootcheck\" -DCLIENT -DWIN32 icon.o os_regex/*.c os_net/*.c os_xml/*.c config/*.c shared/*.c win_service.c rootcheck/*.c -Iheaders/ -I. -lwsock32 +"C:\MinGW\bin\gcc.exe" -o "manage_agents" -Wall -DARGV0=\"ossec-agent\" -DCLIENT -DWIN32 -DMA os_regex/*.c zlib-1.2.3/*.c os_zlib.c shared/*.c os_crypto/blowfish/*.c os_crypto/md5/*.c os_crypto/shared/*.c addagent/*.c -Iheaders/ -I. -lwsock32 +"C:\MinGW\bin\gcc.exe" -o setup-windows -Wall os_regex/*.c -DARGV0=\"setup-windows\" -DCLIENT -DWIN32 win_service.c shared/file_op.c shared/debug_op.c setup/setup-win.c setup/setup-shared.c -Iheaders/ -I. -lwsock32 +"C:\MinGW\bin\gcc.exe" -o setup-syscheck -Wall os_regex/*.c os_xml/*.c setup/setup-syscheck.c setup/setup-shared.c -I. -Iheaders/ +"C:\MinGW\bin\gcc.exe" -o service-start -Wall icon.o os_regex/*.c setup/service-start.c -I. +"C:\MinGW\bin\gcc.exe" -o service-stop -Wall os_regex/*.c setup/service-stop.c -I. +"C:\MinGW\bin\gcc.exe" -o setup-iis -Wall os_regex/*.c setup/setup-iis.c -I. +"C:\MinGW\bin\gcc.exe" -o add-localfile -Wall os_regex/*.c setup/add-localfile.c -I. cd ui\ make diff --git a/src/win32/make.sh b/src/win32/make.sh index 20784d6..d7f6813 100755 --- a/src/win32/make.sh +++ b/src/win32/make.sh @@ -1,15 +1,16 @@ echo Making windows agent -i586-mingw32msvc-windres -i icofile.rc -o icon.o -i586-mingw32msvc-gcc -o ossec-agent.exe -Wall -DARGV0=\"ossec-agent\" -DCLIENT -DWIN32 -DOSSECHIDS icon.o os_regex/*.c os_net/*.c os_xml/*.c zlib-1.2.3/*.c config/*.c shared/*.c os_execd/*.c os_crypto/blowfish/*.c os_crypto/md5/*.c os_crypto/sha1/*.c os_crypto/md5_sha1/*.c os_crypto/shared/*.c rootcheck/*.c *.c -Iheaders/ -I./ -lwsock32 -i586-mingw32msvc-gcc -o ossec-rootcheck.exe -Wall -DARGV0=\"ossec-rootcheck\" -DCLIENT -DWIN32 icon.o os_regex/*.c os_net/*.c os_xml/*.c config/*.c shared/*.c win_service.c rootcheck/*.c -Iheaders/ -I./ -lwsock32 -i586-mingw32msvc-gcc -o manage_agents.exe -Wall -DARGV0=\"ossec-agent\" -DCLIENT -DWIN32 -DMA os_regex/*.c zlib-1.2.3/*.c os_zlib.c shared/*.c os_crypto/blowfish/*.c os_crypto/md5/*.c os_crypto/shared/*.c addagent/*.c -Iheaders/ -I./ -lwsock32 -i586-mingw32msvc-gcc -o setup-windows.exe -Wall os_regex/*.c -DARGV0=\"setup-windows\" -DCLIENT -DWIN32 win_service.c shared/file_op.c shared/debug_op.c setup/setup-win.c setup/setup-shared.c -Iheaders/ -I./ -lwsock32 -i586-mingw32msvc-gcc -o setup-syscheck.exe -Wall os_regex/*.c os_xml/*.c setup/setup-syscheck.c setup/setup-shared.c -I./ -Iheaders/ -i586-mingw32msvc-gcc -o service-start.exe -Wall icon.o os_regex/*.c setup/service-start.c -I./ -i586-mingw32msvc-gcc -o service-stop.exe -Wall os_regex/*.c setup/service-stop.c -I./ -i586-mingw32msvc-gcc -o setup-iis.exe -Wall os_regex/*.c setup/setup-iis.c -I./ -i586-mingw32msvc-gcc -o add-localfile.exe -Wall os_regex/*.c setup/add-localfile.c -I./ +i686-pc-mingw32-windres -i icofile.rc -o icon.o +i686-pc-mingw32-gcc -o ossec-agent.exe -Wall -DARGV0=\"ossec-agent\" -DCLIENT -DWIN32 -DOSSECHIDS icon.o os_regex/*.c os_net/*.c os_xml/*.c zlib-1.2.3/*.c config/*.c shared/*.c os_execd/*.c os_crypto/blowfish/*.c os_crypto/md5/*.c os_crypto/sha1/*.c os_crypto/md5_sha1/*.c os_crypto/shared/*.c rootcheck/*.c *.c -Iheaders/ -I./ -lwsock32 +i686-pc-mingw32-gcc -o ossec-rootcheck.exe -Wall -DARGV0=\"ossec-rootcheck\" -DCLIENT -DWIN32 icon.o os_regex/*.c os_net/*.c os_xml/*.c config/*.c shared/*.c win_service.c rootcheck/*.c -Iheaders/ -I./ -lwsock32 +i686-pc-mingw32-gcc -o manage_agents.exe -Wall -DARGV0=\"ossec-agent\" -DCLIENT -DWIN32 -DMA os_regex/*.c zlib-1.2.3/*.c os_zlib.c shared/*.c os_crypto/blowfish/*.c os_crypto/md5/*.c os_crypto/shared/*.c addagent/*.c -Iheaders/ -I./ -lwsock32 +i686-pc-mingw32-gcc -o agent-auth.exe -Wall -DARGV0=\"agent-auth\" -DUSE_OPENSSL -DCLIENT -DWIN32 -DMA os_auth/main-client.c os_auth/ssl.c addagent/validate.c os_net/*.c os_regex/*.c zlib-1.2.3/*.c os_zlib.c shared/*.c os_crypto/blowfish/*.c os_crypto/md5/*.c os_crypto/shared/*.c -Iheaders/ -I./ -lwsock32 -lssl -lcrypto +i686-pc-mingw32-gcc -o setup-windows.exe -Wall os_regex/*.c -DARGV0=\"setup-windows\" -DCLIENT -DWIN32 win_service.c shared/file_op.c shared/debug_op.c setup/setup-win.c setup/setup-shared.c -Iheaders/ -I./ -lwsock32 +i686-pc-mingw32-gcc -o setup-syscheck.exe -Wall os_regex/*.c os_xml/*.c setup/setup-syscheck.c setup/setup-shared.c -I./ -Iheaders/ +i686-pc-mingw32-gcc -o service-start.exe -Wall icon.o os_regex/*.c setup/service-start.c -I./ +i686-pc-mingw32-gcc -o service-stop.exe -Wall os_regex/*.c setup/service-stop.c -I./ +i686-pc-mingw32-gcc -o setup-iis.exe -Wall os_regex/*.c setup/setup-iis.c -I./ +i686-pc-mingw32-gcc -o add-localfile.exe -Wall os_regex/*.c setup/add-localfile.c -I./ cd ui sh ./make.sh diff --git a/src/win32/os_win.h b/src/win32/os_win.h index ab5d4dd..70934f1 100755 --- a/src/win32/os_win.h +++ b/src/win32/os_win.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/win32/os_win.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -22,11 +23,11 @@ int InstallService(char *path); /** int UninstallService() * Uninstall the OSSEC HIDS agent service. */ -int UninstallService(); +int UninstallService(); -/** int QueryService(): - * Checks if service is running. +/** int QueryService(): + * Checks if service is running. * Return 1 on success (running) or 0 if not. */ int CheckServiceRunning(); diff --git a/src/win32/ossec-installer.nsi b/src/win32/ossec-installer.nsi index bd1e48c..9782200 100755 --- a/src/win32/ossec-installer.nsi +++ b/src/win32/ossec-installer.nsi @@ -8,12 +8,12 @@ !define MUI_ICON favicon.ico !define MUI_UNICON ossec-uninstall.ico -!define VERSION "2.5.1" +!define VERSION "2.7" !define NAME "OSSEC HIDS" !define /date CDATE "%b %d %Y at %H:%M:%S" Name "${NAME} Windows Agent v${VERSION}" -BrandingText "Copyright (C) 2010 Trend Micro Inc." +BrandingText "Copyright (C) 2012 Trend Micro Inc." OutFile "ossec-win32-agent.exe" InstallDir "$PROGRAMFILES\ossec-agent" diff --git a/src/win32/ossec.conf b/src/win32/ossec.conf index b9c2aee..6a943ea 100755 --- a/src/win32/ossec.conf +++ b/src/win32/ossec.conf @@ -95,7 +95,8 @@ %WINDIR%/System32/tftp.exe %WINDIR%/System32/tlntsvr.exe %WINDIR%/System32/drivers/etc - C:\Documents and Settings/All Users/Start Menu/Programs/Startup + C:\Documents and Settings/All Users/Start Menu/Programs/Startup + C:\Users/Public/All Users/Microsoft/Windows/Start Menu/Startup .log$|.htm$|.jpg$|.png$|.chm$|.pnf$|.evtx$ diff --git a/src/win32/read-registry.c b/src/win32/read-registry.c index b5f4d68..b946100 100755 --- a/src/win32/read-registry.c +++ b/src/win32/read-registry.c @@ -6,13 +6,13 @@ #define MAX_KEY_LENGTH 255 #define MAX_KEY 2048 #define MAX_VALUE_NAME 16383 - + char *(os_winreg_ignore_list[]) = {"SOFTWARE\\Classes","test123",NULL}; HKEY sub_tree; int os_winreg_open_key(char *subkey); -void os_winreg_querykey(HKEY hKey, char *p_key) +void os_winreg_querykey(HKEY hKey, char *p_key) { int i, rc; DWORD j; @@ -30,8 +30,8 @@ void os_winreg_querykey(HKEY hKey, char *p_key) DWORD value_count; /* Variables for RegEnumValue */ - TCHAR value_buffer[MAX_VALUE_NAME +1]; - TCHAR data_buffer[MAX_VALUE_NAME +1]; + TCHAR value_buffer[MAX_VALUE_NAME +1]; + TCHAR data_buffer[MAX_VALUE_NAME +1]; DWORD value_size; DWORD data_size; @@ -44,7 +44,7 @@ void os_winreg_querykey(HKEY hKey, char *p_key) class_name_b[MAX_PATH] = '\0'; sub_key_name_b[0] = '\0'; sub_key_name_b[MAX_KEY_LENGTH] = '\0'; - + /* We use the class_name, subkey_count and the value count. */ rc = RegQueryInfoKey(hKey, class_name_b, &class_name_s, NULL, @@ -63,21 +63,21 @@ void os_winreg_querykey(HKEY hKey, char *p_key) if(subkey_count) { /* We open each subkey and call open_key */ - for(i=0;i #include @@ -22,7 +23,7 @@ int main(int argc, char **argv) printf("%s: Attempting to start ossec.", argv[0]); system("net start OssecSvc"); - + system("pause"); return(0); } diff --git a/src/win32/service-stop.c b/src/win32/service-stop.c index 37c0a2d..1ffbb37 100644 --- a/src/win32/service-stop.c +++ b/src/win32/service-stop.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/win32/service-stop.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation */ - + #include #include @@ -22,7 +23,7 @@ int main(int argc, char **argv) printf("%s: Attempting to stop ossec.", argv[0]); system("net stop OssecSvc"); - + system("pause"); return(0); } diff --git a/src/win32/setup-iis.c b/src/win32/setup-iis.c index 7cdd1cf..bfe87d8 100755 --- a/src/win32/setup-iis.c +++ b/src/win32/setup-iis.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/win32/setup-iis.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation */ - + #include #include @@ -31,14 +32,14 @@ int total; int direxist(char *dir) { DIR *dp; - + /* Opening dir */ dp = opendir(dir); if(dp == NULL) return(0); - + closedir(dp); - return(1); + return(1); } @@ -68,7 +69,7 @@ int dogrep(char *file, char *str) /* Clearing memory */ memset(line, '\0', OS_MAXSTR +1); - /* Reading file and looking for str */ + /* Reading file and looking for str */ while(fgets(line, OS_MAXSTR, fp) != NULL) { if(OS_Match(str, line)) @@ -162,7 +163,7 @@ int config_iis(char *name, char *file, char *vfile) if(dogrep(OSSECCONF, vfile)) { - printf("%s: Log file already configured: '%s'.\n", + printf("%s: Log file already configured: '%s'.\n", name, vfile); return(1); } @@ -175,11 +176,11 @@ int config_iis(char *name, char *file, char *vfile) if(!fp) { printf("%s: Unable to edit configuration file.\n", name); - return(1); + return(1); } - fprintf(fp, "\r\n" - "\r\n" + fprintf(fp, "\r\n" + "\r\n" "\r\n" "\r\n" " \r\n" @@ -202,10 +203,10 @@ int main(int argc, char **argv) time_t tm; struct tm *p; - - char win_dir[2048]; - - + + char win_dir[2048]; + + if(argc >= 2) { if(chdir(argv[1]) != 0) @@ -214,7 +215,7 @@ int main(int argc, char **argv) return(0); } } - + /* Checking if ossec was installed already */ if(!fileexist(OSSECCONF)) { @@ -225,20 +226,20 @@ int main(int argc, char **argv) /* Getting todays day */ tm = time(NULL); p = localtime(&tm); - - total = 0; - printf("%s: Looking for IIS log files to monitor.\r\n", + total = 0; + + printf("%s: Looking for IIS log files to monitor.\r\n", argv[0]); - printf("%s: For more information: http://www.ossec.net/en/win.html\r\n", + printf("%s: For more information: http://www.ossec.net/en/win.html\r\n", argv[0]); printf("\r\n"); - - + + /* Getting windows directory */ get_win_dir(win_dir, sizeof(win_dir) -1); - - + + /* Looking for IIS log files */ while(i <= 254) { @@ -248,30 +249,30 @@ int main(int argc, char **argv) i++; /* Searching for NCSA */ - snprintf(lfile, - OS_MAXSTR, + snprintf(lfile, + OS_MAXSTR, "%s\\System32\\LogFiles\\W3SVC%d\\nc%02d%02d%02d.log", win_dir,i, (p->tm_year+1900)-2000, p->tm_mon+1, p->tm_mday); - snprintf(vfile, - OS_MAXSTR, + snprintf(vfile, + OS_MAXSTR, "%s\\System32\\LogFiles\\W3SVC%d\\nc%%y%%m%%d.log", win_dir, i); - + /* Try dir-based */ config_iis(argv[0], lfile, vfile); /* Searching for W3C extended */ - snprintf(lfile, - OS_MAXSTR, + snprintf(lfile, + OS_MAXSTR, "%s\\System32\\LogFiles\\W3SVC%d\\ex%02d%02d%02d.log", win_dir, i, (p->tm_year+1900)-2000, p->tm_mon+1, p->tm_mday); - - snprintf(vfile, - OS_MAXSTR, + + snprintf(vfile, + OS_MAXSTR, "%s\\System32\\LogFiles\\W3SVC%d\\ex%%y%%m%%d.log", win_dir, i); - + /* Try dir-based */ if(config_iis(argv[0], lfile, vfile) == 0) { @@ -283,13 +284,13 @@ int main(int argc, char **argv) /* Searching for FTP Extended format */ - snprintf(lfile, - OS_MAXSTR, + snprintf(lfile, + OS_MAXSTR, "%s\\System32\\LogFiles\\MSFTPSVC%d\\ex%02d%02d%02d.log", win_dir, i, (p->tm_year+1900)-2000, p->tm_mon+1, p->tm_mday); - - snprintf(vfile, - OS_MAXSTR, + + snprintf(vfile, + OS_MAXSTR, "%s\\System32\\LogFiles\\MSFTPSVC%d\\ex%%y%%m%%d.log", win_dir, i); if(config_iis(argv[0], lfile, vfile) == 0) @@ -302,13 +303,13 @@ int main(int argc, char **argv) /* Searching for IIS SMTP logs */ - snprintf(lfile, - OS_MAXSTR, + snprintf(lfile, + OS_MAXSTR, "%s\\System32\\LogFiles\\SMTPSVC%d\\ex%02d%02d%02d.log", win_dir, i, (p->tm_year+1900)-2000, p->tm_mon+1, p->tm_mday); - - snprintf(vfile, - OS_MAXSTR, + + snprintf(vfile, + OS_MAXSTR, "%s\\System32\\LogFiles\\SMTPSVC%d\\ex%%y%%m%%d.log", win_dir, i); if(config_iis(argv[0], lfile, vfile) == 0) @@ -325,6 +326,6 @@ int main(int argc, char **argv) printf("%s: No IIS log added. Look at the link above for more " "information.\r\n", argv[0]); } - + return(0); } diff --git a/src/win32/setup-shared.c b/src/win32/setup-shared.c index 081beaa..8b450ae 100755 --- a/src/win32/setup-shared.c +++ b/src/win32/setup-shared.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/win32/setup-shared.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation */ - + #include #include @@ -53,7 +54,7 @@ int dogrep(char *file, char *str) /* Clearing memory */ memset(line, '\0', OS_MAXSTR +1); - /* Reading file and looking for str */ + /* Reading file and looking for str */ while(fgets(line, OS_MAXSTR, fp) != NULL) { if(OS_Match(str, line)) diff --git a/src/win32/setup-shared.h b/src/win32/setup-shared.h index 5801f42..7fb1a15 100755 --- a/src/win32/setup-shared.h +++ b/src/win32/setup-shared.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/win32/setup-shared.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation */ - + #include #include diff --git a/src/win32/setup-syscheck.c b/src/win32/setup-syscheck.c index f27804d..c20bcfe 100755 --- a/src/win32/setup-syscheck.c +++ b/src/win32/setup-syscheck.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/win32/setup-syscheck.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation */ - + #include "setup-shared.h" #include "os_xml/os_xml.h" @@ -22,7 +23,7 @@ int main(int argc, char **argv) { char *status; char *(xml_syscheck_status[])={"ossec_config","syscheck","disabled", NULL}; - + if(argc < 3) { printf("%s: Invalid syntax.\n", argv[0]); diff --git a/src/win32/setup-win.c b/src/win32/setup-win.c index cee17ab..c31b9c4 100755 --- a/src/win32/setup-win.c +++ b/src/win32/setup-win.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/win32/setup-win.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation */ - + #include "setup-shared.h" @@ -22,19 +23,19 @@ int main(int argc, char **argv) printf("Try: '%s directory'\n\n", argv[0]); return(0); } - + /* Trying to chdir to ossec directory. */ if(chdir(argv[1]) != 0) { printf("%s: Invalid directory: '%s'.\n", argv[0], argv[1]); return(0); } - + /* Checking if ossec was installed already (upgrade) */ if(!fileexist(OSSECCONF)) { char cmd[OS_MAXSTR +1]; - + /* Copy default config to ossec.conf */ snprintf(cmd, OS_MAXSTR, "copy %s %s", OSSECDEF, OSSECCONF); system(cmd); @@ -44,7 +45,7 @@ int main(int argc, char **argv) /* Setting up local files */ system("add-localfile.exe \"C:\\Windows\\pfirewall.log\" --quiet"); system("add-localfile.exe \"C:\\Documents and Settings\\All Users\\Application Data\\Symantec\\Symantec AntiVirus Corporate Edition\\7.5\\Logs\\\%m\%d20\%y.log\" --quiet"); - + /* Configure ossec for automatic startup */ system("sc config OssecSvc start= auto"); @@ -53,7 +54,7 @@ int main(int argc, char **argv) /* Changing permissions. */ checkVista(); - + if(isVista) { char cmd[OS_MAXSTR +1]; @@ -78,7 +79,7 @@ int main(int argc, char **argv) /* Changing permissions. */ system("echo y|cacls * /T /G Administrators:f "); - + /* Copying them back. */ snprintf(cmd, OS_MAXSTR, "move ..\\os_win32ui.exe ."); system(cmd); diff --git a/src/win32/ui.nsi b/src/win32/ui.nsi index 277b96f..87e4c6d 100644 --- a/src/win32/ui.nsi +++ b/src/win32/ui.nsi @@ -2,13 +2,13 @@ ; my template correctly. !include "MUI.nsh" -!define VERSION "2.5.1" -!define NAME "Ossec HIDS" +!define VERSION "2.7" +!define NAME "OSSEC HIDS" !define /date CDATE "%b %d %Y at %H:%M:%S" Name "${NAME} Windows Agent v${VERSION}" -BrandingText "Copyright (C) 2010 Trend Micro Inc." +BrandingText "Copyright (C) 2011 Trend Micro Inc." OutFile "win32ui.exe" diff --git a/src/win32/ui/common.c b/src/win32/ui/common.c index e385a36..b714a9c 100644 --- a/src/win32/ui/common.c +++ b/src/win32/ui/common.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/win32/ui/common.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -26,11 +27,11 @@ int gen_server_info(HWND hwnd) { memset(ui_server_info, '\0', 2048 +1); - snprintf(ui_server_info, 2048, + snprintf(ui_server_info, 2048, "Agent: %s (%s) - %s\r\n\r\n" "Status: %s", - config_inst.agentname, - config_inst.agentid, + config_inst.agentname, + config_inst.agentid, config_inst.agentip, config_inst.status); @@ -41,14 +42,14 @@ int gen_server_info(HWND hwnd) SetDlgItemText(hwnd, UI_SERVER_TOP, config_inst.version); SetDlgItemText(hwnd, UI_SERVER_INFO, ui_server_info); } - + /* Initializing auth key */ SetDlgItemText(hwnd, UI_SERVER_AUTH, config_inst.key); /* Initializing server ip */ SetDlgItemText(hwnd, UI_SERVER_TEXT, config_inst.server); - SendMessage(hStatus, SB_SETTEXT, 0, (LPARAM)"http://www.ossec.net"); + SendMessage(hStatus, SB_SETTEXT, 0, (LPARAM)"http://www.ossec.net"); return(0); } @@ -193,7 +194,7 @@ void init_config() } - /* Testing for permission - this is a vista thing. + /* Testing for permission - this is a vista thing. * For some reason vista is not reporting the return codes * properly. */ @@ -217,7 +218,7 @@ void init_config() { config_inst.admin_access = 0; } - + fclose(fp); /* trying to open it to read. */ @@ -230,7 +231,7 @@ void init_config() { config_inst.admin_access = 0; } - + if(unlink(".test-file.tst")) { config_inst.admin_access = 0; @@ -249,7 +250,7 @@ int config_read(HWND hwnd) { char *tmp_str; - + /* Clearing config */ config_clear(); @@ -266,7 +267,7 @@ int config_read(HWND hwnd) /* Getting version/install date */ - config_inst.version = cat_file(VERSION_FILE, NULL); + config_inst.version = cat_file(VERSION_FILE, NULL); if(config_inst.version) { config_inst.install_date = strchr(config_inst.version, '-'); @@ -279,7 +280,7 @@ int config_read(HWND hwnd) /* Getting number of messages sent */ - tmp_str = cat_file(SENDER_FILE, NULL); + tmp_str = cat_file(SENDER_FILE, NULL); if(tmp_str) { unsigned long int tmp_val = 0; @@ -357,7 +358,7 @@ int config_read(HWND hwnd) /* Getting server ip */ if(!get_ossec_server()) { - if(config_inst.status == ST_MISSING_IMPORT) + if(strcmp(config_inst.status, ST_MISSING_IMPORT) == 0) { config_inst.status = ST_MISSING_ALL; } @@ -418,7 +419,7 @@ int get_ossec_server() free(str); str = NULL; } - + str = OS_GetOneContentforElement(&xml, xml_serverhost); if(str) { @@ -442,7 +443,7 @@ int get_ossec_server() /* Setting up final server name when not available */ config_inst.server = strdup(FL_NOSERVER); - + OS_ClearXML(&xml); return(0); @@ -455,7 +456,7 @@ int set_ossec_server(char *ip, HWND hwnd) char **xml_pt = NULL; char *(xml_serverip[])={"ossec_config","client","server-ip", NULL}; char *(xml_serverhost[])={"ossec_config","client","server-hostname", NULL}; - + /* Verifying IP Address */ if(OS_IsValidIP(ip, NULL) != 1) @@ -483,7 +484,7 @@ int set_ossec_server(char *ip, HWND hwnd) /* Reading the XML. Printing error and line number */ - if(OS_WriteXML(CONFIG, NEWCONFIG, xml_pt, + if(OS_WriteXML(CONFIG, NEWCONFIG, xml_pt, NULL, NULL, ip, 0) != 0) { MessageBox(hwnd, "Unable to set OSSEC Server IP Address.\r\n" diff --git a/src/win32/ui/make.sh b/src/win32/ui/make.sh index 3c2c6df..0c4d039 100755 --- a/src/win32/ui/make.sh +++ b/src/win32/ui/make.sh @@ -1,6 +1,6 @@ echo Making windows agent UI -i586-mingw32msvc-windres -o resource.o win32ui.rc -i586-mingw32msvc-gcc -o os_win32ui.exe -Wall -DARGV0=\"ossec-agent\" -DCLIENT -DWIN32 resource.o ../os_net/*.c ../os_xml/*.c ../addagent/b64.c ../shared/validate_op.c ../shared/debug_op.c ../win_service.c *.c -I../headers/ -I../ -lcomctl32 -mwindows -lwsock32 +i686-pc-mingw32-windres -o resource.o win32ui.rc +i686-pc-mingw32-gcc -o os_win32ui.exe -Wall -DARGV0=\"ossec-agent\" -DCLIENT -DWIN32 resource.o ../os_net/*.c ../os_xml/*.c ../addagent/b64.c ../shared/validate_op.c ../shared/debug_op.c ../win_service.c *.c -I../headers/ -I../ -lcomctl32 -mwindows -lwsock32 cp -pr os_win32ui.exe ../ cd ../ diff --git a/src/win32/ui/os_win32ui.c b/src/win32/ui/os_win32ui.c index 84f5010..e19b969 100644 --- a/src/win32/ui/os_win32ui.c +++ b/src/win32/ui/os_win32ui.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/win32/ui/os_win32ui.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -20,7 +21,7 @@ /* Dialog -- About OSSEC */ -BOOL CALLBACK AboutDlgProc(HWND hwnd, UINT Message, +BOOL CALLBACK AboutDlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) { switch(Message) @@ -53,7 +54,7 @@ BOOL CALLBACK DlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) { int ret_code = 0; - + switch(Message) { case WM_INITDIALOG: @@ -98,17 +99,17 @@ BOOL CALLBACK DlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) hStatus = CreateWindowEx(0, STATUSCLASSNAME, NULL, - WS_CHILD|WS_VISIBLE|SBARS_SIZEGRIP, + WS_CHILD|WS_VISIBLE|SBARS_SIZEGRIP, 0, 0, 0, 0, - hwnd, (HMENU)IDC_MAIN_STATUS, + hwnd, (HMENU)IDC_MAIN_STATUS, GetModuleHandle(NULL), NULL); - SendMessage(hStatus, SB_SETPARTS, - sizeof(statwidths)/sizeof(int), + SendMessage(hStatus, SB_SETPARTS, + sizeof(statwidths)/sizeof(int), (LPARAM)statwidths); SendMessage(hStatus, SB_SETTEXT, 0, (LPARAM)"http://www.ossec.net"); - + /* Initializing config */ config_read(hwnd); @@ -116,11 +117,11 @@ BOOL CALLBACK DlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) /* Setting the icons */ - SendMessage(hwnd, WM_SETICON, ICON_SMALL, - (LPARAM)LoadIcon(GetModuleHandle(NULL), + SendMessage(hwnd, WM_SETICON, ICON_SMALL, + (LPARAM)LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_OSSECICON))); - SendMessage(hwnd, WM_SETICON, ICON_BIG, - (LPARAM)LoadIcon(GetModuleHandle(NULL), + SendMessage(hwnd, WM_SETICON, ICON_BIG, + (LPARAM)LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_OSSECICON))); if(config_inst.admin_access == 0) @@ -130,7 +131,7 @@ BOOL CALLBACK DlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) "Admin access required.", MB_OK); break; } - + } break; @@ -152,10 +153,10 @@ BOOL CALLBACK DlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) break; } - /** Getting values from the user (if chosen save) + /** Getting values from the user (if chosen save) * We should probably create another function for it... **/ - + /* Getting server ip */ len = GetWindowTextLength(GetDlgItem(hwnd, UI_SERVER_TEXT)); if(len > 0) @@ -169,7 +170,7 @@ BOOL CALLBACK DlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) { exit(-1); } - + GetDlgItemText(hwnd, UI_SERVER_TEXT, buf, len + 1); /* If auth key changed, set it */ @@ -185,8 +186,8 @@ BOOL CALLBACK DlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) GlobalFree(buf); } } - - + + /* Getting auth key */ len = GetWindowTextLength(GetDlgItem(hwnd, UI_SERVER_AUTH)); if(len > 0) @@ -224,8 +225,8 @@ BOOL CALLBACK DlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) id = decd_buf; name = strchr(id, ' '); if(name) - { - *name = '\0'; + { + *name = '\0'; name++; ip = strchr(name, ' '); @@ -249,21 +250,21 @@ BOOL CALLBACK DlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) if(!ip) { MessageBox(hwnd, "Unable to import " - "authentication key. Invalid.", + "authentication key. Invalid.", "Error Saving.", MB_OK); } else { char mbox_msg[1024 +1]; mbox_msg[1024] = '\0'; - + snprintf(mbox_msg, 1024, "Adding key for:\r\n\r\n" - "Agent ID: %s\r\n" - "Agent Name: %s\r\n" + "Agent ID: %s\r\n" + "Agent Name: %s\r\n" "IP Address: %s\r\n", id, name, ip); - - ret = MessageBox(hwnd, mbox_msg, + + ret = MessageBox(hwnd, mbox_msg, "Confirm Importing Key", MB_OKCANCEL); if(ret == IDOK) { @@ -277,7 +278,7 @@ BOOL CALLBACK DlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) } } - + } /* Free used memory */ @@ -324,10 +325,10 @@ BOOL CALLBACK DlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) (LPARAM)"Auth key and server ip saved .."); } - } + } } break; - + case UI_MENU_MANAGE_EXIT: PostMessage(hwnd, WM_CLOSE, 0, 0); break; @@ -335,7 +336,7 @@ BOOL CALLBACK DlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) case UI_MENU_VIEW_LOGS: _spawnlp( _P_NOWAIT, "notepad", "notepad " OSSECLOGS, NULL ); break; - case UI_MENU_VIEW_CONFIG: + case UI_MENU_VIEW_CONFIG: _spawnlp( _P_NOWAIT, "notepad", "notepad " CONFIG, NULL ); break; case UI_MENU_HELP_HELP: @@ -343,17 +344,17 @@ BOOL CALLBACK DlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) break; case UI_MENU_HELP_ABOUT: { - DialogBox(GetModuleHandle(NULL), + DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_ABOUT), hwnd, AboutDlgProc); } break; case IDC_CANCEL: - config_read(hwnd); + config_read(hwnd); gen_server_info(hwnd); break; - + case UI_MENU_MANAGE_START: - + /* Starting OSSEC -- must have a valid config before. */ if((strcmp(config_inst.key, FL_NOKEY) != 0) && (strcmp(config_inst.server, FL_NOSERVER) != 0)) @@ -364,7 +365,7 @@ BOOL CALLBACK DlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) { ret_code = 0; } - + if(ret_code == 0) { MessageBox(hwnd, "Unable to start OSSEC (check config).", @@ -385,9 +386,9 @@ BOOL CALLBACK DlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) MessageBox(hwnd, "Agent already running (try restart).", "Already running..", MB_OK); } - break; + break; case UI_MENU_MANAGE_STOP: - + /* Stopping OSSEC */ ret_code = os_stop_service(); if(ret_code == 1) @@ -419,18 +420,18 @@ BOOL CALLBACK DlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) } break; case UI_MENU_MANAGE_RESTART: - + if((strcmp(config_inst.key, FL_NOKEY) == 0) || (strcmp(config_inst.server, FL_NOSERVER) == 0)) { MessageBox(hwnd, "Unable to restart OSSEC (check config).", "Error -- Unable to restart", MB_OK); break; - + } - + ret_code = os_stop_service(); - + /* Starting OSSEC */ ret_code = os_start_service(); if(ret_code == 0) @@ -447,14 +448,14 @@ BOOL CALLBACK DlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) MessageBox(hwnd, "OSSEC Agent Restarted.", "Restarted..", MB_OK); } - break; + break; } break; - + case WM_CLOSE: EndDialog(hwnd, 0); break; - + default: return FALSE; } diff --git a/src/win32/ui/os_win32ui.h b/src/win32/ui/os_win32ui.h index 5bd608f..eef7efc 100644 --- a/src/win32/ui/os_win32ui.h +++ b/src/win32/ui/os_win32ui.h @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/win32/ui/os_win32ui.h, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -49,7 +50,7 @@ #define ST_MISSING_ALL "Require import of authentication key.\r\n" \ " Missing OSSEC Server IP address.\r\n" \ " - Not Running..." - + /* Pre-def fields */ diff --git a/src/win32/ui/win32ui.rc b/src/win32/ui/win32ui.rc index 5f49da6..28e7d6d 100644 --- a/src/win32/ui/win32ui.rc +++ b/src/win32/ui/win32ui.rc @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/win32/ui/win32ui.rc, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. diff --git a/src/win32/win-files.txt b/src/win32/win-files.txt index 530daa6..45077f9 100755 --- a/src/win32/win-files.txt +++ b/src/win32/win-files.txt @@ -4,6 +4,7 @@ os_xml os_xml os_crypto os_crypto headers headers shared shared +os_auth os_auth error_messages error_messages addagent addagent config config diff --git a/src/win32/win_agent.c b/src/win32/win_agent.c index 0c01224..c2b80ca 100755 --- a/src/win32/win_agent.c +++ b/src/win32/win_agent.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/win32/win_agent.c, 2011/11/01 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -79,8 +80,8 @@ int main(int argc, char **argv) /* Find where I'm */ mypath[OS_MAXSTR] = '\0'; myfile[OS_MAXSTR] = '\0'; - - + + /* mypath is going to be the whole path of the file */ strncpy(mypath, argv[0], OS_MAXSTR); tmpstr = strrchr(mypath, '\\'); @@ -101,8 +102,8 @@ int main(int argc, char **argv) getcwd(mypath, OS_MAXSTR -1); strncat(mypath, "\\", OS_MAXSTR - (strlen(mypath) + 2)); strncat(mypath, myfile, OS_MAXSTR - (strlen(mypath) + 2)); - - + + if(argc > 1) { if(strcmp(argv[1], "install-service") == 0) @@ -147,6 +148,7 @@ int main(int argc, char **argv) int local_start() { int debug_level; + int accept_manager_commands = 0; char *cfg = DEFAULTCPATH; WSADATA wsaData; DWORD threadID; @@ -169,9 +171,12 @@ int local_start() nowDebug(); debug_level--; } - - - + accept_manager_commands = getDefine_Int("logcollector", + "remote_commands", 0, 1); + + + + /* Configuration file not present */ if(File_DateofChange(cfg) < 0) ErrorExit("%s: Configuration file '%s' not found",ARGV0,cfg); @@ -182,7 +187,7 @@ int local_start() { ErrorExit("%s: WSAStartup() failed", ARGV0); } - + /* Read agent config */ debug1("%s: DEBUG: Reading agent configuration.", ARGV0); @@ -194,7 +199,7 @@ int local_start() /* Reading logcollector config file */ debug1("%s: DEBUG: Reading logcollector configuration.", ARGV0); - if(LogCollectorConfig(cfg) < 0) + if(LogCollectorConfig(cfg, accept_manager_commands) < 0) { ErrorExit(CONFIG_ERROR, ARGV0, cfg); } @@ -205,7 +210,7 @@ int local_start() { ErrorExit(AG_NOKEYS_EXIT, ARGV0); } - + /* If there is not file to monitor, create a clean entry @@ -230,14 +235,14 @@ int local_start() { logr->execdq = -1; } - - + + /* Reading keys */ verbose(ENC_READ, ARGV0); - + OS_ReadKeys(&keys); OS_StartCounter(&keys); - os_write_agent_info(keys.keyentries[0]->name, NULL, keys.keyentries[0]->id); + os_write_agent_info(keys.keyentries[0]->name, NULL, keys.keyentries[0]->id, NULL); /* Initial random numbers */ @@ -261,47 +266,47 @@ int local_start() /* Starting syscheck thread */ - if(CreateThread(NULL, - 0, - (LPTHREAD_START_ROUTINE)skthread, - NULL, - 0, + if(CreateThread(NULL, + 0, + (LPTHREAD_START_ROUTINE)skthread, + NULL, + 0, (LPDWORD)&threadID) == NULL) { merror(THREAD_ERROR, ARGV0); } - + /* Checking if server is connected */ os_setwait(); - + start_agent(1); - + os_delwait(); /* Sending integrity message for agent configs */ intcheck_file(cfg, ""); intcheck_file(OSSEC_DEFINES, ""); - + /* Starting receiver thread */ - if(CreateThread(NULL, - 0, - (LPTHREAD_START_ROUTINE)receiver_thread, - NULL, - 0, + if(CreateThread(NULL, + 0, + (LPTHREAD_START_ROUTINE)receiver_thread, + NULL, + 0, (LPDWORD)&threadID2) == NULL) { merror(THREAD_ERROR, ARGV0); } - - + + /* Sending agent information message */ send_win32_info(time(0)); - - + + /* Startting logcollector -- main process here */ LogCollectorStart(); @@ -314,27 +319,27 @@ int local_start() int SendMSG(int queue, char *message, char *locmsg, char loc) { int _ssize; - + time_t cu_time; - + char *pl; char tmpstr[OS_MAXSTR+2]; char crypt_msg[OS_MAXSTR +2]; - - DWORD dwWaitResult; + + DWORD dwWaitResult; tmpstr[OS_MAXSTR +1] = '\0'; crypt_msg[OS_MAXSTR +1] = '\0'; debug2("%s: DEBUG: Attempting to send message to server.", ARGV0); - + /* Using a mutex to synchronize the writes */ while(1) { dwWaitResult = WaitForSingleObject(hMutex, 1000000L); - if(dwWaitResult != WAIT_OBJECT_0) + if(dwWaitResult != WAIT_OBJECT_0) { switch(dwWaitResult) { @@ -345,8 +350,8 @@ int SendMSG(int queue, char *message, char *locmsg, char loc) case WAIT_ABANDONED: merror("%s: Error waiting mutex (abandoned).", ARGV0); return(0); - default: - merror("%s: Error waiting mutex.", ARGV0); + default: + merror("%s: Error waiting mutex.", ARGV0); return(0); } } @@ -359,7 +364,7 @@ int SendMSG(int queue, char *message, char *locmsg, char loc) cu_time = time(0); - + #ifndef ONEWAY /* Check if the server has responded */ @@ -441,12 +446,12 @@ int SendMSG(int queue, char *message, char *locmsg, char loc) { int curr_rip = logr->rip_id; merror("%s: INFO: Trying next server ip in " - "line: '%s'.", + "line: '%s'.", ARGV0, logr->rip[logr->rip_id + 1] != NULL? logr->rip[logr->rip_id + 1]: logr->rip[0]); - + connect_server(logr->rip_id +1); if(logr->rip_id != curr_rip) @@ -474,7 +479,7 @@ int SendMSG(int queue, char *message, char *locmsg, char loc) } } - verbose(AG_CONNECTED, ARGV0, logr->rip[logr->rip_id], + verbose(AG_CONNECTED, ARGV0, logr->rip[logr->rip_id], logr->port); verbose(SERVER_UP, ARGV0); } @@ -495,7 +500,7 @@ int SendMSG(int queue, char *message, char *locmsg, char loc) } - + /* locmsg cannot have the C:, as we use it as delimiter */ pl = strchr(locmsg, ':'); if(pl) @@ -508,9 +513,9 @@ int SendMSG(int queue, char *message, char *locmsg, char loc) pl = locmsg; } - + debug2("%s: DEBUG: Sending message to server: '%s'", ARGV0, message); - + snprintf(tmpstr,OS_MAXSTR,"%c:%s:%s", loc, pl, message); _ssize = CreateSecMSG(&keys, tmpstr, crypt_msg, 0); @@ -522,9 +527,9 @@ int SendMSG(int queue, char *message, char *locmsg, char loc) merror(SEC_ERROR,ARGV0); if(!ReleaseMutex(hMutex)) { - merror("%s: Error releasing mutex.", ARGV0); + merror("%s: Error releasing mutex.", ARGV0); } - + return(-1); } @@ -539,7 +544,7 @@ int SendMSG(int queue, char *message, char *locmsg, char loc) { merror("%s: Error releasing mutex.", ARGV0); } - return(0); + return(0); } @@ -548,12 +553,12 @@ int StartMQ(char * path, short int type) { /* Connecting to the server. */ connect_server(0); - + if((path == NULL) && (type == 0)) { return(0); } - + return(0); } @@ -599,8 +604,8 @@ void send_win32_info(time_t curr_time) __win32_shared_time = __win32_curr_time; } - - + + /* get shared files */ if(!__win32_shared) { diff --git a/src/win32/win_service.c b/src/win32/win_service.c index d17d7b8..1989c4e 100755 --- a/src/win32/win_service.c +++ b/src/win32/win_service.c @@ -1,4 +1,5 @@ -/* @(#) $Id$ */ +/* @(#) $Id: ./src/win32/win_service.c, 2011/09/08 dcid Exp $ + */ /* Copyright (C) 2009 Trend Micro Inc. * All rights reserved. @@ -8,7 +9,7 @@ * License (version 2) as published by the FSF - Free Software * Foundation. * - * License details at the LICENSE file included with OSSEC or + * License details at the LICENSE file included with OSSEC or * online at: http://www.ossec.net/en/licensing.html */ @@ -24,8 +25,8 @@ #endif static LPTSTR g_lpszServiceName = "OssecSvc"; -static LPTSTR g_lpszServiceDisplayName = "OSSEC Hids"; -static LPTSTR g_lpszServiceDescription = "OSSEC Hids Windows Agent"; +static LPTSTR g_lpszServiceDisplayName = "OSSEC HIDS"; +static LPTSTR g_lpszServiceDescription = "OSSEC HIDS Windows Agent"; static SERVICE_STATUS ossecServiceStatus; static SERVICE_STATUS_HANDLE ossecServiceStatusHandle; @@ -62,7 +63,7 @@ int os_start_service() rc = -1; } } - + CloseServiceHandle(schService); } @@ -89,13 +90,13 @@ int os_stop_service() if(schService) { SERVICE_STATUS lpServiceStatus; - - if(ControlService(schService, + + if(ControlService(schService, SERVICE_CONTROL_STOP, &lpServiceStatus)) { rc = 1; } - + CloseServiceHandle(schService); } @@ -123,7 +124,7 @@ int CheckServiceRunning() { /* Checking status */ SERVICE_STATUS lpServiceStatus; - + if(QueryServiceStatus(schService, &lpServiceStatus)) { if(lpServiceStatus.dwCurrentState == SERVICE_RUNNING) @@ -133,14 +134,14 @@ int CheckServiceRunning() } CloseServiceHandle(schService); } - + CloseServiceHandle(schSCManager); } return(rc); } - + /* int InstallService() * Install the OSSEC HIDS agent service. */ @@ -151,17 +152,17 @@ int InstallService(char *path) SC_HANDLE schSCManager, schService; LPCTSTR lpszBinaryPathName = NULL; SERVICE_DESCRIPTION sdBuf; - + /* Cleaning up some variables */ buffer[MAX_PATH] = '\0'; - - + + /* Executable path -- it must be called with the * full path */ lpszBinaryPathName = path; - + /* Opening the services database */ schSCManager = OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS); @@ -171,7 +172,7 @@ int InstallService(char *path) } /* Creating the service */ - schService = CreateService(schSCManager, + schService = CreateService(schSCManager, g_lpszServiceName, g_lpszServiceDisplayName, SERVICE_ALL_ACCESS, @@ -180,7 +181,7 @@ int InstallService(char *path) SERVICE_ERROR_NORMAL, lpszBinaryPathName, NULL, NULL, NULL, NULL, NULL); - + if (schService == NULL) { goto install_error; @@ -192,7 +193,7 @@ int InstallService(char *path) { goto install_error; } - + CloseServiceHandle(schService); CloseServiceHandle(schSCManager); @@ -204,7 +205,7 @@ int InstallService(char *path) { char local_msg[1025]; LPVOID lpMsgBuf; - + memset(local_msg, 0, 1025); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | @@ -227,11 +228,11 @@ int InstallService(char *path) /* int UninstallService() * Uninstall the OSSEC HIDS agent service. */ -int UninstallService() +int UninstallService() { SC_HANDLE schSCManager, schService; - + /* Removing from the services database */ schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (schSCManager) @@ -256,7 +257,7 @@ int UninstallService() fprintf(stderr, " [%s] Error removing from " "the Services database.\n", ARGV0); - + return(0); } @@ -284,7 +285,7 @@ VOID WINAPI OssecServiceCtrlHandler(DWORD dwOpcode) } return; } - + /** void WinSetError() * Sets the error code in the services @@ -294,11 +295,11 @@ void WinSetError() OssecServiceCtrlHandler(SERVICE_CONTROL_STOP); } - + /** int os_WinMain(int argc, char **argv) * Initializes OSSEC dispatcher */ -int os_WinMain(int argc, char **argv) +int os_WinMain(int argc, char **argv) { SERVICE_TABLE_ENTRY steDispatchTable[] = { @@ -329,8 +330,8 @@ void WINAPI OssecServiceStart (DWORD argc, LPTSTR *argv) ossecServiceStatus.dwCheckPoint = 0; ossecServiceStatus.dwWaitHint = 0; - ossecServiceStatusHandle = - RegisterServiceCtrlHandler(g_lpszServiceName, + ossecServiceStatusHandle = + RegisterServiceCtrlHandler(g_lpszServiceName, OssecServiceCtrlHandler); if (ossecServiceStatusHandle == (SERVICE_STATUS_HANDLE)0)